]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - model_brush.c
Add THREADDISABLE define to make builds with whole threading system disabled.
[xonotic/darkplaces.git] / model_brush.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "curves.h"
26 #include "wad.h"
27
28
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
31 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
42 cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
43 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
44 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
45 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
46 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
47 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
48 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
49 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
50 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
51 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
52 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
53 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
54 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
55 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
56 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
57 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
58 cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
59 cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
60 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
61
62 static texture_t mod_q1bsp_texture_solid;
63 static texture_t mod_q1bsp_texture_sky;
64 static texture_t mod_q1bsp_texture_lava;
65 static texture_t mod_q1bsp_texture_slime;
66 static texture_t mod_q1bsp_texture_water;
67
68 void Mod_BrushInit(void)
69 {
70 //      Cvar_RegisterVariable(&r_subdivide_size);
71         Cvar_RegisterVariable(&mod_bsp_portalize);
72         Cvar_RegisterVariable(&r_novis);
73         Cvar_RegisterVariable(&r_nosurftextures);
74         Cvar_RegisterVariable(&r_subdivisions_tolerance);
75         Cvar_RegisterVariable(&r_subdivisions_mintess);
76         Cvar_RegisterVariable(&r_subdivisions_maxtess);
77         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
78         Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
79         Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
80         Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
81         Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
82         Cvar_RegisterVariable(&r_trippy);
83         Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
84         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
85         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
86         Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
87         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
88         Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
89         Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
90         Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
91         Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
92         Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
93         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
94         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
95         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
96         Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
97         Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
98         Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
99         Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
100         Cvar_RegisterVariable(&mod_collision_bih);
101         Cvar_RegisterVariable(&mod_recalculatenodeboxes);
102
103         // these games were made for older DP engines and are no longer
104         // maintained; use this hack to show their textures properly
105         if(gamemode == GAME_NEXUIZ)
106                 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
107
108         memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
109         strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
110         mod_q1bsp_texture_solid.surfaceflags = 0;
111         mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
112
113         mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
114         strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
115         mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
116         mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
117
118         mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
119         strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
120         mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
121         mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
122
123         mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
124         strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
125         mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
126         mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
127
128         mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
129         strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
130         mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
131         mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
132 }
133
134 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
135 {
136         mnode_t *node;
137
138         if (model == NULL)
139                 return NULL;
140
141         // LordHavoc: modified to start at first clip node,
142         // in other words: first node of the (sub)model
143         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
144         while (node->plane)
145                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
146
147         return (mleaf_t *)node;
148 }
149
150 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
151 {
152         int i;
153         mleaf_t *leaf;
154         leaf = Mod_Q1BSP_PointInLeaf(model, p);
155         if (leaf)
156         {
157                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
158                 if (i)
159                 {
160                         memcpy(out, leaf->ambient_sound_level, i);
161                         out += i;
162                         outsize -= i;
163                 }
164         }
165         if (outsize)
166                 memset(out, 0, outsize);
167 }
168
169 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
170 {
171         int numclusters = 0;
172         int nodestackindex = 0;
173         mnode_t *node, *nodestack[1024];
174         if (!model->brush.num_pvsclusters)
175                 return -1;
176         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
177         for (;;)
178         {
179 #if 1
180                 if (node->plane)
181                 {
182                         // node - recurse down the BSP tree
183                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
184                         if (sides < 3)
185                         {
186                                 if (sides == 0)
187                                         return -1; // ERROR: NAN bounding box!
188                                 // box is on one side of plane, take that path
189                                 node = node->children[sides-1];
190                         }
191                         else
192                         {
193                                 // box crosses plane, take one path and remember the other
194                                 if (nodestackindex < 1024)
195                                         nodestack[nodestackindex++] = node->children[0];
196                                 node = node->children[1];
197                         }
198                         continue;
199                 }
200                 else
201                 {
202                         // leaf - add clusterindex to list
203                         if (numclusters < maxclusters)
204                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
205                         numclusters++;
206                 }
207 #else
208                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
209                 {
210                         if (node->plane)
211                         {
212                                 if (nodestackindex < 1024)
213                                         nodestack[nodestackindex++] = node->children[0];
214                                 node = node->children[1];
215                                 continue;
216                         }
217                         else
218                         {
219                                 // leaf - add clusterindex to list
220                                 if (numclusters < maxclusters)
221                                         clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
222                                 numclusters++;
223                         }
224                 }
225 #endif
226                 // try another path we didn't take earlier
227                 if (nodestackindex == 0)
228                         break;
229                 node = nodestack[--nodestackindex];
230         }
231         // return number of clusters found (even if more than the maxclusters)
232         return numclusters;
233 }
234
235 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
236 {
237         int nodestackindex = 0;
238         mnode_t *node, *nodestack[1024];
239         if (!model->brush.num_pvsclusters)
240                 return true;
241         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
242         for (;;)
243         {
244 #if 1
245                 if (node->plane)
246                 {
247                         // node - recurse down the BSP tree
248                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
249                         if (sides < 3)
250                         {
251                                 if (sides == 0)
252                                         return -1; // ERROR: NAN bounding box!
253                                 // box is on one side of plane, take that path
254                                 node = node->children[sides-1];
255                         }
256                         else
257                         {
258                                 // box crosses plane, take one path and remember the other
259                                 if (nodestackindex < 1024)
260                                         nodestack[nodestackindex++] = node->children[0];
261                                 node = node->children[1];
262                         }
263                         continue;
264                 }
265                 else
266                 {
267                         // leaf - check cluster bit
268                         int clusterindex = ((mleaf_t *)node)->clusterindex;
269                         if (CHECKPVSBIT(pvs, clusterindex))
270                         {
271                                 // it is visible, return immediately with the news
272                                 return true;
273                         }
274                 }
275 #else
276                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
277                 {
278                         if (node->plane)
279                         {
280                                 if (nodestackindex < 1024)
281                                         nodestack[nodestackindex++] = node->children[0];
282                                 node = node->children[1];
283                                 continue;
284                         }
285                         else
286                         {
287                                 // leaf - check cluster bit
288                                 int clusterindex = ((mleaf_t *)node)->clusterindex;
289                                 if (CHECKPVSBIT(pvs, clusterindex))
290                                 {
291                                         // it is visible, return immediately with the news
292                                         return true;
293                                 }
294                         }
295                 }
296 #endif
297                 // nothing to see here, try another path we didn't take earlier
298                 if (nodestackindex == 0)
299                         break;
300                 node = nodestack[--nodestackindex];
301         }
302         // it is not visible
303         return false;
304 }
305
306 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
307 {
308         int nodestackindex = 0;
309         mnode_t *node, *nodestack[1024];
310         if (!model->brush.num_leafs)
311                 return true;
312         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
313         for (;;)
314         {
315 #if 1
316                 if (node->plane)
317                 {
318                         // node - recurse down the BSP tree
319                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
320                         if (sides < 3)
321                         {
322                                 if (sides == 0)
323                                         return -1; // ERROR: NAN bounding box!
324                                 // box is on one side of plane, take that path
325                                 node = node->children[sides-1];
326                         }
327                         else
328                         {
329                                 // box crosses plane, take one path and remember the other
330                                 if (nodestackindex < 1024)
331                                         nodestack[nodestackindex++] = node->children[0];
332                                 node = node->children[1];
333                         }
334                         continue;
335                 }
336                 else
337                 {
338                         // leaf - check cluster bit
339                         int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
340                         if (CHECKPVSBIT(pvs, clusterindex))
341                         {
342                                 // it is visible, return immediately with the news
343                                 return true;
344                         }
345                 }
346 #else
347                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
348                 {
349                         if (node->plane)
350                         {
351                                 if (nodestackindex < 1024)
352                                         nodestack[nodestackindex++] = node->children[0];
353                                 node = node->children[1];
354                                 continue;
355                         }
356                         else
357                         {
358                                 // leaf - check cluster bit
359                                 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
360                                 if (CHECKPVSBIT(pvs, clusterindex))
361                                 {
362                                         // it is visible, return immediately with the news
363                                         return true;
364                                 }
365                         }
366                 }
367 #endif
368                 // nothing to see here, try another path we didn't take earlier
369                 if (nodestackindex == 0)
370                         break;
371                 node = nodestack[--nodestackindex];
372         }
373         // it is not visible
374         return false;
375 }
376
377 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
378 {
379         int nodestackindex = 0;
380         mnode_t *node, *nodestack[1024];
381         if (!model->brush.num_leafs)
382                 return true;
383         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
384         for (;;)
385         {
386 #if 1
387                 if (node->plane)
388                 {
389                         // node - recurse down the BSP tree
390                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
391                         if (sides < 3)
392                         {
393                                 if (sides == 0)
394                                         return -1; // ERROR: NAN bounding box!
395                                 // box is on one side of plane, take that path
396                                 node = node->children[sides-1];
397                         }
398                         else
399                         {
400                                 // box crosses plane, take one path and remember the other
401                                 if (nodestackindex < 1024)
402                                         nodestack[nodestackindex++] = node->children[0];
403                                 node = node->children[1];
404                         }
405                         continue;
406                 }
407                 else
408                 {
409                         // leaf - check if it is visible
410                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
411                         {
412                                 // it is visible, return immediately with the news
413                                 return true;
414                         }
415                 }
416 #else
417                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
418                 {
419                         if (node->plane)
420                         {
421                                 if (nodestackindex < 1024)
422                                         nodestack[nodestackindex++] = node->children[0];
423                                 node = node->children[1];
424                                 continue;
425                         }
426                         else
427                         {
428                                 // leaf - check if it is visible
429                                 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
430                                 {
431                                         // it is visible, return immediately with the news
432                                         return true;
433                                 }
434                         }
435                 }
436 #endif
437                 // nothing to see here, try another path we didn't take earlier
438                 if (nodestackindex == 0)
439                         break;
440                 node = nodestack[--nodestackindex];
441         }
442         // it is not visible
443         return false;
444 }
445
446 typedef struct findnonsolidlocationinfo_s
447 {
448         vec3_t center;
449         vec3_t absmin, absmax;
450         vec_t radius;
451         vec3_t nudge;
452         vec_t bestdist;
453         dp_model_t *model;
454 }
455 findnonsolidlocationinfo_t;
456
457 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
458 {
459         int i, *tri;
460         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
461
462         tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
463         VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
464         VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
465         VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
466         VectorSubtract(vert[1], vert[0], edge[0]);
467         VectorSubtract(vert[2], vert[1], edge[1]);
468         CrossProduct(edge[1], edge[0], facenormal);
469         if (facenormal[0] || facenormal[1] || facenormal[2])
470         {
471                 VectorNormalize(facenormal);
472                 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
473                 if (f <= info->bestdist && f >= -info->bestdist)
474                 {
475                         VectorSubtract(vert[0], vert[2], edge[2]);
476                         VectorNormalize(edge[0]);
477                         VectorNormalize(edge[1]);
478                         VectorNormalize(edge[2]);
479                         CrossProduct(facenormal, edge[0], edgenormal[0]);
480                         CrossProduct(facenormal, edge[1], edgenormal[1]);
481                         CrossProduct(facenormal, edge[2], edgenormal[2]);
482                         // face distance
483                         if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
484                                         && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
485                                         && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
486                         {
487                                 // we got lucky, the center is within the face
488                                 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
489                                 if (dist < 0)
490                                 {
491                                         dist = -dist;
492                                         if (info->bestdist > dist)
493                                         {
494                                                 info->bestdist = dist;
495                                                 VectorScale(facenormal, (info->radius - -dist), info->nudge);
496                                         }
497                                 }
498                                 else
499                                 {
500                                         if (info->bestdist > dist)
501                                         {
502                                                 info->bestdist = dist;
503                                                 VectorScale(facenormal, (info->radius - dist), info->nudge);
504                                         }
505                                 }
506                         }
507                         else
508                         {
509                                 // check which edge or vertex the center is nearest
510                                 for (i = 0;i < 3;i++)
511                                 {
512                                         f = DotProduct(info->center, edge[i]);
513                                         if (f >= DotProduct(vert[0], edge[i])
514                                                         && f <= DotProduct(vert[1], edge[i]))
515                                         {
516                                                 // on edge
517                                                 VectorMA(info->center, -f, edge[i], point);
518                                                 dist = sqrt(DotProduct(point, point));
519                                                 if (info->bestdist > dist)
520                                                 {
521                                                         info->bestdist = dist;
522                                                         VectorScale(point, (info->radius / dist), info->nudge);
523                                                 }
524                                                 // skip both vertex checks
525                                                 // (both are further away than this edge)
526                                                 i++;
527                                         }
528                                         else
529                                         {
530                                                 // not on edge, check first vertex of edge
531                                                 VectorSubtract(info->center, vert[i], point);
532                                                 dist = sqrt(DotProduct(point, point));
533                                                 if (info->bestdist > dist)
534                                                 {
535                                                         info->bestdist = dist;
536                                                         VectorScale(point, (info->radius / dist), info->nudge);
537                                                 }
538                                         }
539                                 }
540                         }
541                 }
542         }
543 }
544
545 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
546 {
547         int surfacenum, k, *mark;
548         msurface_t *surface;
549         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
550         {
551                 surface = info->model->data_surfaces + *mark;
552                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
553                 {
554                         if(surface->deprecatedq3num_bboxstride > 0)
555                         {
556                                 int i, cnt, tri;
557                                 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
558                                 for(i = 0; i < cnt; ++i)
559                                 {
560                                         if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
561                                         {
562                                                 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
563                                                 {
564                                                         tri = i * surface->deprecatedq3num_bboxstride + k;
565                                                         if(tri >= surface->num_triangles)
566                                                                 break;
567                                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
568                                                 }
569                                         }
570                                 }
571                         }
572                         else
573                         {
574                                 for (k = 0;k < surface->num_triangles;k++)
575                                 {
576                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
577                                 }
578                         }
579                 }
580         }
581 }
582
583 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
584 {
585         if (node->plane)
586         {
587                 float f = PlaneDiff(info->center, node->plane);
588                 if (f >= -info->bestdist)
589                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
590                 if (f <= info->bestdist)
591                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
592         }
593         else
594         {
595                 if (((mleaf_t *)node)->numleafsurfaces)
596                         Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
597         }
598 }
599
600 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
601 {
602         int i;
603         findnonsolidlocationinfo_t info;
604         if (model == NULL)
605         {
606                 VectorCopy(in, out);
607                 return;
608         }
609         VectorCopy(in, info.center);
610         info.radius = radius;
611         info.model = model;
612         i = 0;
613         do
614         {
615                 VectorClear(info.nudge);
616                 info.bestdist = radius;
617                 VectorCopy(info.center, info.absmin);
618                 VectorCopy(info.center, info.absmax);
619                 info.absmin[0] -= info.radius + 1;
620                 info.absmin[1] -= info.radius + 1;
621                 info.absmin[2] -= info.radius + 1;
622                 info.absmax[0] += info.radius + 1;
623                 info.absmax[1] += info.radius + 1;
624                 info.absmax[2] += info.radius + 1;
625                 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
626                 VectorAdd(info.center, info.nudge, info.center);
627         }
628         while (info.bestdist < radius && ++i < 10);
629         VectorCopy(info.center, out);
630 }
631
632 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
633 {
634         switch(nativecontents)
635         {
636                 case CONTENTS_EMPTY:
637                         return 0;
638                 case CONTENTS_SOLID:
639                         return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
640                 case CONTENTS_WATER:
641                         return SUPERCONTENTS_WATER;
642                 case CONTENTS_SLIME:
643                         return SUPERCONTENTS_SLIME;
644                 case CONTENTS_LAVA:
645                         return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
646                 case CONTENTS_SKY:
647                         return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
648         }
649         return 0;
650 }
651
652 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
653 {
654         if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
655                 return CONTENTS_SOLID;
656         if (supercontents & SUPERCONTENTS_SKY)
657                 return CONTENTS_SKY;
658         if (supercontents & SUPERCONTENTS_LAVA)
659                 return CONTENTS_LAVA;
660         if (supercontents & SUPERCONTENTS_SLIME)
661                 return CONTENTS_SLIME;
662         if (supercontents & SUPERCONTENTS_WATER)
663                 return CONTENTS_WATER;
664         return CONTENTS_EMPTY;
665 }
666
667 typedef struct RecursiveHullCheckTraceInfo_s
668 {
669         // the hull we're tracing through
670         const hull_t *hull;
671
672         // the trace structure to fill in
673         trace_t *trace;
674
675         // start, end, and end - start (in model space)
676         double start[3];
677         double end[3];
678         double dist[3];
679 }
680 RecursiveHullCheckTraceInfo_t;
681
682 // 1/32 epsilon to keep floating point happy
683 #define DIST_EPSILON (0.03125)
684
685 #define HULLCHECKSTATE_EMPTY 0
686 #define HULLCHECKSTATE_SOLID 1
687 #define HULLCHECKSTATE_DONE 2
688
689 extern cvar_t collision_prefernudgedfraction;
690 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
691 {
692         // status variables, these don't need to be saved on the stack when
693         // recursing...  but are because this should be thread-safe
694         // (note: tracing against a bbox is not thread-safe, yet)
695         int ret;
696         mplane_t *plane;
697         double t1, t2;
698
699         // variables that need to be stored on the stack when recursing
700         mclipnode_t *node;
701         int side;
702         double midf, mid[3];
703
704         // LordHavoc: a goto!  everyone flee in terror... :)
705 loc0:
706         // check for empty
707         if (num < 0)
708         {
709                 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
710                 if (!t->trace->startfound)
711                 {
712                         t->trace->startfound = true;
713                         t->trace->startsupercontents |= num;
714                 }
715                 if (num & SUPERCONTENTS_LIQUIDSMASK)
716                         t->trace->inwater = true;
717                 if (num == 0)
718                         t->trace->inopen = true;
719                 if (num & SUPERCONTENTS_SOLID)
720                         t->trace->hittexture = &mod_q1bsp_texture_solid;
721                 else if (num & SUPERCONTENTS_SKY)
722                         t->trace->hittexture = &mod_q1bsp_texture_sky;
723                 else if (num & SUPERCONTENTS_LAVA)
724                         t->trace->hittexture = &mod_q1bsp_texture_lava;
725                 else if (num & SUPERCONTENTS_SLIME)
726                         t->trace->hittexture = &mod_q1bsp_texture_slime;
727                 else
728                         t->trace->hittexture = &mod_q1bsp_texture_water;
729                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
730                 t->trace->hitsupercontents = num;
731                 if (num & t->trace->hitsupercontentsmask)
732                 {
733                         // if the first leaf is solid, set startsolid
734                         if (t->trace->allsolid)
735                                 t->trace->startsolid = true;
736 #if COLLISIONPARANOID >= 3
737                         Con_Print("S");
738 #endif
739                         return HULLCHECKSTATE_SOLID;
740                 }
741                 else
742                 {
743                         t->trace->allsolid = false;
744 #if COLLISIONPARANOID >= 3
745                         Con_Print("E");
746 #endif
747                         return HULLCHECKSTATE_EMPTY;
748                 }
749         }
750
751         // find the point distances
752         node = t->hull->clipnodes + num;
753
754         plane = t->hull->planes + node->planenum;
755         if (plane->type < 3)
756         {
757                 t1 = p1[plane->type] - plane->dist;
758                 t2 = p2[plane->type] - plane->dist;
759         }
760         else
761         {
762                 t1 = DotProduct (plane->normal, p1) - plane->dist;
763                 t2 = DotProduct (plane->normal, p2) - plane->dist;
764         }
765
766         if (t1 < 0)
767         {
768                 if (t2 < 0)
769                 {
770 #if COLLISIONPARANOID >= 3
771                         Con_Print("<");
772 #endif
773                         num = node->children[1];
774                         goto loc0;
775                 }
776                 side = 1;
777         }
778         else
779         {
780                 if (t2 >= 0)
781                 {
782 #if COLLISIONPARANOID >= 3
783                         Con_Print(">");
784 #endif
785                         num = node->children[0];
786                         goto loc0;
787                 }
788                 side = 0;
789         }
790
791         // the line intersects, find intersection point
792         // LordHavoc: this uses the original trace for maximum accuracy
793 #if COLLISIONPARANOID >= 3
794         Con_Print("M");
795 #endif
796         if (plane->type < 3)
797         {
798                 t1 = t->start[plane->type] - plane->dist;
799                 t2 = t->end[plane->type] - plane->dist;
800         }
801         else
802         {
803                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
804                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
805         }
806
807         midf = t1 / (t1 - t2);
808         midf = bound(p1f, midf, p2f);
809         VectorMA(t->start, midf, t->dist, mid);
810
811         // recurse both sides, front side first
812         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
813         // if this side is not empty, return what it is (solid or done)
814         if (ret != HULLCHECKSTATE_EMPTY)
815                 return ret;
816
817         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
818         // if other side is not solid, return what it is (empty or done)
819         if (ret != HULLCHECKSTATE_SOLID)
820                 return ret;
821
822         // front is air and back is solid, this is the impact point...
823         if (side)
824         {
825                 t->trace->plane.dist = -plane->dist;
826                 VectorNegate (plane->normal, t->trace->plane.normal);
827         }
828         else
829         {
830                 t->trace->plane.dist = plane->dist;
831                 VectorCopy (plane->normal, t->trace->plane.normal);
832         }
833
834         // calculate the true fraction
835         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
836         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
837         midf = t1 / (t1 - t2);
838         t->trace->realfraction = bound(0, midf, 1);
839
840         // calculate the return fraction which is nudged off the surface a bit
841         midf = (t1 - DIST_EPSILON) / (t1 - t2);
842         t->trace->fraction = bound(0, midf, 1);
843
844         if (collision_prefernudgedfraction.integer)
845                 t->trace->realfraction = t->trace->fraction;
846
847 #if COLLISIONPARANOID >= 3
848         Con_Print("D");
849 #endif
850         return HULLCHECKSTATE_DONE;
851 }
852
853 //#if COLLISIONPARANOID < 2
854 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
855 {
856         mplane_t *plane;
857         mclipnode_t *nodes = t->hull->clipnodes;
858         mplane_t *planes = t->hull->planes;
859         vec3_t point;
860         VectorCopy(t->start, point);
861         while (num >= 0)
862         {
863                 plane = planes + nodes[num].planenum;
864                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
865         }
866         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
867         t->trace->startsupercontents |= num;
868         if (num & SUPERCONTENTS_LIQUIDSMASK)
869                 t->trace->inwater = true;
870         if (num == 0)
871                 t->trace->inopen = true;
872         if (num & t->trace->hitsupercontentsmask)
873         {
874                 t->trace->allsolid = t->trace->startsolid = true;
875                 return HULLCHECKSTATE_SOLID;
876         }
877         else
878         {
879                 t->trace->allsolid = t->trace->startsolid = false;
880                 return HULLCHECKSTATE_EMPTY;
881         }
882 }
883 //#endif
884
885 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
886 {
887         RecursiveHullCheckTraceInfo_t rhc;
888
889         memset(&rhc, 0, sizeof(rhc));
890         memset(trace, 0, sizeof(trace_t));
891         rhc.trace = trace;
892         rhc.trace->fraction = 1;
893         rhc.trace->realfraction = 1;
894         rhc.trace->allsolid = true;
895         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
896         VectorCopy(start, rhc.start);
897         VectorCopy(start, rhc.end);
898         Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
899 }
900
901 static void Mod_Q1BSP_TraceLine(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
902 {
903         RecursiveHullCheckTraceInfo_t rhc;
904
905         if (VectorCompare(start, end))
906         {
907                 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
908                 return;
909         }
910
911         memset(&rhc, 0, sizeof(rhc));
912         memset(trace, 0, sizeof(trace_t));
913         rhc.trace = trace;
914         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
915         rhc.trace->fraction = 1;
916         rhc.trace->realfraction = 1;
917         rhc.trace->allsolid = true;
918         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
919         VectorCopy(start, rhc.start);
920         VectorCopy(end, rhc.end);
921         VectorSubtract(rhc.end, rhc.start, rhc.dist);
922 #if COLLISIONPARANOID >= 2
923         Con_Printf("t(%f %f %f,%f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2]);
924         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
925         {
926
927                 double test[3];
928                 trace_t testtrace;
929                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
930                 memset(&testtrace, 0, sizeof(trace_t));
931                 rhc.trace = &testtrace;
932                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
933                 rhc.trace->fraction = 1;
934                 rhc.trace->realfraction = 1;
935                 rhc.trace->allsolid = true;
936                 VectorCopy(test, rhc.start);
937                 VectorCopy(test, rhc.end);
938                 VectorClear(rhc.dist);
939                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
940                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
941                 if (!trace->startsolid && testtrace.startsolid)
942                         Con_Printf(" - ended in solid!\n");
943         }
944         Con_Print("\n");
945 #else
946         if (VectorLength2(rhc.dist))
947                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
948         else
949                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
950 #endif
951 }
952
953 static void Mod_Q1BSP_TraceBox(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
954 {
955         // this function currently only supports same size start and end
956         double boxsize[3];
957         RecursiveHullCheckTraceInfo_t rhc;
958
959         if (VectorCompare(boxmins, boxmaxs))
960         {
961                 if (VectorCompare(start, end))
962                         Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
963                 else
964                         Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
965                 return;
966         }
967
968         memset(&rhc, 0, sizeof(rhc));
969         memset(trace, 0, sizeof(trace_t));
970         rhc.trace = trace;
971         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
972         rhc.trace->fraction = 1;
973         rhc.trace->realfraction = 1;
974         rhc.trace->allsolid = true;
975         VectorSubtract(boxmaxs, boxmins, boxsize);
976         if (boxsize[0] < 3)
977                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
978         else if (model->brush.ishlbsp)
979         {
980                 // LordHavoc: this has to have a minor tolerance (the .1) because of
981                 // minor float precision errors from the box being transformed around
982                 if (boxsize[0] < 32.1)
983                 {
984                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
985                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
986                         else
987                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
988                 }
989                 else
990                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
991         }
992         else
993         {
994                 // LordHavoc: this has to have a minor tolerance (the .1) because of
995                 // minor float precision errors from the box being transformed around
996                 if (boxsize[0] < 32.1)
997                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
998                 else
999                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1000         }
1001         VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1002         VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1003         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1004 #if COLLISIONPARANOID >= 2
1005         Con_Printf("t(%f %f %f,%f %f %f,%i %f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2], rhc.hull - model->brushq1.hulls, rhc.hull->clip_mins[0], rhc.hull->clip_mins[1], rhc.hull->clip_mins[2]);
1006         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1007         {
1008
1009                 double test[3];
1010                 trace_t testtrace;
1011                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1012                 memset(&testtrace, 0, sizeof(trace_t));
1013                 rhc.trace = &testtrace;
1014                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1015                 rhc.trace->fraction = 1;
1016                 rhc.trace->realfraction = 1;
1017                 rhc.trace->allsolid = true;
1018                 VectorCopy(test, rhc.start);
1019                 VectorCopy(test, rhc.end);
1020                 VectorClear(rhc.dist);
1021                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1022                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1023                 if (!trace->startsolid && testtrace.startsolid)
1024                         Con_Printf(" - ended in solid!\n");
1025         }
1026         Con_Print("\n");
1027 #else
1028         if (VectorLength2(rhc.dist))
1029                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1030         else
1031                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1032 #endif
1033 }
1034
1035 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1036 {
1037         int num = model->brushq1.hulls[0].firstclipnode;
1038         mplane_t *plane;
1039         mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1040         mplane_t *planes = model->brushq1.hulls[0].planes;
1041         while (num >= 0)
1042         {
1043                 plane = planes + nodes[num].planenum;
1044                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1045         }
1046         return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1047 }
1048
1049 void Collision_ClipTrace_Box(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1050 {
1051 #if 1
1052         colbrushf_t cbox;
1053         colplanef_t cbox_planes[6];
1054         cbox.isaabb = true;
1055         cbox.hasaabbplanes = true;
1056         cbox.supercontents = boxsupercontents;
1057         cbox.numplanes = 6;
1058         cbox.numpoints = 0;
1059         cbox.numtriangles = 0;
1060         cbox.planes = cbox_planes;
1061         cbox.points = NULL;
1062         cbox.elements = NULL;
1063         cbox.markframe = 0;
1064         cbox.mins[0] = 0;
1065         cbox.mins[1] = 0;
1066         cbox.mins[2] = 0;
1067         cbox.maxs[0] = 0;
1068         cbox.maxs[1] = 0;
1069         cbox.maxs[2] = 0;
1070         cbox_planes[0].normal[0] =  1;cbox_planes[0].normal[1] =  0;cbox_planes[0].normal[2] =  0;cbox_planes[0].dist = cmaxs[0] - mins[0];
1071         cbox_planes[1].normal[0] = -1;cbox_planes[1].normal[1] =  0;cbox_planes[1].normal[2] =  0;cbox_planes[1].dist = maxs[0] - cmins[0];
1072         cbox_planes[2].normal[0] =  0;cbox_planes[2].normal[1] =  1;cbox_planes[2].normal[2] =  0;cbox_planes[2].dist = cmaxs[1] - mins[1];
1073         cbox_planes[3].normal[0] =  0;cbox_planes[3].normal[1] = -1;cbox_planes[3].normal[2] =  0;cbox_planes[3].dist = maxs[1] - cmins[1];
1074         cbox_planes[4].normal[0] =  0;cbox_planes[4].normal[1] =  0;cbox_planes[4].normal[2] =  1;cbox_planes[4].dist = cmaxs[2] - mins[2];
1075         cbox_planes[5].normal[0] =  0;cbox_planes[5].normal[1] =  0;cbox_planes[5].normal[2] = -1;cbox_planes[5].dist = maxs[2] - cmins[2];
1076         cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1077         cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1078         cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1079         cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1080         cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1081         cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1082         memset(trace, 0, sizeof(trace_t));
1083         trace->hitsupercontentsmask = hitsupercontentsmask;
1084         trace->fraction = 1;
1085         trace->realfraction = 1;
1086         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1087 #else
1088         RecursiveHullCheckTraceInfo_t rhc;
1089         static hull_t box_hull;
1090         static mclipnode_t box_clipnodes[6];
1091         static mplane_t box_planes[6];
1092         // fill in a default trace
1093         memset(&rhc, 0, sizeof(rhc));
1094         memset(trace, 0, sizeof(trace_t));
1095         //To keep everything totally uniform, bounding boxes are turned into small
1096         //BSP trees instead of being compared directly.
1097         // create a temp hull from bounding box sizes
1098         box_planes[0].dist = cmaxs[0] - mins[0];
1099         box_planes[1].dist = cmins[0] - maxs[0];
1100         box_planes[2].dist = cmaxs[1] - mins[1];
1101         box_planes[3].dist = cmins[1] - maxs[1];
1102         box_planes[4].dist = cmaxs[2] - mins[2];
1103         box_planes[5].dist = cmins[2] - maxs[2];
1104 #if COLLISIONPARANOID >= 3
1105         Con_Printf("box_planes %f:%f %f:%f %f:%f\ncbox %f %f %f:%f %f %f\nbox %f %f %f:%f %f %f\n", box_planes[0].dist, box_planes[1].dist, box_planes[2].dist, box_planes[3].dist, box_planes[4].dist, box_planes[5].dist, cmins[0], cmins[1], cmins[2], cmaxs[0], cmaxs[1], cmaxs[2], mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
1106 #endif
1107
1108         if (box_hull.clipnodes == NULL)
1109         {
1110                 int i, side;
1111
1112                 //Set up the planes and clipnodes so that the six floats of a bounding box
1113                 //can just be stored out and get a proper hull_t structure.
1114
1115                 box_hull.clipnodes = box_clipnodes;
1116                 box_hull.planes = box_planes;
1117                 box_hull.firstclipnode = 0;
1118                 box_hull.lastclipnode = 5;
1119
1120                 for (i = 0;i < 6;i++)
1121                 {
1122                         box_clipnodes[i].planenum = i;
1123
1124                         side = i&1;
1125
1126                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1127                         if (i != 5)
1128                                 box_clipnodes[i].children[side^1] = i + 1;
1129                         else
1130                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1131
1132                         box_planes[i].type = i>>1;
1133                         box_planes[i].normal[i>>1] = 1;
1134                 }
1135         }
1136
1137         // trace a line through the generated clipping hull
1138         //rhc.boxsupercontents = boxsupercontents;
1139         rhc.hull = &box_hull;
1140         rhc.trace = trace;
1141         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1142         rhc.trace->fraction = 1;
1143         rhc.trace->realfraction = 1;
1144         rhc.trace->allsolid = true;
1145         VectorCopy(start, rhc.start);
1146         VectorCopy(end, rhc.end);
1147         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1148         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1149         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1150         if (rhc.trace->startsupercontents)
1151                 rhc.trace->startsupercontents = boxsupercontents;
1152 #endif
1153 }
1154
1155 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1156 {
1157         memset(trace, 0, sizeof(trace_t));
1158         trace->fraction = 1;
1159         trace->realfraction = 1;
1160         if (BoxesOverlap(start, start, cmins, cmaxs))
1161         {
1162                 trace->startsupercontents |= boxsupercontents;
1163                 if (hitsupercontentsmask & boxsupercontents)
1164                 {
1165                         trace->startsolid = true;
1166                         trace->allsolid = true;
1167                 }
1168         }
1169 }
1170
1171 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1172 {
1173         trace_t trace;
1174         Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1175         return trace.fraction == 1;
1176 }
1177
1178 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(dp_model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1179 {
1180         int side;
1181         float front, back;
1182         float mid, distz = endz - startz;
1183
1184 loc0:
1185         if (!node->plane)
1186                 return false;           // didn't hit anything
1187
1188         switch (node->plane->type)
1189         {
1190         case PLANE_X:
1191                 node = node->children[x < node->plane->dist];
1192                 goto loc0;
1193         case PLANE_Y:
1194                 node = node->children[y < node->plane->dist];
1195                 goto loc0;
1196         case PLANE_Z:
1197                 side = startz < node->plane->dist;
1198                 if ((endz < node->plane->dist) == side)
1199                 {
1200                         node = node->children[side];
1201                         goto loc0;
1202                 }
1203                 // found an intersection
1204                 mid = node->plane->dist;
1205                 break;
1206         default:
1207                 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1208                 front += startz * node->plane->normal[2];
1209                 back += endz * node->plane->normal[2];
1210                 side = front < node->plane->dist;
1211                 if ((back < node->plane->dist) == side)
1212                 {
1213                         node = node->children[side];
1214                         goto loc0;
1215                 }
1216                 // found an intersection
1217                 mid = startz + distz * (front - node->plane->dist) / (front - back);
1218                 break;
1219         }
1220
1221         // go down front side
1222         if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1223                 return true;    // hit something
1224         else
1225         {
1226                 // check for impact on this node
1227                 if (node->numsurfaces)
1228                 {
1229                         int i, dsi, dti, lmwidth, lmheight;
1230                         float ds, dt;
1231                         msurface_t *surface;
1232                         unsigned char *lightmap;
1233                         int maps, line3, size3;
1234                         float dsfrac;
1235                         float dtfrac;
1236                         float scale, w, w00, w01, w10, w11;
1237
1238                         surface = model->data_surfaces + node->firstsurface;
1239                         for (i = 0;i < node->numsurfaces;i++, surface++)
1240                         {
1241                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1242                                         continue;       // no lightmaps
1243
1244                                 // location we want to sample in the lightmap
1245                                 ds = ((x * surface->lightmapinfo->texinfo->vecs[0][0] + y * surface->lightmapinfo->texinfo->vecs[0][1] + mid * surface->lightmapinfo->texinfo->vecs[0][2] + surface->lightmapinfo->texinfo->vecs[0][3]) - surface->lightmapinfo->texturemins[0]) * 0.0625f;
1246                                 dt = ((x * surface->lightmapinfo->texinfo->vecs[1][0] + y * surface->lightmapinfo->texinfo->vecs[1][1] + mid * surface->lightmapinfo->texinfo->vecs[1][2] + surface->lightmapinfo->texinfo->vecs[1][3]) - surface->lightmapinfo->texturemins[1]) * 0.0625f;
1247
1248                                 // check the bounds
1249                                 dsi = (int)ds;
1250                                 dti = (int)dt;
1251                                 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1252                                 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1253
1254                                 // is it in bounds?
1255                                 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1256                                 {
1257                                         // calculate bilinear interpolation factors
1258                                         // and also multiply by fixedpoint conversion factors
1259                                         dsfrac = ds - dsi;
1260                                         dtfrac = dt - dti;
1261                                         w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1262                                         w01 = (    dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1263                                         w10 = (1 - dsfrac) * (    dtfrac) * (1.0f / 32768.0f);
1264                                         w11 = (    dsfrac) * (    dtfrac) * (1.0f / 32768.0f);
1265
1266                                         // values for pointer math
1267                                         line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1268                                         size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1269
1270                                         // look up the pixel
1271                                         lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1272
1273                                         // bilinear filter each lightmap style, and sum them
1274                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1275                                         {
1276                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1277                                                 w = w00 * scale;VectorMA(ambientcolor, w, lightmap            , ambientcolor);
1278                                                 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3        , ambientcolor);
1279                                                 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3    , ambientcolor);
1280                                                 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1281                                                 lightmap += size3;
1282                                         }
1283
1284                                         return true; // success
1285                                 }
1286                         }
1287                 }
1288
1289                 // go down back side
1290                 node = node->children[side ^ 1];
1291                 startz = mid;
1292                 distz = endz - startz;
1293                 goto loc0;
1294         }
1295 }
1296
1297 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1298 {
1299         // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1300         VectorSet(diffusenormal, 0, 0, 1);
1301
1302         if (!model->brushq1.lightdata)
1303         {
1304                 VectorSet(ambientcolor, 1, 1, 1);
1305                 VectorSet(diffusecolor, 0, 0, 0);
1306                 return;
1307         }
1308
1309         Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2] + 0.125, p[2] - 65536);
1310 }
1311
1312 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1313 {
1314         int i;
1315         int j;
1316         int k;
1317         const msurface_t *surface;
1318         float normal[3];
1319         float v0[3];
1320         float v1[3];
1321         float edgedir[3];
1322         float edgenormal[3];
1323         float p[4];
1324         float midf;
1325         float t1;
1326         float t2;
1327         VectorCopy(mid, p);
1328         p[3] = 1;
1329         surface = model->data_surfaces + node->firstsurface;
1330         for (i = 0;i < node->numsurfaces;i++, surface++)
1331         {
1332                 // skip surfaces whose bounding box does not include the point
1333 //              if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1334 //                      continue;
1335                 // skip faces with contents we don't care about
1336                 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1337                         continue;
1338                 // get the surface normal - since it is flat we know any vertex normal will suffice
1339                 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1340                 // skip backfaces
1341                 if (DotProduct(t->dist, normal) > 0)
1342                         continue;
1343                 // iterate edges and see if the point is outside one of them
1344                 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1345                 {
1346                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1347                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1348                         VectorSubtract(v0, v1, edgedir);
1349                         CrossProduct(edgedir, normal, edgenormal);
1350                         if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1351                                 break;
1352                 }
1353                 // if the point is outside one of the edges, it is not within the surface
1354                 if (j < surface->num_vertices)
1355                         continue;
1356
1357                 // we hit a surface, this is the impact point...
1358                 VectorCopy(normal, t->trace->plane.normal);
1359                 t->trace->plane.dist = DotProduct(normal, p);
1360
1361                 // calculate the true fraction
1362                 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1363                 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1364                 midf = t1 / (t1 - t2);
1365                 t->trace->realfraction = midf;
1366
1367                 // calculate the return fraction which is nudged off the surface a bit
1368                 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1369                 t->trace->fraction = bound(0, midf, 1);
1370
1371                 if (collision_prefernudgedfraction.integer)
1372                         t->trace->realfraction = t->trace->fraction;
1373
1374                 t->trace->hittexture = surface->texture->currentframe;
1375                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1376                 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1377                 return surface->texture->currentframe;
1378         }
1379         return NULL;
1380 }
1381
1382 static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
1383 {
1384         const mplane_t *plane;
1385         double t1, t2;
1386         int side;
1387         double midf, mid[3];
1388         const mleaf_t *leaf;
1389
1390         while (node->plane)
1391         {
1392                 plane = node->plane;
1393                 if (plane->type < 3)
1394                 {
1395                         t1 = p1[plane->type] - plane->dist;
1396                         t2 = p2[plane->type] - plane->dist;
1397                 }
1398                 else
1399                 {
1400                         t1 = DotProduct (plane->normal, p1) - plane->dist;
1401                         t2 = DotProduct (plane->normal, p2) - plane->dist;
1402                 }
1403                 if (t1 < 0)
1404                 {
1405                         if (t2 < 0)
1406                         {
1407                                 node = node->children[1];
1408                                 continue;
1409                         }
1410                         side = 1;
1411                 }
1412                 else
1413                 {
1414                         if (t2 >= 0)
1415                         {
1416                                 node = node->children[0];
1417                                 continue;
1418                         }
1419                         side = 0;
1420                 }
1421
1422                 // the line intersects, find intersection point
1423                 // LordHavoc: this uses the original trace for maximum accuracy
1424                 if (plane->type < 3)
1425                 {
1426                         t1 = t->start[plane->type] - plane->dist;
1427                         t2 = t->end[plane->type] - plane->dist;
1428                 }
1429                 else
1430                 {
1431                         t1 = DotProduct (plane->normal, t->start) - plane->dist;
1432                         t2 = DotProduct (plane->normal, t->end) - plane->dist;
1433                 }
1434         
1435                 midf = t1 / (t1 - t2);
1436                 VectorMA(t->start, midf, t->dist, mid);
1437
1438                 // recurse both sides, front side first, return if we hit a surface
1439                 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1440                         return HULLCHECKSTATE_DONE;
1441
1442                 // test each surface on the node
1443                 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1444                 if (t->trace->hittexture)
1445                         return HULLCHECKSTATE_DONE;
1446
1447                 // recurse back side
1448                 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1449         }
1450         leaf = (const mleaf_t *)node;
1451         side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1452         if (!t->trace->startfound)
1453         {
1454                 t->trace->startfound = true;
1455                 t->trace->startsupercontents |= side;
1456         }
1457         if (side & SUPERCONTENTS_LIQUIDSMASK)
1458                 t->trace->inwater = true;
1459         if (side == 0)
1460                 t->trace->inopen = true;
1461         if (side & t->trace->hitsupercontentsmask)
1462         {
1463                 // if the first leaf is solid, set startsolid
1464                 if (t->trace->allsolid)
1465                         t->trace->startsolid = true;
1466                 return HULLCHECKSTATE_SOLID;
1467         }
1468         else
1469         {
1470                 t->trace->allsolid = false;
1471                 return HULLCHECKSTATE_EMPTY;
1472         }
1473 }
1474
1475 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
1476 {
1477         RecursiveHullCheckTraceInfo_t rhc;
1478
1479         memset(&rhc, 0, sizeof(rhc));
1480         memset(trace, 0, sizeof(trace_t));
1481         rhc.trace = trace;
1482         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1483         rhc.trace->fraction = 1;
1484         rhc.trace->realfraction = 1;
1485         rhc.trace->allsolid = true;
1486         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1487         VectorCopy(start, rhc.start);
1488         VectorCopy(end, rhc.end);
1489         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1490         Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1491         VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1492 }
1493
1494 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1495 {
1496         int c;
1497         unsigned char *outstart = out;
1498         while (out < outend)
1499         {
1500                 if (in == inend)
1501                 {
1502                         Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1503                         return;
1504                 }
1505                 c = *in++;
1506                 if (c)
1507                         *out++ = c;
1508                 else
1509                 {
1510                         if (in == inend)
1511                         {
1512                                 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1513                                 return;
1514                         }
1515                         for (c = *in++;c > 0;c--)
1516                         {
1517                                 if (out == outend)
1518                                 {
1519                                         Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1520                                         return;
1521                                 }
1522                                 *out++ = 0;
1523                         }
1524                 }
1525         }
1526 }
1527
1528 /*
1529 =============
1530 R_Q1BSP_LoadSplitSky
1531
1532 A sky texture is 256*128, with the right side being a masked overlay
1533 ==============
1534 */
1535 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1536 {
1537         int x, y;
1538         int w = width/2;
1539         int h = height;
1540         unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1541         unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1542
1543         // allocate a texture pool if we need it
1544         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1545                 loadmodel->texturepool = R_AllocTexturePool();
1546
1547         if (bytesperpixel == 4)
1548         {
1549                 for (y = 0;y < h;y++)
1550                 {
1551                         for (x = 0;x < w;x++)
1552                         {
1553                                 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1554                                 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1555                         }
1556                 }
1557         }
1558         else
1559         {
1560                 // make an average value for the back to avoid
1561                 // a fringe on the top level
1562                 int p, r, g, b;
1563                 union
1564                 {
1565                         unsigned int i;
1566                         unsigned char b[4];
1567                 }
1568                 bgra;
1569                 r = g = b = 0;
1570                 for (y = 0;y < h;y++)
1571                 {
1572                         for (x = 0;x < w;x++)
1573                         {
1574                                 p = src[x*width+y+w];
1575                                 r += palette_rgb[p][0];
1576                                 g += palette_rgb[p][1];
1577                                 b += palette_rgb[p][2];
1578                         }
1579                 }
1580                 bgra.b[2] = r/(w*h);
1581                 bgra.b[1] = g/(w*h);
1582                 bgra.b[0] = b/(w*h);
1583                 bgra.b[3] = 0;
1584                 for (y = 0;y < h;y++)
1585                 {
1586                         for (x = 0;x < w;x++)
1587                         {
1588                                 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1589                                 p = src[y*width+x];
1590                                 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1591                         }
1592                 }
1593         }
1594
1595         loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0         , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1596         loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1597         Mem_Free(solidpixels);
1598         Mem_Free(alphapixels);
1599 }
1600
1601 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1602 {
1603         int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1604         skinframe_t *skinframe;
1605         miptex_t *dmiptex;
1606         texture_t *tx, *tx2, *anims[10], *altanims[10];
1607         texture_t backuptex;
1608         dmiptexlump_t *m;
1609         unsigned char *data, *mtdata;
1610         const char *s;
1611         char mapname[MAX_QPATH], name[MAX_QPATH];
1612         unsigned char zeroopaque[4], zerotrans[4];
1613         char vabuf[1024];
1614         Vector4Set(zeroopaque, 0, 0, 0, 255);
1615         Vector4Set(zerotrans, 0, 0, 0, 128);
1616
1617         loadmodel->data_textures = NULL;
1618
1619         // add two slots for notexture walls and notexture liquids
1620         if (l->filelen)
1621         {
1622                 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1623                 m->nummiptex = LittleLong (m->nummiptex);
1624                 loadmodel->num_textures = m->nummiptex + 2;
1625                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1626         }
1627         else
1628         {
1629                 m = NULL;
1630                 loadmodel->num_textures = 2;
1631                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1632         }
1633
1634         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1635
1636         // fill out all slots with notexture
1637         if (cls.state != ca_dedicated)
1638                 skinframe = R_SkinFrame_LoadMissing();
1639         else
1640                 skinframe = NULL;
1641         for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1642         {
1643                 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1644                 tx->width = 16;
1645                 tx->height = 16;
1646                 if (cls.state != ca_dedicated)
1647                 {
1648                         tx->numskinframes = 1;
1649                         tx->skinframerate = 1;
1650                         tx->skinframes[0] = skinframe;
1651                         tx->currentskinframe = tx->skinframes[0];
1652                 }
1653                 tx->basematerialflags = MATERIALFLAG_WALL;
1654                 if (i == loadmodel->num_textures - 1)
1655                 {
1656                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1657                         tx->supercontents = mod_q1bsp_texture_water.supercontents;
1658                         tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1659                 }
1660                 else
1661                 {
1662                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1663                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1664                 }
1665                 tx->currentframe = tx;
1666
1667                 // clear water settings
1668                 tx->reflectmin = 0;
1669                 tx->reflectmax = 1;
1670                 tx->refractfactor = 1;
1671                 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1672                 tx->reflectfactor = 1;
1673                 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1674                 tx->r_water_wateralpha = 1;
1675                 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1676                 tx->offsetscale = 1;
1677                 tx->offsetbias = 0;
1678                 tx->specularscalemod = 1;
1679                 tx->specularpowermod = 1;
1680         }
1681
1682         if (!m)
1683         {
1684                 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1685                 return;
1686         }
1687
1688         s = loadmodel->name;
1689         if (!strncasecmp(s, "maps/", 5))
1690                 s += 5;
1691         FS_StripExtension(s, mapname, sizeof(mapname));
1692
1693         // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1694         dofs = m->dataofs;
1695         // LordHavoc: mostly rewritten map texture loader
1696         for (i = 0;i < m->nummiptex;i++)
1697         {
1698                 dofs[i] = LittleLong(dofs[i]);
1699                 if (r_nosurftextures.integer)
1700                         continue;
1701                 if (dofs[i] == -1)
1702                 {
1703                         Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1704                         continue;
1705                 }
1706                 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1707
1708                 // copy name, but only up to 16 characters
1709                 // (the output buffer can hold more than this, but the input buffer is
1710                 //  only 16)
1711                 for (j = 0;j < 16 && dmiptex->name[j];j++)
1712                         name[j] = dmiptex->name[j];
1713                 name[j] = 0;
1714
1715                 if (!name[0])
1716                 {
1717                         dpsnprintf(name, sizeof(name), "unnamed%i", i);
1718                         Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1719                 }
1720
1721                 mtwidth = LittleLong(dmiptex->width);
1722                 mtheight = LittleLong(dmiptex->height);
1723                 mtdata = NULL;
1724                 j = LittleLong(dmiptex->offsets[0]);
1725                 if (j)
1726                 {
1727                         // texture included
1728                         if (j < 40 || j + mtwidth * mtheight > l->filelen)
1729                         {
1730                                 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1731                                 continue;
1732                         }
1733                         mtdata = (unsigned char *)dmiptex + j;
1734                 }
1735
1736                 if ((mtwidth & 15) || (mtheight & 15))
1737                         Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1738
1739                 // LordHavoc: force all names to lowercase
1740                 for (j = 0;name[j];j++)
1741                         if (name[j] >= 'A' && name[j] <= 'Z')
1742                                 name[j] += 'a' - 'A';
1743
1744                 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1745                 backuptex = loadmodel->data_textures[i];
1746                 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1747                         continue;
1748                 loadmodel->data_textures[i] = backuptex;
1749
1750                 tx = loadmodel->data_textures + i;
1751                 strlcpy(tx->name, name, sizeof(tx->name));
1752                 tx->width = mtwidth;
1753                 tx->height = mtheight;
1754
1755                 if (tx->name[0] == '*')
1756                 {
1757                         if (!strncmp(tx->name, "*lava", 5))
1758                         {
1759                                 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1760                                 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1761                         }
1762                         else if (!strncmp(tx->name, "*slime", 6))
1763                         {
1764                                 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1765                                 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1766                         }
1767                         else
1768                         {
1769                                 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1770                                 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1771                         }
1772                 }
1773                 else if (!strncmp(tx->name, "sky", 3))
1774                 {
1775                         tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1776                         tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1777                         tx->supercontents |= SUPERCONTENTS_SOLID; // for the surface traceline we need to hit this surface as a solid...
1778                 }
1779                 else
1780                 {
1781                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1782                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1783                 }
1784
1785                 if (cls.state != ca_dedicated)
1786                 {
1787                         // LordHavoc: HL sky textures are entirely different than quake
1788                         if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1789                         {
1790                                 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1791                                 if (!data)
1792                                         data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1793                                 if (data && image_width == image_height * 2)
1794                                 {
1795                                         R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1796                                         Mem_Free(data);
1797                                 }
1798                                 else if (mtdata != NULL)
1799                                         R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1800                         }
1801                         else
1802                         {
1803                                 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1804                                 if (!skinframe)
1805                                         skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1806                                 if (skinframe)
1807                                         tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1808                                 if (!skinframe)
1809                                 {
1810                                         // did not find external texture, load it from the bsp or wad3
1811                                         if (loadmodel->brush.ishlbsp)
1812                                         {
1813                                                 // internal texture overrides wad
1814                                                 unsigned char *pixels, *freepixels;
1815                                                 pixels = freepixels = NULL;
1816                                                 if (mtdata)
1817                                                         pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1818                                                 if (pixels == NULL)
1819                                                         pixels = freepixels = W_GetTextureBGRA(tx->name);
1820                                                 if (pixels != NULL)
1821                                                 {
1822                                                         tx->width = image_width;
1823                                                         tx->height = image_height;
1824                                                         skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1825                                                 }
1826                                                 if (freepixels)
1827                                                         Mem_Free(freepixels);
1828                                         }
1829                                         else if (mtdata) // texture included
1830                                                 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1831                                 }
1832                                 // if skinframe is still NULL the "missing" texture will be used
1833                                 if (skinframe)
1834                                         tx->skinframes[0] = skinframe;
1835                         }
1836                         // LordHavoc: some Tenebrae textures get replaced by black
1837                         if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1838                                 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1839                         else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1840                                 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1841                 }
1842
1843                 tx->basematerialflags = MATERIALFLAG_WALL;
1844                 if (tx->name[0] == '*')
1845                 {
1846                         // LordHavoc: some turbulent textures should not be affected by wateralpha
1847                         if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1848                                 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1849                         else if (!strncmp(tx->name,"*lava",5)
1850                          || !strncmp(tx->name,"*teleport",9)
1851                          || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1852                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1853                         else
1854                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1855                         if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1856                                 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1857                 }
1858                 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1859                 {
1860                         // replace the texture with black
1861                         tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1862                 }
1863                 else if (!strncmp(tx->name, "sky", 3))
1864                         tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1865                 else if (!strcmp(tx->name, "caulk"))
1866                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1867                 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1868                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1869
1870                 // start out with no animation
1871                 tx->currentframe = tx;
1872                 tx->currentskinframe = tx->skinframes[0];
1873                 tx->currentmaterialflags = tx->basematerialflags;
1874         }
1875
1876         // sequence the animations
1877         for (i = 0;i < m->nummiptex;i++)
1878         {
1879                 tx = loadmodel->data_textures + i;
1880                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1881                         continue;
1882                 if (tx->anim_total[0] || tx->anim_total[1])
1883                         continue;       // already sequenced
1884
1885                 // find the number of frames in the animation
1886                 memset(anims, 0, sizeof(anims));
1887                 memset(altanims, 0, sizeof(altanims));
1888
1889                 for (j = i;j < m->nummiptex;j++)
1890                 {
1891                         tx2 = loadmodel->data_textures + j;
1892                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1893                                 continue;
1894
1895                         num = tx2->name[1];
1896                         if (num >= '0' && num <= '9')
1897                                 anims[num - '0'] = tx2;
1898                         else if (num >= 'a' && num <= 'j')
1899                                 altanims[num - 'a'] = tx2;
1900                         else
1901                                 Con_Printf("Bad animating texture %s\n", tx->name);
1902                 }
1903
1904                 max = altmax = 0;
1905                 for (j = 0;j < 10;j++)
1906                 {
1907                         if (anims[j])
1908                                 max = j + 1;
1909                         if (altanims[j])
1910                                 altmax = j + 1;
1911                 }
1912                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1913
1914                 incomplete = false;
1915                 for (j = 0;j < max;j++)
1916                 {
1917                         if (!anims[j])
1918                         {
1919                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1920                                 incomplete = true;
1921                         }
1922                 }
1923                 for (j = 0;j < altmax;j++)
1924                 {
1925                         if (!altanims[j])
1926                         {
1927                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1928                                 incomplete = true;
1929                         }
1930                 }
1931                 if (incomplete)
1932                         continue;
1933
1934                 if (altmax < 1)
1935                 {
1936                         // if there is no alternate animation, duplicate the primary
1937                         // animation into the alternate
1938                         altmax = max;
1939                         for (k = 0;k < 10;k++)
1940                                 altanims[k] = anims[k];
1941                 }
1942
1943                 // link together the primary animation
1944                 for (j = 0;j < max;j++)
1945                 {
1946                         tx2 = anims[j];
1947                         tx2->animated = true;
1948                         tx2->anim_total[0] = max;
1949                         tx2->anim_total[1] = altmax;
1950                         for (k = 0;k < 10;k++)
1951                         {
1952                                 tx2->anim_frames[0][k] = anims[k];
1953                                 tx2->anim_frames[1][k] = altanims[k];
1954                         }
1955                 }
1956
1957                 // if there really is an alternate anim...
1958                 if (anims[0] != altanims[0])
1959                 {
1960                         // link together the alternate animation
1961                         for (j = 0;j < altmax;j++)
1962                         {
1963                                 tx2 = altanims[j];
1964                                 tx2->animated = true;
1965                                 // the primary/alternate are reversed here
1966                                 tx2->anim_total[0] = altmax;
1967                                 tx2->anim_total[1] = max;
1968                                 for (k = 0;k < 10;k++)
1969                                 {
1970                                         tx2->anim_frames[0][k] = altanims[k];
1971                                         tx2->anim_frames[1][k] = anims[k];
1972                                 }
1973                         }
1974                 }
1975         }
1976 }
1977
1978 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1979 {
1980         int i;
1981         unsigned char *in, *out, *data, d;
1982         char litfilename[MAX_QPATH];
1983         char dlitfilename[MAX_QPATH];
1984         fs_offset_t filesize;
1985         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1986         {
1987                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1988                 for (i=0; i<l->filelen; i++)
1989                         loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1990         }
1991         else // LordHavoc: bsp version 29 (normal white lighting)
1992         {
1993                 // LordHavoc: hope is not lost yet, check for a .lit file to load
1994                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1995                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1996                 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1997                 strlcat (litfilename, ".lit", sizeof (litfilename));
1998                 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1999                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2000                 if (data)
2001                 {
2002                         if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2003                         {
2004                                 i = LittleLong(((int *)data)[1]);
2005                                 if (i == 1)
2006                                 {
2007                                         if (developer_loading.integer)
2008                                                 Con_Printf("loaded %s\n", litfilename);
2009                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2010                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2011                                         Mem_Free(data);
2012                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2013                                         if (data)
2014                                         {
2015                                                 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2016                                                 {
2017                                                         i = LittleLong(((int *)data)[1]);
2018                                                         if (i == 1)
2019                                                         {
2020                                                                 if (developer_loading.integer)
2021                                                                         Con_Printf("loaded %s\n", dlitfilename);
2022                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2023                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2024                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
2025                                                                 loadmodel->brushq3.deluxemapping = true;
2026                                                         }
2027                                                 }
2028                                                 Mem_Free(data);
2029                                                 data = NULL;
2030                                         }
2031                                         return;
2032                                 }
2033                                 else
2034                                         Con_Printf("Unknown .lit file version (%d)\n", i);
2035                         }
2036                         else if (filesize == 8)
2037                                 Con_Print("Empty .lit file, ignoring\n");
2038                         else
2039                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
2040                         if (data)
2041                         {
2042                                 Mem_Free(data);
2043                                 data = NULL;
2044                         }
2045                 }
2046                 // LordHavoc: oh well, expand the white lighting data
2047                 if (!l->filelen)
2048                         return;
2049                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
2050                 in = mod_base + l->fileofs;
2051                 out = loadmodel->brushq1.lightdata;
2052                 for (i = 0;i < l->filelen;i++)
2053                 {
2054                         d = *in++;
2055                         *out++ = d;
2056                         *out++ = d;
2057                         *out++ = d;
2058                 }
2059         }
2060 }
2061
2062 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
2063 {
2064         loadmodel->brushq1.num_compressedpvs = 0;
2065         loadmodel->brushq1.data_compressedpvs = NULL;
2066         if (!l->filelen)
2067                 return;
2068         loadmodel->brushq1.num_compressedpvs = l->filelen;
2069         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
2070         memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
2071 }
2072
2073 // used only for HalfLife maps
2074 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2075 {
2076         char key[128], value[4096];
2077         int i, j, k;
2078         if (!data)
2079                 return;
2080         if (!COM_ParseToken_Simple(&data, false, false, true))
2081                 return; // error
2082         if (com_token[0] != '{')
2083                 return; // error
2084         while (1)
2085         {
2086                 if (!COM_ParseToken_Simple(&data, false, false, true))
2087                         return; // error
2088                 if (com_token[0] == '}')
2089                         break; // end of worldspawn
2090                 if (com_token[0] == '_')
2091                         strlcpy(key, com_token + 1, sizeof(key));
2092                 else
2093                         strlcpy(key, com_token, sizeof(key));
2094                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2095                         key[strlen(key)-1] = 0;
2096                 if (!COM_ParseToken_Simple(&data, false, false, true))
2097                         return; // error
2098                 dpsnprintf(value, sizeof(value), "%s", com_token);
2099                 if (!strcmp("wad", key)) // for HalfLife maps
2100                 {
2101                         if (loadmodel->brush.ishlbsp)
2102                         {
2103                                 j = 0;
2104                                 for (i = 0;i < (int)sizeof(value);i++)
2105                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2106                                                 break;
2107                                 if (value[i])
2108                                 {
2109                                         for (;i < (int)sizeof(value);i++)
2110                                         {
2111                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2112                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2113                                                         j = i+1;
2114                                                 else if (value[i] == ';' || value[i] == 0)
2115                                                 {
2116                                                         k = value[i];
2117                                                         value[i] = 0;
2118                                                         W_LoadTextureWadFile(&value[j], false);
2119                                                         j = i+1;
2120                                                         if (!k)
2121                                                                 break;
2122                                                 }
2123                                         }
2124                                 }
2125                         }
2126                 }
2127         }
2128 }
2129
2130 static void Mod_Q1BSP_LoadEntities(lump_t *l)
2131 {
2132         loadmodel->brush.entities = NULL;
2133         if (!l->filelen)
2134                 return;
2135         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
2136         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
2137         loadmodel->brush.entities[l->filelen] = 0;
2138         if (loadmodel->brush.ishlbsp)
2139                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2140 }
2141
2142
2143 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
2144 {
2145         dvertex_t       *in;
2146         mvertex_t       *out;
2147         int                     i, count;
2148
2149         in = (dvertex_t *)(mod_base + l->fileofs);
2150         if (l->filelen % sizeof(*in))
2151                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2152         count = l->filelen / sizeof(*in);
2153         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2154
2155         loadmodel->brushq1.vertexes = out;
2156         loadmodel->brushq1.numvertexes = count;
2157
2158         for ( i=0 ; i<count ; i++, in++, out++)
2159         {
2160                 out->position[0] = LittleFloat(in->point[0]);
2161                 out->position[1] = LittleFloat(in->point[1]);
2162                 out->position[2] = LittleFloat(in->point[2]);
2163         }
2164 }
2165
2166 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
2167 // can be used for this
2168 // REMOVEME
2169 static int SB_ReadInt (unsigned char **buffer)
2170 {
2171         int     i;
2172         i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
2173         (*buffer) += 4;
2174         return i;
2175 }
2176
2177 // REMOVEME
2178 static float SB_ReadFloat (unsigned char **buffer)
2179 {
2180         union
2181         {
2182                 int             i;
2183                 float   f;
2184         } u;
2185
2186         u.i = SB_ReadInt (buffer);
2187         return u.f;
2188 }
2189
2190 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
2191 {
2192         unsigned char           *index;
2193         dmodel_t        *out;
2194         int                     i, j, count;
2195
2196         index = (unsigned char *)(mod_base + l->fileofs);
2197         if (l->filelen % (48+4*hullinfo->filehulls))
2198                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2199
2200         count = l->filelen / (48+4*hullinfo->filehulls);
2201         out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2202
2203         loadmodel->brushq1.submodels = out;
2204         loadmodel->brush.numsubmodels = count;
2205
2206         for (i = 0; i < count; i++, out++)
2207         {
2208         // spread out the mins / maxs by a pixel
2209                 out->mins[0] = SB_ReadFloat (&index) - 1;
2210                 out->mins[1] = SB_ReadFloat (&index) - 1;
2211                 out->mins[2] = SB_ReadFloat (&index) - 1;
2212                 out->maxs[0] = SB_ReadFloat (&index) + 1;
2213                 out->maxs[1] = SB_ReadFloat (&index) + 1;
2214                 out->maxs[2] = SB_ReadFloat (&index) + 1;
2215                 out->origin[0] = SB_ReadFloat (&index);
2216                 out->origin[1] = SB_ReadFloat (&index);
2217                 out->origin[2] = SB_ReadFloat (&index);
2218                 for (j = 0; j < hullinfo->filehulls; j++)
2219                         out->headnode[j] = SB_ReadInt (&index);
2220                 out->visleafs = SB_ReadInt (&index);
2221                 out->firstface = SB_ReadInt (&index);
2222                 out->numfaces = SB_ReadInt (&index);
2223         }
2224 }
2225
2226 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2227 {
2228         dedge_t *in;
2229         medge_t *out;
2230         int     i, count;
2231
2232         in = (dedge_t *)(mod_base + l->fileofs);
2233         if (l->filelen % sizeof(*in))
2234                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2235         count = l->filelen / sizeof(*in);
2236         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2237
2238         loadmodel->brushq1.edges = out;
2239         loadmodel->brushq1.numedges = count;
2240
2241         for ( i=0 ; i<count ; i++, in++, out++)
2242         {
2243                 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2244                 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2245                 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2246                 {
2247                         Con_Printf("Mod_Q1BSP_LoadEdges: %s has invalid vertex indices in edge %i (vertices %i %i >= numvertices %i)\n", loadmodel->name, i, out->v[0], out->v[1], loadmodel->brushq1.numvertexes);
2248                         if(!loadmodel->brushq1.numvertexes)
2249                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2250                                 
2251                         out->v[0] = 0;
2252                         out->v[1] = 0;
2253                 }
2254         }
2255 }
2256
2257 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2258 {
2259         texinfo_t *in;
2260         mtexinfo_t *out;
2261         int i, j, k, count, miptex;
2262
2263         in = (texinfo_t *)(mod_base + l->fileofs);
2264         if (l->filelen % sizeof(*in))
2265                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2266         count = l->filelen / sizeof(*in);
2267         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2268
2269         loadmodel->brushq1.texinfo = out;
2270         loadmodel->brushq1.numtexinfo = count;
2271
2272         for (i = 0;i < count;i++, in++, out++)
2273         {
2274                 for (k = 0;k < 2;k++)
2275                         for (j = 0;j < 4;j++)
2276                                 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2277
2278                 miptex = LittleLong(in->miptex);
2279                 out->flags = LittleLong(in->flags);
2280
2281                 out->texture = NULL;
2282                 if (loadmodel->data_textures)
2283                 {
2284                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2285                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2286                         else
2287                                 out->texture = loadmodel->data_textures + miptex;
2288                 }
2289                 if (out->flags & TEX_SPECIAL)
2290                 {
2291                         // if texture chosen is NULL or the shader needs a lightmap,
2292                         // force to notexture water shader
2293                         if (out->texture == NULL)
2294                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2295                 }
2296                 else
2297                 {
2298                         // if texture chosen is NULL, force to notexture
2299                         if (out->texture == NULL)
2300                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2301                 }
2302         }
2303 }
2304
2305 #if 0
2306 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2307 {
2308         int             i, j;
2309         float   *v;
2310
2311         mins[0] = mins[1] = mins[2] = 9999;
2312         maxs[0] = maxs[1] = maxs[2] = -9999;
2313         v = verts;
2314         for (i = 0;i < numverts;i++)
2315         {
2316                 for (j = 0;j < 3;j++, v++)
2317                 {
2318                         if (*v < mins[j])
2319                                 mins[j] = *v;
2320                         if (*v > maxs[j])
2321                                 maxs[j] = *v;
2322                 }
2323         }
2324 }
2325
2326 #define MAX_SUBDIVPOLYTRIANGLES 4096
2327 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2328
2329 static int subdivpolyverts, subdivpolytriangles;
2330 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2331 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2332
2333 static int subdivpolylookupvert(vec3_t v)
2334 {
2335         int i;
2336         for (i = 0;i < subdivpolyverts;i++)
2337                 if (subdivpolyvert[i][0] == v[0]
2338                  && subdivpolyvert[i][1] == v[1]
2339                  && subdivpolyvert[i][2] == v[2])
2340                         return i;
2341         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2342                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2343         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2344         return subdivpolyverts++;
2345 }
2346
2347 static void SubdividePolygon(int numverts, float *verts)
2348 {
2349         int             i, i1, i2, i3, f, b, c, p;
2350         vec3_t  mins, maxs, front[256], back[256];
2351         float   m, *pv, *cv, dist[256], frac;
2352
2353         if (numverts > 250)
2354                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2355
2356         BoundPoly(numverts, verts, mins, maxs);
2357
2358         for (i = 0;i < 3;i++)
2359         {
2360                 m = (mins[i] + maxs[i]) * 0.5;
2361                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2362                 if (maxs[i] - m < 8)
2363                         continue;
2364                 if (m - mins[i] < 8)
2365                         continue;
2366
2367                 // cut it
2368                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2369                         dist[c] = cv[i] - m;
2370
2371                 f = b = 0;
2372                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2373                 {
2374                         if (dist[p] >= 0)
2375                         {
2376                                 VectorCopy(pv, front[f]);
2377                                 f++;
2378                         }
2379                         if (dist[p] <= 0)
2380                         {
2381                                 VectorCopy(pv, back[b]);
2382                                 b++;
2383                         }
2384                         if (dist[p] == 0 || dist[c] == 0)
2385                                 continue;
2386                         if ((dist[p] > 0) != (dist[c] > 0) )
2387                         {
2388                                 // clip point
2389                                 frac = dist[p] / (dist[p] - dist[c]);
2390                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2391                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2392                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2393                                 f++;
2394                                 b++;
2395                         }
2396                 }
2397
2398                 SubdividePolygon(f, front[0]);
2399                 SubdividePolygon(b, back[0]);
2400                 return;
2401         }
2402
2403         i1 = subdivpolylookupvert(verts);
2404         i2 = subdivpolylookupvert(verts + 3);
2405         for (i = 2;i < numverts;i++)
2406         {
2407                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2408                 {
2409                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2410                         return;
2411                 }
2412
2413                 i3 = subdivpolylookupvert(verts + i * 3);
2414                 subdivpolyindex[subdivpolytriangles][0] = i1;
2415                 subdivpolyindex[subdivpolytriangles][1] = i2;
2416                 subdivpolyindex[subdivpolytriangles][2] = i3;
2417                 i2 = i3;
2418                 subdivpolytriangles++;
2419         }
2420 }
2421
2422 //Breaks a polygon up along axial 64 unit
2423 //boundaries so that turbulent and sky warps
2424 //can be done reasonably.
2425 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2426 {
2427         int i, j;
2428         surfvertex_t *v;
2429         surfmesh_t *mesh;
2430
2431         subdivpolytriangles = 0;
2432         subdivpolyverts = 0;
2433         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2434         if (subdivpolytriangles < 1)
2435                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2436
2437         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2438         mesh->num_vertices = subdivpolyverts;
2439         mesh->num_triangles = subdivpolytriangles;
2440         mesh->vertex = (surfvertex_t *)(mesh + 1);
2441         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2442         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2443
2444         for (i = 0;i < mesh->num_triangles;i++)
2445                 for (j = 0;j < 3;j++)
2446                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2447
2448         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2449         {
2450                 VectorCopy(subdivpolyvert[i], v->v);
2451                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2452                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2453         }
2454 }
2455 #endif
2456
2457 extern cvar_t gl_max_lightmapsize;
2458 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2459 {
2460         dface_t *in;
2461         msurface_t *surface;
2462         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2463         float texmins[2], texmaxs[2], val;
2464         rtexture_t *lightmaptexture, *deluxemaptexture;
2465         char vabuf[1024];
2466
2467         in = (dface_t *)(mod_base + l->fileofs);
2468         if (l->filelen % sizeof(*in))
2469                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2470         count = l->filelen / sizeof(*in);
2471         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2472         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2473
2474         loadmodel->num_surfaces = count;
2475
2476         loadmodel->brushq1.firstrender = true;
2477         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2478
2479         totalverts = 0;
2480         totaltris = 0;
2481         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2482         {
2483                 numedges = (unsigned short)LittleShort(in->numedges);
2484                 totalverts += numedges;
2485                 totaltris += numedges - 2;
2486         }
2487
2488         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2489
2490         lightmaptexture = NULL;
2491         deluxemaptexture = r_texture_blanknormalmap;
2492         lightmapnumber = 0;
2493         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2494         totallightmapsamples = 0;
2495
2496         totalverts = 0;
2497         totaltris = 0;
2498         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2499         {
2500                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2501
2502                 // FIXME: validate edges, texinfo, etc?
2503                 firstedge = LittleLong(in->firstedge);
2504                 numedges = (unsigned short)LittleShort(in->numedges);
2505                 if ((unsigned int) firstedge > (unsigned int) loadmodel->brushq1.numsurfedges || (unsigned int) numedges > (unsigned int) loadmodel->brushq1.numsurfedges || (unsigned int) firstedge + (unsigned int) numedges > (unsigned int) loadmodel->brushq1.numsurfedges)
2506                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2507                 i = (unsigned short)LittleShort(in->texinfo);
2508                 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2509                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2510                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2511                 surface->texture = surface->lightmapinfo->texinfo->texture;
2512
2513                 planenum = (unsigned short)LittleShort(in->planenum);
2514                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2515                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2516
2517                 //surface->flags = surface->texture->flags;
2518                 //if (LittleShort(in->side))
2519                 //      surface->flags |= SURF_PLANEBACK;
2520                 //surface->plane = loadmodel->brush.data_planes + planenum;
2521
2522                 surface->num_firstvertex = totalverts;
2523                 surface->num_vertices = numedges;
2524                 surface->num_firsttriangle = totaltris;
2525                 surface->num_triangles = numedges - 2;
2526                 totalverts += numedges;
2527                 totaltris += numedges - 2;
2528
2529                 // convert edges back to a normal polygon
2530                 for (i = 0;i < surface->num_vertices;i++)
2531                 {
2532                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2533                         float s, t;
2534                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2535                         if (lindex >= 0)
2536                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2537                         else
2538                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2539                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2540                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2541                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2542                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2543                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2544                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2545                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2546                 }
2547
2548                 for (i = 0;i < surface->num_triangles;i++)
2549                 {
2550                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2551                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2552                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2553                 }
2554
2555                 // compile additional data about the surface geometry
2556                 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
2557                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
2558                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2559
2560                 // generate surface extents information
2561                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2562                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2563                 for (i = 1;i < surface->num_vertices;i++)
2564                 {
2565                         for (j = 0;j < 2;j++)
2566                         {
2567                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2568                                 texmins[j] = min(texmins[j], val);
2569                                 texmaxs[j] = max(texmaxs[j], val);
2570                         }
2571                 }
2572                 for (i = 0;i < 2;i++)
2573                 {
2574                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2575                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2576                 }
2577
2578                 smax = surface->lightmapinfo->extents[0] >> 4;
2579                 tmax = surface->lightmapinfo->extents[1] >> 4;
2580                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2581                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2582
2583                 // lighting info
2584                 for (i = 0;i < MAXLIGHTMAPS;i++)
2585                         surface->lightmapinfo->styles[i] = in->styles[i];
2586                 surface->lightmaptexture = NULL;
2587                 surface->deluxemaptexture = r_texture_blanknormalmap;
2588                 i = LittleLong(in->lightofs);
2589                 if (i == -1)
2590                 {
2591                         surface->lightmapinfo->samples = NULL;
2592 #if 1
2593                         // give non-lightmapped water a 1x white lightmap
2594                         if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2595                         {
2596                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2597                                 surface->lightmapinfo->styles[0] = 0;
2598                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2599                         }
2600 #endif
2601                 }
2602                 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2603                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2604                 else // LordHavoc: white lighting (bsp version 29)
2605                 {
2606                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2607                         if (loadmodel->brushq1.nmaplightdata)
2608                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2609                 }
2610
2611                 // check if we should apply a lightmap to this
2612                 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2613                 {
2614                         if (ssize > 256 || tsize > 256)
2615                                 Host_Error("Bad surface extents");
2616
2617                         if (lightmapsize < ssize)
2618                                 lightmapsize = ssize;
2619                         if (lightmapsize < tsize)
2620                                 lightmapsize = tsize;
2621
2622                         totallightmapsamples += ssize*tsize;
2623
2624                         // force lightmap upload on first time seeing the surface
2625                         //
2626                         // additionally this is used by the later code to see if a
2627                         // lightmap is needed on this surface (rather than duplicating the
2628                         // logic above)
2629                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2630                         loadmodel->lit = true;
2631                 }
2632         }
2633
2634         // small maps (such as ammo boxes especially) don't need big lightmap
2635         // textures, so this code tries to guess a good size based on
2636         // totallightmapsamples (size of the lightmaps lump basically), as well as
2637         // trying to max out the size if there is a lot of lightmap data to store
2638         // additionally, never choose a lightmapsize that is smaller than the
2639         // largest surface encountered (as it would fail)
2640         i = lightmapsize;
2641         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2642                 ;
2643
2644         // now that we've decided the lightmap texture size, we can do the rest
2645         if (cls.state != ca_dedicated)
2646         {
2647                 int stainmapsize = 0;
2648                 mod_alloclightmap_state_t allocState;
2649
2650                 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2651                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2652                 {
2653                         int i, iu, iv, lightmapx = 0, lightmapy = 0;
2654                         float u, v, ubase, vbase, uscale, vscale;
2655
2656                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2657                                 continue;
2658
2659                         smax = surface->lightmapinfo->extents[0] >> 4;
2660                         tmax = surface->lightmapinfo->extents[1] >> 4;
2661                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2662                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2663                         stainmapsize += ssize * tsize * 3;
2664
2665                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2666                         {
2667                                 // allocate a texture pool if we need it
2668                                 if (loadmodel->texturepool == NULL)
2669                                         loadmodel->texturepool = R_AllocTexturePool();
2670                                 // could not find room, make a new lightmap
2671                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2672                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2673                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2674                                 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2675                                 if (loadmodel->brushq1.nmaplightdata)
2676                                         loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2677                                 lightmapnumber++;
2678                                 Mod_AllocLightmap_Reset(&allocState);
2679                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2680                         }
2681                         surface->lightmaptexture = lightmaptexture;
2682                         surface->deluxemaptexture = deluxemaptexture;
2683                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2684                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2685
2686                         uscale = 1.0f / (float)lightmapsize;
2687                         vscale = 1.0f / (float)lightmapsize;
2688                         ubase = lightmapx * uscale;
2689                         vbase = lightmapy * vscale;
2690
2691                         for (i = 0;i < surface->num_vertices;i++)
2692                         {
2693                                 u = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3]) + 8 - surface->lightmapinfo->texturemins[0]) * (1.0 / 16.0);
2694                                 v = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3]) + 8 - surface->lightmapinfo->texturemins[1]) * (1.0 / 16.0);
2695                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2696                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2697                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2698                                 iu = (int) u;
2699                                 iv = (int) v;
2700                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2701                         }
2702                 }
2703
2704                 if (cl_stainmaps.integer)
2705                 {
2706                         // allocate stainmaps for permanent marks on walls and clear white
2707                         unsigned char *stainsamples = NULL;
2708                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2709                         memset(stainsamples, 255, stainmapsize);
2710                         // assign pointers
2711                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2712                         {
2713                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2714                                         continue;
2715                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2716                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2717                                 surface->lightmapinfo->stainsamples = stainsamples;
2718                                 stainsamples += ssize * tsize * 3;
2719                         }
2720                 }
2721         }
2722
2723         // generate ushort elements array if possible
2724         if (loadmodel->surfmesh.data_element3s)
2725                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2726                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2727 }
2728
2729 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2730 {
2731         //if (node->parent)
2732         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2733         node->parent = parent;
2734         if (node->plane)
2735         {
2736                 // this is a node, recurse to children
2737                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2738                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2739                 // combine supercontents of children
2740                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2741         }
2742         else
2743         {
2744                 int j;
2745                 mleaf_t *leaf = (mleaf_t *)node;
2746                 // if this is a leaf, calculate supercontents mask from all collidable
2747                 // primitives in the leaf (brushes and collision surfaces)
2748                 // also flag if the leaf contains any collision surfaces
2749                 leaf->combinedsupercontents = 0;
2750                 // combine the supercontents values of all brushes in this leaf
2751                 for (j = 0;j < leaf->numleafbrushes;j++)
2752                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2753                 // check if this leaf contains any collision surfaces (q3 patches)
2754                 for (j = 0;j < leaf->numleafsurfaces;j++)
2755                 {
2756                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2757                         if (surface->num_collisiontriangles)
2758                         {
2759                                 leaf->containscollisionsurfaces = true;
2760                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2761                         }
2762                 }
2763         }
2764 }
2765
2766 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2767 {
2768         int                     i, j, count, p;
2769         dnode_t         *in;
2770         mnode_t         *out;
2771
2772         in = (dnode_t *)(mod_base + l->fileofs);
2773         if (l->filelen % sizeof(*in))
2774                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2775         count = l->filelen / sizeof(*in);
2776         if (count == 0)
2777                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2778         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2779
2780         loadmodel->brush.data_nodes = out;
2781         loadmodel->brush.num_nodes = count;
2782
2783         for ( i=0 ; i<count ; i++, in++, out++)
2784         {
2785                 for (j=0 ; j<3 ; j++)
2786                 {
2787                         out->mins[j] = LittleShort(in->mins[j]);
2788                         out->maxs[j] = LittleShort(in->maxs[j]);
2789                 }
2790
2791                 p = LittleLong(in->planenum);
2792                 out->plane = loadmodel->brush.data_planes + p;
2793
2794                 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2795                 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2796
2797                 for (j=0 ; j<2 ; j++)
2798                 {
2799                         // LordHavoc: this code supports broken bsp files produced by
2800                         // arguire qbsp which can produce more than 32768 nodes, any value
2801                         // below count is assumed to be a node number, any other value is
2802                         // assumed to be a leaf number
2803                         p = (unsigned short)LittleShort(in->children[j]);
2804                         if (p < count)
2805                         {
2806                                 if (p < loadmodel->brush.num_nodes)
2807                                         out->children[j] = loadmodel->brush.data_nodes + p;
2808                                 else
2809                                 {
2810                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2811                                         // map it to the solid leaf
2812                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2813                                 }
2814                         }
2815                         else
2816                         {
2817                                 // note this uses 65535 intentionally, -1 is leaf 0
2818                                 p = 65535 - p;
2819                                 if (p < loadmodel->brush.num_leafs)
2820                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2821                                 else
2822                                 {
2823                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2824                                         // map it to the solid leaf
2825                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2826                                 }
2827                         }
2828                 }
2829         }
2830
2831         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2832 }
2833
2834 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2835 {
2836         dleaf_t *in;
2837         mleaf_t *out;
2838         int i, j, count, p;
2839
2840         in = (dleaf_t *)(mod_base + l->fileofs);
2841         if (l->filelen % sizeof(*in))
2842                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2843         count = l->filelen / sizeof(*in);
2844         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2845
2846         loadmodel->brush.data_leafs = out;
2847         loadmodel->brush.num_leafs = count;
2848         // get visleafs from the submodel data
2849         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2850         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2851         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2852         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2853
2854         for ( i=0 ; i<count ; i++, in++, out++)
2855         {
2856                 for (j=0 ; j<3 ; j++)
2857                 {
2858                         out->mins[j] = LittleShort(in->mins[j]);
2859                         out->maxs[j] = LittleShort(in->maxs[j]);
2860                 }
2861
2862                 // FIXME: this function could really benefit from some error checking
2863
2864                 out->contents = LittleLong(in->contents);
2865
2866                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2867                 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2868                 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2869                 {
2870                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", (int)(out->firstleafsurface - loadmodel->brush.data_leafsurfaces), (int)(out->firstleafsurface + out->numleafsurfaces - loadmodel->brush.data_leafsurfaces), 0, loadmodel->brush.num_leafsurfaces);
2871                         out->firstleafsurface = NULL;
2872                         out->numleafsurfaces = 0;
2873                 }
2874
2875                 out->clusterindex = i - 1;
2876                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2877                         out->clusterindex = -1;
2878
2879                 p = LittleLong(in->visofs);
2880                 // ignore visofs errors on leaf 0 (solid)
2881                 if (p >= 0 && out->clusterindex >= 0)
2882                 {
2883                         if (p >= loadmodel->brushq1.num_compressedpvs)
2884                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2885                         else
2886                                 Mod_Q1BSP_DecompressVis(loadmodel->brushq1.data_compressedpvs + p, loadmodel->brushq1.data_compressedpvs + loadmodel->brushq1.num_compressedpvs, loadmodel->brush.data_pvsclusters + out->clusterindex * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (out->clusterindex + 1) * loadmodel->brush.num_pvsclusterbytes);
2887                 }
2888
2889                 for (j = 0;j < 4;j++)
2890                         out->ambient_sound_level[j] = in->ambient_level[j];
2891
2892                 // FIXME: Insert caustics here
2893         }
2894 }
2895
2896 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2897 {
2898         int i, j;
2899         mleaf_t *leaf;
2900         const unsigned char *pvs;
2901         // if there's no vis data, assume supported (because everything is visible all the time)
2902         if (!loadmodel->brush.data_pvsclusters)
2903                 return true;
2904         // check all liquid leafs to see if they can see into empty leafs, if any
2905         // can we can assume this map supports r_wateralpha
2906         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2907         {
2908                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2909                 {
2910                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2911                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
2912                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2913                                         return true;
2914                 }
2915         }
2916         return false;
2917 }
2918
2919 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2920 {
2921         dclipnode_t *in;
2922         mclipnode_t *out;
2923         int                     i, count;
2924         hull_t          *hull;
2925
2926         in = (dclipnode_t *)(mod_base + l->fileofs);
2927         if (l->filelen % sizeof(*in))
2928                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2929         count = l->filelen / sizeof(*in);
2930         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2931
2932         loadmodel->brushq1.clipnodes = out;
2933         loadmodel->brushq1.numclipnodes = count;
2934
2935         for (i = 1; i < MAX_MAP_HULLS; i++)
2936         {
2937                 hull = &loadmodel->brushq1.hulls[i];
2938                 hull->clipnodes = out;
2939                 hull->firstclipnode = 0;
2940                 hull->lastclipnode = count-1;
2941                 hull->planes = loadmodel->brush.data_planes;
2942                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2943                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2944                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2945                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2946                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2947                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2948                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2949         }
2950
2951         for (i=0 ; i<count ; i++, out++, in++)
2952         {
2953                 out->planenum = LittleLong(in->planenum);
2954                 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2955                 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2956                 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2957                 if (out->children[0] >= count)
2958                         out->children[0] -= 65536;
2959                 if (out->children[1] >= count)
2960                         out->children[1] -= 65536;
2961                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2962                         Host_Error("Corrupt clipping hull(out of range planenum)");
2963         }
2964 }
2965
2966 //Duplicate the drawing hull structure as a clipping hull
2967 static void Mod_Q1BSP_MakeHull0(void)
2968 {
2969         mnode_t         *in;
2970         mclipnode_t *out;
2971         int                     i;
2972         hull_t          *hull;
2973
2974         hull = &loadmodel->brushq1.hulls[0];
2975
2976         in = loadmodel->brush.data_nodes;
2977         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2978
2979         hull->clipnodes = out;
2980         hull->firstclipnode = 0;
2981         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2982         hull->planes = loadmodel->brush.data_planes;
2983
2984         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2985         {
2986                 out->planenum = in->plane - loadmodel->brush.data_planes;
2987                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2988                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2989         }
2990 }
2991
2992 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2993 {
2994         int i, j;
2995         short *in;
2996
2997         in = (short *)(mod_base + l->fileofs);
2998         if (l->filelen % sizeof(*in))
2999                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3000         loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
3001         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3002
3003         for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3004         {
3005                 j = (unsigned short) LittleShort(in[i]);
3006                 if (j >= loadmodel->num_surfaces)
3007                         Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3008                 loadmodel->brush.data_leafsurfaces[i] = j;
3009         }
3010 }
3011
3012 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
3013 {
3014         int             i;
3015         int             *in;
3016
3017         in = (int *)(mod_base + l->fileofs);
3018         if (l->filelen % sizeof(*in))
3019                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3020         loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
3021         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3022
3023         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3024                 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
3025 }
3026
3027
3028 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
3029 {
3030         int                     i;
3031         mplane_t        *out;
3032         dplane_t        *in;
3033
3034         in = (dplane_t *)(mod_base + l->fileofs);
3035         if (l->filelen % sizeof(*in))
3036                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3037
3038         loadmodel->brush.num_planes = l->filelen / sizeof(*in);
3039         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3040
3041         for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
3042         {
3043                 out->normal[0] = LittleFloat(in->normal[0]);
3044                 out->normal[1] = LittleFloat(in->normal[1]);
3045                 out->normal[2] = LittleFloat(in->normal[2]);
3046                 out->dist = LittleFloat(in->dist);
3047
3048                 PlaneClassify(out);
3049         }
3050 }
3051
3052 static void Mod_Q1BSP_LoadMapBrushes(void)
3053 {
3054 #if 0
3055 // unfinished
3056         int submodel, numbrushes;
3057         qboolean firstbrush;
3058         char *text, *maptext;
3059         char mapfilename[MAX_QPATH];
3060         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3061         strlcat (mapfilename, ".map", sizeof (mapfilename));
3062         maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3063         if (!maptext)
3064                 return;
3065         text = maptext;
3066         if (!COM_ParseToken_Simple(&data, false, false, true))
3067                 return; // error
3068         submodel = 0;
3069         for (;;)
3070         {
3071                 if (!COM_ParseToken_Simple(&data, false, false, true))
3072                         break;
3073                 if (com_token[0] != '{')
3074                         return; // error
3075                 // entity
3076                 firstbrush = true;
3077                 numbrushes = 0;
3078                 maxbrushes = 256;
3079                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3080                 for (;;)
3081                 {
3082                         if (!COM_ParseToken_Simple(&data, false, false, true))
3083                                 return; // error
3084                         if (com_token[0] == '}')
3085                                 break; // end of entity
3086                         if (com_token[0] == '{')
3087                         {
3088                                 // brush
3089                                 if (firstbrush)
3090                                 {
3091                                         if (submodel)
3092                                         {
3093                                                 if (submodel > loadmodel->brush.numsubmodels)
3094                                                 {
3095                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3096                                                         model = NULL;
3097                                                 }
3098                                                 else
3099                                                         model = loadmodel->brush.submodels[submodel];
3100                                         }
3101                                         else
3102                                                 model = loadmodel;
3103                                 }
3104                                 for (;;)
3105                                 {
3106                                         if (!COM_ParseToken_Simple(&data, false, false, true))
3107                                                 return; // error
3108                                         if (com_token[0] == '}')
3109                                                 break; // end of brush
3110                                         // each brush face should be this format:
3111                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3112                                         // FIXME: support hl .map format
3113                                         for (pointnum = 0;pointnum < 3;pointnum++)
3114                                         {
3115                                                 COM_ParseToken_Simple(&data, false, false, true);
3116                                                 for (componentnum = 0;componentnum < 3;componentnum++)
3117                                                 {
3118                                                         COM_ParseToken_Simple(&data, false, false, true);
3119                                                         point[pointnum][componentnum] = atof(com_token);
3120                                                 }
3121                                                 COM_ParseToken_Simple(&data, false, false, true);
3122                                         }
3123                                         COM_ParseToken_Simple(&data, false, false, true);
3124                                         strlcpy(facetexture, com_token, sizeof(facetexture));
3125                                         COM_ParseToken_Simple(&data, false, false, true);
3126                                         //scroll_s = atof(com_token);
3127                                         COM_ParseToken_Simple(&data, false, false, true);
3128                                         //scroll_t = atof(com_token);
3129                                         COM_ParseToken_Simple(&data, false, false, true);
3130                                         //rotate = atof(com_token);
3131                                         COM_ParseToken_Simple(&data, false, false, true);
3132                                         //scale_s = atof(com_token);
3133                                         COM_ParseToken_Simple(&data, false, false, true);
3134                                         //scale_t = atof(com_token);
3135                                         TriangleNormal(point[0], point[1], point[2], planenormal);
3136                                         VectorNormalizeDouble(planenormal);
3137                                         planedist = DotProduct(point[0], planenormal);
3138                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3139                                 }
3140                                 continue;
3141                         }
3142                 }
3143         }
3144 #endif
3145 }
3146
3147
3148 #define MAX_PORTALPOINTS 64
3149
3150 typedef struct portal_s
3151 {
3152         mplane_t plane;
3153         mnode_t *nodes[2];              // [0] = front side of plane
3154         struct portal_s *next[2];
3155         int numpoints;
3156         double points[3*MAX_PORTALPOINTS];
3157         struct portal_s *chain; // all portals are linked into a list
3158 }
3159 portal_t;
3160
3161 static memexpandablearray_t portalarray;
3162
3163 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3164 {
3165         // process only nodes (leafs already had their box calculated)
3166         if (!node->plane)
3167                 return;
3168
3169         // calculate children first
3170         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3171         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3172
3173         // make combined bounding box from children
3174         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3175         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3176         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3177         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3178         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3179         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3180 }
3181
3182 static void Mod_Q1BSP_FinalizePortals(void)
3183 {
3184         int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3185         portal_t *p;
3186         mportal_t *portal;
3187         mvertex_t *point;
3188         mleaf_t *leaf, *endleaf;
3189
3190         // tally up portal and point counts and recalculate bounding boxes for all
3191         // leafs (because qbsp is very sloppy)
3192         leaf = loadmodel->brush.data_leafs;
3193         endleaf = leaf + loadmodel->brush.num_leafs;
3194         if (mod_recalculatenodeboxes.integer)
3195         {
3196                 for (;leaf < endleaf;leaf++)
3197                 {
3198                         VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
3199                         VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3200                 }
3201         }
3202         numportals = 0;
3203         numpoints = 0;
3204         for (portalindex = 0;portalindex < portalrange;portalindex++)
3205         {
3206                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3207                 if (!p)
3208                         continue;
3209                 // note: this check must match the one below or it will usually corrupt memory
3210                 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3211                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3212                 {
3213                         numportals += 2;
3214                         numpoints += p->numpoints * 2;
3215                 }
3216         }
3217         loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3218         loadmodel->brush.num_portals = numportals;
3219         loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3220         loadmodel->brush.num_portalpoints = numpoints;
3221         // clear all leaf portal chains
3222         for (i = 0;i < loadmodel->brush.num_leafs;i++)
3223                 loadmodel->brush.data_leafs[i].portals = NULL;
3224         // process all portals in the global portal chain, while freeing them
3225         portal = loadmodel->brush.data_portals;
3226         point = loadmodel->brush.data_portalpoints;
3227         for (portalindex = 0;portalindex < portalrange;portalindex++)
3228         {
3229                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3230                 if (!p)
3231                         continue;
3232                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3233                 {
3234                         // note: this check must match the one above or it will usually corrupt memory
3235                         // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3236                         if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3237                         {
3238                                 // first make the back to front portal(forward portal)
3239                                 portal->points = point;
3240                                 portal->numpoints = p->numpoints;
3241                                 portal->plane.dist = p->plane.dist;
3242                                 VectorCopy(p->plane.normal, portal->plane.normal);
3243                                 portal->here = (mleaf_t *)p->nodes[1];
3244                                 portal->past = (mleaf_t *)p->nodes[0];
3245                                 // copy points
3246                                 for (j = 0;j < portal->numpoints;j++)
3247                                 {
3248                                         VectorCopy(p->points + j*3, point->position);
3249                                         point++;
3250                                 }
3251                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3252                                 PlaneClassify(&portal->plane);
3253
3254                                 // link into leaf's portal chain
3255                                 portal->next = portal->here->portals;
3256                                 portal->here->portals = portal;
3257
3258                                 // advance to next portal
3259                                 portal++;
3260
3261                                 // then make the front to back portal(backward portal)
3262                                 portal->points = point;
3263                                 portal->numpoints = p->numpoints;
3264                                 portal->plane.dist = -p->plane.dist;
3265                                 VectorNegate(p->plane.normal, portal->plane.normal);
3266                                 portal->here = (mleaf_t *)p->nodes[0];
3267                                 portal->past = (mleaf_t *)p->nodes[1];
3268                                 // copy points
3269                                 for (j = portal->numpoints - 1;j >= 0;j--)
3270                                 {
3271                                         VectorCopy(p->points + j*3, point->position);
3272                                         point++;
3273                                 }
3274                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3275                                 PlaneClassify(&portal->plane);
3276
3277                                 // link into leaf's portal chain
3278                                 portal->next = portal->here->portals;
3279                                 portal->here->portals = portal;
3280
3281                                 // advance to next portal
3282                                 portal++;
3283                         }
3284                         // add the portal's polygon points to the leaf bounding boxes
3285                         if (mod_recalculatenodeboxes.integer)
3286                         {
3287                                 for (i = 0;i < 2;i++)
3288                                 {
3289                                         leaf = (mleaf_t *)p->nodes[i];
3290                                         for (j = 0;j < p->numpoints;j++)
3291                                         {
3292                                                 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3293                                                 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3294                                                 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3295                                                 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3296                                                 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3297                                                 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3298                                         }
3299                                 }
3300                         }
3301                 }
3302         }
3303         // now recalculate the node bounding boxes from the leafs
3304         if (mod_recalculatenodeboxes.integer)
3305                 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3306 }
3307
3308 /*
3309 =============
3310 AddPortalToNodes
3311 =============
3312 */
3313 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3314 {
3315         if (!front)
3316                 Host_Error("AddPortalToNodes: NULL front node");
3317         if (!back)
3318                 Host_Error("AddPortalToNodes: NULL back node");
3319         if (p->nodes[0] || p->nodes[1])
3320                 Host_Error("AddPortalToNodes: already included");
3321         // note: front == back is handled gracefully, because leaf 0 is the shared solid leaf, it can often have portals with the same leaf on both sides
3322
3323         p->nodes[0] = front;
3324         p->next[0] = (portal_t *)front->portals;
3325         front->portals = (mportal_t *)p;
3326
3327         p->nodes[1] = back;
3328         p->next[1] = (portal_t *)back->portals;
3329         back->portals = (mportal_t *)p;
3330 }
3331
3332 /*
3333 =============
3334 RemovePortalFromNode
3335 =============
3336 */
3337 static void RemovePortalFromNodes(portal_t *portal)
3338 {
3339         int i;
3340         mnode_t *node;
3341         void **portalpointer;
3342         portal_t *t;
3343         for (i = 0;i < 2;i++)
3344         {
3345                 node = portal->nodes[i];
3346
3347                 portalpointer = (void **) &node->portals;
3348                 while (1)
3349                 {
3350                         t = (portal_t *)*portalpointer;
3351                         if (!t)
3352                                 Host_Error("RemovePortalFromNodes: portal not in leaf");
3353
3354                         if (t == portal)
3355                         {
3356                                 if (portal->nodes[0] == node)
3357                                 {
3358                                         *portalpointer = portal->next[0];
3359                                         portal->nodes[0] = NULL;
3360                                 }
3361                                 else if (portal->nodes[1] == node)
3362                                 {
3363                                         *portalpointer = portal->next[1];
3364                                         portal->nodes[1] = NULL;
3365                                 }
3366                                 else
3367                                         Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3368                                 break;
3369                         }
3370
3371                         if (t->nodes[0] == node)
3372                                 portalpointer = (void **) &t->next[0];
3373                         else if (t->nodes[1] == node)
3374                                 portalpointer = (void **) &t->next[1];
3375                         else
3376                                 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3377                 }
3378         }
3379 }
3380
3381 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3382 static double *portalpointsbuffer;
3383 static int portalpointsbufferoffset;
3384 static int portalpointsbuffersize;
3385 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3386 {
3387         int i, side;
3388         mnode_t *front, *back, *other_node;
3389         mplane_t clipplane, *plane;
3390         portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3391         int numfrontpoints, numbackpoints;
3392         double *frontpoints, *backpoints;
3393
3394         // if a leaf, we're done
3395         if (!node->plane)
3396                 return;
3397
3398         // get some space for our clipping operations to use
3399         if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3400         {
3401                 portalpointsbuffersize = portalpointsbufferoffset * 2;
3402                 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3403         }
3404         frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3405         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3406         backpoints = portalpointsbuffer + portalpointsbufferoffset;
3407         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3408
3409         plane = node->plane;
3410
3411         front = node->children[0];
3412         back = node->children[1];
3413         if (front == back)
3414                 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3415
3416         // create the new portal by generating a polygon for the node plane,
3417         // and clipping it by all of the other portals(which came from nodes above this one)
3418         nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3419         nodeportal->plane = *plane;
3420
3421         // TODO: calculate node bounding boxes during recursion and calculate a maximum plane size accordingly to improve precision (as most maps do not need 1 billion unit plane polygons)
3422         PolygonD_QuadForPlane(nodeportal->points, nodeportal->plane.normal[0], nodeportal->plane.normal[1], nodeportal->plane.normal[2], nodeportal->plane.dist, 1024.0*1024.0*1024.0);
3423         nodeportal->numpoints = 4;
3424         side = 0;       // shut up compiler warning
3425         for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3426         {
3427                 clipplane = portal->plane;
3428                 if (portal->nodes[0] == portal->nodes[1])
3429                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3430                 if (portal->nodes[0] == node)
3431                         side = 0;
3432                 else if (portal->nodes[1] == node)
3433                 {
3434                         clipplane.dist = -clipplane.dist;
3435                         VectorNegate(clipplane.normal, clipplane.normal);
3436                         side = 1;
3437                 }
3438                 else
3439                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3440
3441                 for (i = 0;i < nodeportal->numpoints*3;i++)
3442                         frontpoints[i] = nodeportal->points[i];
3443                 PolygonD_Divide(nodeportal->numpoints, frontpoints, clipplane.normal[0], clipplane.normal[1], clipplane.normal[2], clipplane.dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, nodeportal->points, &nodeportal->numpoints, 0, NULL, NULL, NULL);
3444                 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3445                         break;
3446         }
3447
3448         if (nodeportal->numpoints < 3)
3449         {
3450                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3451                 nodeportal->numpoints = 0;
3452         }
3453         else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3454         {
3455                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3456                 nodeportal->numpoints = 0;
3457         }
3458
3459         AddPortalToNodes(nodeportal, front, back);
3460
3461         // split the portals of this node along this node's plane and assign them to the children of this node
3462         // (migrating the portals downward through the tree)
3463         for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3464         {
3465                 if (portal->nodes[0] == portal->nodes[1])
3466                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3467                 if (portal->nodes[0] == node)
3468                         side = 0;
3469                 else if (portal->nodes[1] == node)
3470                         side = 1;
3471                 else
3472                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3473                 nextportal = portal->next[side];
3474                 if (!portal->numpoints)
3475                         continue;
3476
3477                 other_node = portal->nodes[!side];
3478                 RemovePortalFromNodes(portal);
3479
3480                 // cut the portal into two portals, one on each side of the node plane
3481                 PolygonD_Divide(portal->numpoints, portal->points, plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, frontpoints, &numfrontpoints, MAX_PORTALPOINTS, backpoints, &numbackpoints, NULL);
3482
3483                 if (!numfrontpoints)
3484                 {
3485                         if (side == 0)
3486                                 AddPortalToNodes(portal, back, other_node);
3487                         else
3488                                 AddPortalToNodes(portal, other_node, back);
3489                         continue;
3490                 }
3491                 if (!numbackpoints)
3492                 {
3493                         if (side == 0)
3494                                 AddPortalToNodes(portal, front, other_node);
3495                         else
3496                                 AddPortalToNodes(portal, other_node, front);
3497                         continue;
3498                 }
3499
3500                 // the portal is split
3501                 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3502                 temp = splitportal->chain;
3503                 *splitportal = *portal;
3504                 splitportal->chain = temp;
3505                 for (i = 0;i < numbackpoints*3;i++)
3506                         splitportal->points[i] = backpoints[i];
3507                 splitportal->numpoints = numbackpoints;
3508                 for (i = 0;i < numfrontpoints*3;i++)
3509                         portal->points[i] = frontpoints[i];
3510                 portal->numpoints = numfrontpoints;
3511
3512                 if (side == 0)
3513                 {
3514                         AddPortalToNodes(portal, front, other_node);
3515                         AddPortalToNodes(splitportal, back, other_node);
3516                 }
3517                 else
3518                 {
3519                         AddPortalToNodes(portal, other_node, front);
3520                         AddPortalToNodes(splitportal, other_node, back);
3521                 }
3522         }
3523
3524         Mod_Q1BSP_RecursiveNodePortals(front);
3525         Mod_Q1BSP_RecursiveNodePortals(back);
3526
3527         portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3528 }
3529
3530 static void Mod_Q1BSP_MakePortals(void)
3531 {
3532         Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3533         portalpointsbufferoffset = 0;
3534         portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3535         portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3536         Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3537         Mem_Free(portalpointsbuffer);
3538         portalpointsbuffer = NULL;
3539         portalpointsbufferoffset = 0;
3540         portalpointsbuffersize = 0;
3541         Mod_Q1BSP_FinalizePortals();
3542         Mem_ExpandableArray_FreeArray(&portalarray);
3543 }
3544
3545 //Returns PVS data for a given point
3546 //(note: can return NULL)
3547 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3548 {
3549         mnode_t *node;
3550         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3551         while (node->plane)
3552                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3553         if (((mleaf_t *)node)->clusterindex >= 0)
3554                 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3555         else
3556                 return NULL;
3557 }
3558
3559 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
3560 {
3561         while (node->plane)
3562         {
3563                 float d = PlaneDiff(org, node->plane);
3564                 if (d > radius)
3565                         node = node->children[0];
3566                 else if (d < -radius)
3567                         node = node->children[1];
3568                 else
3569                 {
3570                         // go down both sides
3571                         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3572                         node = node->children[1];
3573                 }
3574         }
3575         // if this leaf is in a cluster, accumulate the pvs bits
3576         if (((mleaf_t *)node)->clusterindex >= 0)
3577         {
3578                 int i;
3579                 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3580                 for (i = 0;i < pvsbytes;i++)
3581                         pvsbuffer[i] |= pvs[i];
3582         }
3583 }
3584
3585 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3586 //of the given point.
3587 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3588 {
3589         int bytes = model->brush.num_pvsclusterbytes;
3590         bytes = min(bytes, pvsbufferlength);
3591         if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3592         {
3593                 memset(pvsbuffer, 0xFF, bytes);
3594                 return bytes;
3595         }
3596         if (!merge)
3597                 memset(pvsbuffer, 0, bytes);
3598         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3599         return bytes;
3600 }
3601
3602 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3603 {
3604         vec3_t size;
3605         const hull_t *hull;
3606
3607         VectorSubtract(inmaxs, inmins, size);
3608         if (cmodel->brush.ishlbsp)
3609         {
3610                 if (size[0] < 3)
3611                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3612                 else if (size[0] <= 32)
3613                 {
3614                         if (size[2] < 54) // pick the nearest of 36 or 72
3615                                 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3616                         else
3617                                 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3618                 }
3619                 else
3620                         hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3621         }
3622         else
3623         {
3624                 if (size[0] < 3)
3625                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3626                 else if (size[0] <= 32)
3627                         hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3628                 else
3629                         hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3630         }
3631         VectorCopy(inmins, outmins);
3632         VectorAdd(inmins, hull->clip_size, outmaxs);
3633 }
3634
3635 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3636 {
3637         int j;
3638         int numshadowmeshtriangles = 0;
3639         msurface_t *surface;
3640         if (cls.state == ca_dedicated)
3641                 return 0;
3642         // make a single combined shadow mesh to allow optimized shadow volume creation
3643
3644         for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3645         {
3646                 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3647                 numshadowmeshtriangles += surface->num_triangles;
3648         }
3649         mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3650         for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3651                 if (surface->num_triangles > 0)
3652                         Mod_ShadowMesh_AddMesh(mod->mempool, mod->brush.shadowmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
3653         mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3654         if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3655                 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3656
3657         return numshadowmeshtriangles;
3658 }
3659
3660 void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask);
3661
3662 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3663 {
3664         int i, j, k;
3665         dheader_t *header;
3666         dmodel_t *bm;
3667         float dist, modelyawradius, modelradius;
3668         msurface_t *surface;
3669         hullinfo_t hullinfo;
3670         int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3671         model_brush_lightstyleinfo_t styleinfo[256];
3672         unsigned char *datapointer;
3673
3674         mod->modeldatatypestring = "Q1BSP";
3675
3676         mod->type = mod_brushq1;
3677
3678         header = (dheader_t *)buffer;
3679
3680         i = LittleLong(header->version);
3681         if (i != BSPVERSION && i != 30)
3682                 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3683         mod->brush.ishlbsp = i == 30;
3684
3685 // fill in hull info
3686         VectorClear (hullinfo.hullsizes[0][0]);
3687         VectorClear (hullinfo.hullsizes[0][1]);
3688         if (mod->brush.ishlbsp)
3689         {
3690                 mod->modeldatatypestring = "HLBSP";
3691
3692                 hullinfo.filehulls = 4;
3693                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3694                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3695                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3696                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3697                 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3698                 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3699         }
3700         else
3701         {
3702                 hullinfo.filehulls = 4;
3703                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3704                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3705                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3706                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3707         }
3708
3709 // read lumps
3710         mod_base = (unsigned char*)buffer;
3711         for (i = 0; i < HEADER_LUMPS; i++)
3712         {
3713                 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3714                 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3715         }
3716
3717         mod->soundfromcenter = true;
3718         mod->TraceBox = Mod_Q1BSP_TraceBox;
3719         if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
3720                 mod->TraceLine = Mod_Q1BSP_TraceLineAgainstSurfaces; // LordHavoc: use the surface-hitting version of TraceLine in all cases
3721         else
3722                 mod->TraceLine = Mod_Q1BSP_TraceLine;
3723         mod->TracePoint = Mod_Q1BSP_TracePoint;
3724         mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3725         mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3726         mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3727         mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3728         mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3729         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3730         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3731         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3732         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3733         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3734         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3735         mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3736         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3737         mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3738         mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3739         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3740         mod->Draw = R_Q1BSP_Draw;
3741         mod->DrawDepth = R_Q1BSP_DrawDepth;
3742         mod->DrawDebug = R_Q1BSP_DrawDebug;
3743         mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3744         mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3745         mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3746         mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3747         mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3748         mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3749         mod->DrawLight = R_Q1BSP_DrawLight;
3750
3751 // load into heap
3752
3753         mod->brush.qw_md4sum = 0;
3754         mod->brush.qw_md4sum2 = 0;
3755         for (i = 0;i < HEADER_LUMPS;i++)
3756         {
3757                 int temp;
3758                 if (i == LUMP_ENTITIES)
3759                         continue;
3760                 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3761                 mod->brush.qw_md4sum ^= LittleLong(temp);
3762                 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3763                         continue;
3764                 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3765                 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3766         }
3767
3768         Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3769         Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3770         Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3771         Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3772         Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3773         Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3774         Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3775         Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3776         Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3777         Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3778         Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3779         // load submodels before leafs because they contain the number of vis leafs
3780         Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3781         Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3782         Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3783         Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3784
3785         // check if the map supports transparent water rendering
3786         loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3787
3788         if (mod->brushq1.data_compressedpvs)
3789                 Mem_Free(mod->brushq1.data_compressedpvs);
3790         mod->brushq1.data_compressedpvs = NULL;
3791         mod->brushq1.num_compressedpvs = 0;
3792
3793         Mod_Q1BSP_MakeHull0();
3794         if (mod_bsp_portalize.integer)
3795                 Mod_Q1BSP_MakePortals();
3796
3797         mod->numframes = 2;             // regular and alternate animation
3798         mod->numskins = 1;
3799
3800         // make a single combined shadow mesh to allow optimized shadow volume creation
3801         Mod_Q1BSP_CreateShadowMesh(loadmodel);
3802
3803         if (loadmodel->brush.numsubmodels)
3804                 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3805
3806         // LordHavoc: to clear the fog around the original quake submodel code, I
3807         // will explain:
3808         // first of all, some background info on the submodels:
3809         // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3810         // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3811         // now the weird for loop itself:
3812         // the loop functions in an odd way, on each iteration it sets up the
3813         // current 'mod' model (which despite the confusing code IS the model of
3814         // the number i), at the end of the loop it duplicates the model to become
3815         // the next submodel, and loops back to set up the new submodel.
3816
3817         // LordHavoc: now the explanation of my sane way (which works identically):
3818         // set up the world model, then on each submodel copy from the world model
3819         // and set up the submodel with the respective model info.
3820         totalstylesurfaces = 0;
3821         totalstyles = 0;
3822         for (i = 0;i < mod->brush.numsubmodels;i++)
3823         {
3824                 memset(stylecounts, 0, sizeof(stylecounts));
3825                 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3826                 {
3827                         surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3828                         for (j = 0;j < MAXLIGHTMAPS;j++)
3829                                 stylecounts[surface->lightmapinfo->styles[j]]++;
3830                 }
3831                 for (k = 0;k < 255;k++)
3832                 {
3833                         totalstyles++;
3834                         if (stylecounts[k])
3835                                 totalstylesurfaces += stylecounts[k];
3836                 }
3837         }
3838         datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3839         for (i = 0;i < mod->brush.numsubmodels;i++)
3840         {
3841                 // LordHavoc: this code was originally at the end of this loop, but
3842                 // has been transformed to something more readable at the start here.
3843
3844                 if (i > 0)
3845                 {
3846                         char name[10];
3847                         // duplicate the basic information
3848                         dpsnprintf(name, sizeof(name), "*%i", i);
3849                         mod = Mod_FindName(name, loadmodel->name);
3850                         // copy the base model to this one
3851                         *mod = *loadmodel;
3852                         // rename the clone back to its proper name
3853                         strlcpy(mod->name, name, sizeof(mod->name));
3854                         mod->brush.parentmodel = loadmodel;
3855                         // textures and memory belong to the main model
3856                         mod->texturepool = NULL;
3857                         mod->mempool = NULL;
3858                         mod->brush.GetPVS = NULL;
3859                         mod->brush.FatPVS = NULL;
3860                         mod->brush.BoxTouchingPVS = NULL;
3861                         mod->brush.BoxTouchingLeafPVS = NULL;
3862                         mod->brush.BoxTouchingVisibleLeafs = NULL;
3863                         mod->brush.FindBoxClusters = NULL;
3864                         mod->brush.LightPoint = NULL;
3865                         mod->brush.AmbientSoundLevelsForPoint = NULL;
3866                 }
3867
3868                 mod->brush.submodel = i;
3869
3870                 if (loadmodel->brush.submodels)
3871                         loadmodel->brush.submodels[i] = mod;
3872
3873                 bm = &mod->brushq1.submodels[i];
3874
3875                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3876                 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3877                 {
3878                         mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3879                         mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3880                 }
3881
3882                 mod->firstmodelsurface = bm->firstface;
3883                 mod->nummodelsurfaces = bm->numfaces;
3884
3885                 // set node/leaf parents for this submodel
3886                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3887
3888                 // make the model surface list (used by shadowing/lighting)
3889                 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3890                 Mod_MakeSortedSurfaces(mod);
3891
3892                 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3893                 // (previously this code measured the radius of the vertices of surfaces in the submodel, but that broke submodels that contain only CLIP brushes, which do not produce surfaces)
3894                 VectorCopy(bm->mins, mod->normalmins);
3895                 VectorCopy(bm->maxs, mod->normalmaxs);
3896                 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3897                 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3898                 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3899                 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3900                 modelradius = modelyawradius + modelradius * modelradius;
3901                 modelyawradius = sqrt(modelyawradius);
3902                 modelradius = sqrt(modelradius);
3903                 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3904                 mod->yawmins[2] = mod->normalmins[2];
3905                 mod->yawmaxs[0] = mod->yawmaxs[1] =  modelyawradius;
3906                 mod->yawmaxs[2] = mod->normalmaxs[2];
3907                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3908                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] =  modelradius;
3909                 mod->radius = modelradius;
3910                 mod->radius2 = modelradius * modelradius;
3911
3912                 // this gets altered below if sky or water is used
3913                 mod->DrawSky = NULL;
3914                 mod->DrawAddWaterPlanes = NULL;
3915
3916                 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3917                 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3918                 if (mod->nummodelsurfaces)
3919                 {
3920                         for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3921                                 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3922                                         break;
3923                         if (j < mod->nummodelsurfaces)
3924                                 mod->DrawSky = R_Q1BSP_DrawSky;
3925
3926                         for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3927                                 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
3928                                         break;
3929                         if (j < mod->nummodelsurfaces)
3930                                 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3931
3932                         // build lightstyle update chains
3933                         // (used to rapidly mark lightmapupdateflags on many surfaces
3934                         // when d_lightstylevalue changes)
3935                         memset(stylecounts, 0, sizeof(stylecounts));
3936                         for (k = 0;k < mod->nummodelsurfaces;k++)
3937                         {
3938                                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3939                                 for (j = 0;j < MAXLIGHTMAPS;j++)
3940                                         stylecounts[surface->lightmapinfo->styles[j]]++;
3941                         }
3942                         mod->brushq1.num_lightstyles = 0;
3943                         for (k = 0;k < 255;k++)
3944                         {
3945                                 if (stylecounts[k])
3946                                 {
3947                                         styleinfo[mod->brushq1.num_lightstyles].style = k;
3948                                         styleinfo[mod->brushq1.num_lightstyles].value = 0;
3949                                         styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3950                                         styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3951                                         remapstyles[k] = mod->brushq1.num_lightstyles;
3952                                         mod->brushq1.num_lightstyles++;
3953                                 }
3954                         }
3955                         for (k = 0;k < mod->nummodelsurfaces;k++)
3956                         {
3957                                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3958                                 for (j = 0;j < MAXLIGHTMAPS;j++)
3959                                 {
3960                                         if (surface->lightmapinfo->styles[j] != 255)
3961                                         {
3962                                                 int r = remapstyles[surface->lightmapinfo->styles[j]];
3963                                                 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3964                                         }
3965                                 }
3966                         }
3967                         mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3968                         memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3969                 }
3970                 else
3971                 {
3972                         // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3973                         Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3974                 }
3975                 //mod->brushq1.num_visleafs = bm->visleafs;
3976
3977                 // build a Bounding Interval Hierarchy for culling triangles in light rendering
3978                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
3979
3980                 if (mod_q1bsp_polygoncollisions.integer)
3981                 {
3982                         mod->collision_bih = mod->render_bih;
3983                         // point traces and contents checks still use the bsp tree
3984                         mod->TraceLine = Mod_CollisionBIH_TraceLine;
3985                         mod->TraceBox = Mod_CollisionBIH_TraceBox;
3986                         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
3987                         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
3988                 }
3989
3990                 // generate VBOs and other shared data before cloning submodels
3991                 if (i == 0)
3992                 {
3993                         Mod_BuildVBOs();
3994                         Mod_Q1BSP_LoadMapBrushes();
3995                         //Mod_Q1BSP_ProcessLightList();
3996                 }
3997         }
3998
3999         Con_DPrintf("Stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
4000 }
4001
4002 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4003 {
4004 }
4005
4006 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4007 {
4008 /*
4009         d_t *in;
4010         m_t *out;
4011         int i, count;
4012
4013         in = (void *)(mod_base + l->fileofs);
4014         if (l->filelen % sizeof(*in))
4015                 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4016         count = l->filelen / sizeof(*in);
4017         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4018
4019         loadmodel-> = out;
4020         loadmodel->num = count;
4021
4022         for (i = 0;i < count;i++, in++, out++)
4023         {
4024         }
4025 */
4026 }
4027
4028 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4029 {
4030 /*
4031         d_t *in;
4032         m_t *out;
4033         int i, count;
4034
4035         in = (void *)(mod_base + l->fileofs);
4036         if (l->filelen % sizeof(*in))
4037                 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4038         count = l->filelen / sizeof(*in);
4039         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4040
4041         loadmodel-> = out;
4042         loadmodel->num = count;
4043
4044         for (i = 0;i < count;i++, in++, out++)
4045         {
4046         }
4047 */
4048 }
4049
4050 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4051 {
4052 /*
4053         d_t *in;
4054         m_t *out;
4055         int i, count;
4056
4057         in = (void *)(mod_base + l->fileofs);
4058         if (l->filelen % sizeof(*in))
4059                 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4060         count = l->filelen / sizeof(*in);
4061         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4062
4063         loadmodel-> = out;
4064         loadmodel->num = count;
4065
4066         for (i = 0;i < count;i++, in++, out++)
4067         {
4068         }
4069 */
4070 }
4071
4072 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4073 {
4074 /*
4075         d_t *in;
4076         m_t *out;
4077         int i, count;
4078
4079         in = (void *)(mod_base + l->fileofs);
4080         if (l->filelen % sizeof(*in))
4081                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4082         count = l->filelen / sizeof(*in);
4083         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4084
4085         loadmodel-> = out;
4086         loadmodel->num = count;
4087
4088         for (i = 0;i < count;i++, in++, out++)
4089         {
4090         }
4091 */
4092 }
4093
4094 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4095 {
4096 /*
4097         d_t *in;
4098         m_t *out;
4099         int i, count;
4100
4101         in = (void *)(mod_base + l->fileofs);
4102         if (l->filelen % sizeof(*in))
4103                 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4104         count = l->filelen / sizeof(*in);
4105         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4106
4107         loadmodel-> = out;
4108         loadmodel->num = count;
4109
4110         for (i = 0;i < count;i++, in++, out++)
4111         {
4112         }
4113 */
4114 }
4115
4116 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4117 {
4118 /*
4119         d_t *in;
4120         m_t *out;
4121         int i, count;
4122
4123         in = (void *)(mod_base + l->fileofs);
4124         if (l->filelen % sizeof(*in))
4125                 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4126         count = l->filelen / sizeof(*in);
4127         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4128
4129         loadmodel-> = out;
4130         loadmodel->num = count;
4131
4132         for (i = 0;i < count;i++, in++, out++)
4133         {
4134         }
4135 */
4136 }
4137
4138 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4139 {
4140 /*
4141         d_t *in;
4142         m_t *out;
4143         int i, count;
4144
4145         in = (void *)(mod_base + l->fileofs);
4146         if (l->filelen % sizeof(*in))
4147                 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4148         count = l->filelen / sizeof(*in);
4149         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4150
4151         loadmodel-> = out;
4152         loadmodel->num = count;
4153
4154         for (i = 0;i < count;i++, in++, out++)
4155         {
4156         }
4157 */
4158 }
4159
4160 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4161 {
4162 /*
4163         d_t *in;
4164         m_t *out;
4165         int i, count;
4166
4167         in = (void *)(mod_base + l->fileofs);
4168         if (l->filelen % sizeof(*in))
4169                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4170         count = l->filelen / sizeof(*in);
4171         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4172
4173         loadmodel-> = out;
4174         loadmodel->num = count;
4175
4176         for (i = 0;i < count;i++, in++, out++)
4177         {
4178         }
4179 */
4180 }
4181
4182 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4183 {
4184 /*
4185         d_t *in;
4186         m_t *out;
4187         int i, count;
4188
4189         in = (void *)(mod_base + l->fileofs);
4190         if (l->filelen % sizeof(*in))
4191                 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4192         count = l->filelen / sizeof(*in);
4193         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4194
4195         loadmodel-> = out;
4196         loadmodel->num = count;
4197
4198         for (i = 0;i < count;i++, in++, out++)
4199         {
4200         }
4201 */
4202 }
4203
4204 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4205 {
4206 /*
4207         d_t *in;
4208         m_t *out;
4209         int i, count;
4210
4211         in = (void *)(mod_base + l->fileofs);
4212         if (l->filelen % sizeof(*in))
4213                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4214         count = l->filelen / sizeof(*in);
4215         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4216
4217         loadmodel-> = out;
4218         loadmodel->num = count;
4219
4220         for (i = 0;i < count;i++, in++, out++)
4221         {
4222         }
4223 */
4224 }
4225
4226 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4227 {
4228 /*
4229         d_t *in;
4230         m_t *out;
4231         int i, count;
4232
4233         in = (void *)(mod_base + l->fileofs);
4234         if (l->filelen % sizeof(*in))
4235                 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4236         count = l->filelen / sizeof(*in);
4237         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4238
4239         loadmodel-> = out;
4240         loadmodel->num = count;
4241
4242         for (i = 0;i < count;i++, in++, out++)
4243         {
4244         }
4245 */
4246 }
4247
4248 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4249 {
4250 /*
4251         d_t *in;
4252         m_t *out;
4253         int i, count;
4254
4255         in = (void *)(mod_base + l->fileofs);
4256         if (l->filelen % sizeof(*in))
4257                 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4258         count = l->filelen / sizeof(*in);
4259         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4260
4261         loadmodel-> = out;
4262         loadmodel->num = count;
4263
4264         for (i = 0;i < count;i++, in++, out++)
4265         {
4266         }
4267 */
4268 }
4269
4270 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4271 {
4272 /*
4273         d_t *in;
4274         m_t *out;
4275         int i, count;
4276
4277         in = (void *)(mod_base + l->fileofs);
4278         if (l->filelen % sizeof(*in))
4279                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4280         count = l->filelen / sizeof(*in);
4281         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4282
4283         loadmodel-> = out;
4284         loadmodel->num = count;
4285
4286         for (i = 0;i < count;i++, in++, out++)
4287         {
4288         }
4289 */
4290 }
4291
4292 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4293 {
4294 /*
4295         d_t *in;
4296         m_t *out;
4297         int i, count;
4298
4299         in = (void *)(mod_base + l->fileofs);
4300         if (l->filelen % sizeof(*in))
4301                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4302         count = l->filelen / sizeof(*in);
4303         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4304
4305         loadmodel-> = out;
4306         loadmodel->num = count;
4307
4308         for (i = 0;i < count;i++, in++, out++)
4309         {
4310         }
4311 */
4312 }
4313
4314 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4315 {
4316 /*
4317         d_t *in;
4318         m_t *out;
4319         int i, count;
4320
4321         in = (void *)(mod_base + l->fileofs);
4322         if (l->filelen % sizeof(*in))
4323                 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4324         count = l->filelen / sizeof(*in);
4325         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4326
4327         loadmodel-> = out;
4328         loadmodel->num = count;
4329
4330         for (i = 0;i < count;i++, in++, out++)
4331         {
4332         }
4333 */
4334 }
4335
4336 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4337 {
4338 /*
4339         d_t *in;
4340         m_t *out;
4341         int i, count;
4342
4343         in = (void *)(mod_base + l->fileofs);
4344         if (l->filelen % sizeof(*in))
4345                 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4346         count = l->filelen / sizeof(*in);
4347         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4348
4349         loadmodel-> = out;
4350         loadmodel->num = count;
4351
4352         for (i = 0;i < count;i++, in++, out++)
4353         {
4354         }
4355 */
4356 }
4357
4358 static void Mod_Q2BSP_LoadModels(lump_t *l)
4359 {
4360 /*
4361         d_t *in;
4362         m_t *out;
4363         int i, count;
4364
4365         in = (void *)(mod_base + l->fileofs);
4366         if (l->filelen % sizeof(*in))
4367                 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4368         count = l->filelen / sizeof(*in);
4369         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4370
4371         loadmodel-> = out;
4372         loadmodel->num = count;
4373
4374         for (i = 0;i < count;i++, in++, out++)
4375         {
4376         }
4377 */
4378 }
4379
4380 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4381 {
4382         int i;
4383         q2dheader_t *header;
4384
4385         Host_Error("Mod_Q2BSP_Load: not yet implemented");
4386
4387         mod->modeldatatypestring = "Q2BSP";
4388
4389         mod->type = mod_brushq2;
4390
4391         header = (q2dheader_t *)buffer;
4392
4393         i = LittleLong(header->version);
4394         if (i != Q2BSPVERSION)
4395                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4396
4397         mod_base = (unsigned char *)header;
4398
4399         // swap all the lumps
4400         for (i = 0;i < (int) sizeof(*header) / 4;i++)
4401                 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4402
4403         mod->brush.qw_md4sum = 0;
4404         mod->brush.qw_md4sum2 = 0;
4405         for (i = 0;i < Q2HEADER_LUMPS;i++)
4406         {
4407                 if (i == Q2LUMP_ENTITIES)
4408                         continue;
4409                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4410                 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4411                         continue;
4412                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4413         }
4414
4415         Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4416         Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4417         Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4418         Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4419         Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4420         Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4421         Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4422         Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4423         Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4424         Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4425         Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4426         Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4427         Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4428         Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4429         Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4430         Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4431         Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4432         // LordHavoc: must go last because this makes the submodels
4433         Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4434 }
4435
4436 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4437 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4438
4439 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4440 {
4441         const char *data;
4442         char key[128], value[MAX_INPUTLINE];
4443         float v[3];
4444         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4445         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4446         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4447         if (!l->filelen)
4448                 return;
4449         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4450         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4451         loadmodel->brush.entities[l->filelen] = 0;
4452         data = loadmodel->brush.entities;
4453         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4454         // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4455         loadmodel->brushq3.deluxemapping = false;
4456         if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4457         {
4458                 while (1)
4459                 {
4460                         if (!COM_ParseToken_Simple(&data, false, false, true))
4461                                 break; // error
4462                         if (com_token[0] == '}')
4463                                 break; // end of worldspawn
4464                         if (com_token[0] == '_')
4465                                 strlcpy(key, com_token + 1, sizeof(key));
4466                         else
4467                                 strlcpy(key, com_token, sizeof(key));
4468                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
4469                                 key[strlen(key)-1] = 0;
4470                         if (!COM_ParseToken_Simple(&data, false, false, true))
4471                                 break; // error
4472                         strlcpy(value, com_token, sizeof(value));
4473                         if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4474                         {
4475 #if _MSC_VER >= 1400
4476 #define sscanf sscanf_s
4477 #endif
4478 #if 0
4479                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4480                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4481 #else
4482                                 VectorSet(v, 64, 64, 128);
4483                                 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4484                                         Con_Printf("Mod_Q3BSP_LoadEntities: funny gridsize \"%s\" in %s, interpreting as \"%f %f %f\" to match q3map2's parsing\n", value, loadmodel->name, v[0], v[1], v[2]);
4485                                 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4486                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4487 #endif
4488                         }
4489                         else if (!strcmp("deluxeMaps", key))
4490                         {
4491                                 if (!strcmp(com_token, "1"))
4492                                 {
4493                                         loadmodel->brushq3.deluxemapping = true;
4494                                         loadmodel->brushq3.deluxemapping_modelspace = true;
4495                                 }
4496                                 else if (!strcmp(com_token, "2"))
4497                                 {
4498                                         loadmodel->brushq3.deluxemapping = true;
4499                                         loadmodel->brushq3.deluxemapping_modelspace = false;
4500                                 }
4501                         }
4502                 }
4503         }
4504 }
4505
4506 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4507 {
4508         q3dtexture_t *in;
4509         texture_t *out;
4510         int i, count;
4511
4512         in = (q3dtexture_t *)(mod_base + l->fileofs);
4513         if (l->filelen % sizeof(*in))
4514                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4515         count = l->filelen / sizeof(*in);
4516         out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4517
4518         loadmodel->data_textures = out;
4519         loadmodel->num_textures = count;
4520         loadmodel->num_texturesperskin = loadmodel->num_textures;
4521
4522         for (i = 0;i < count;i++)
4523         {
4524                 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4525                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4526                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4527                 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4528                 // restore the surfaceflags and supercontents
4529                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4530                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4531         }
4532 }
4533
4534 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4535 {
4536         q3dplane_t *in;
4537         mplane_t *out;
4538         int i, count;
4539
4540         in = (q3dplane_t *)(mod_base + l->fileofs);
4541         if (l->filelen % sizeof(*in))
4542                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4543         count = l->filelen / sizeof(*in);
4544         out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4545
4546         loadmodel->brush.data_planes = out;
4547         loadmodel->brush.num_planes = count;
4548
4549         for (i = 0;i < count;i++, in++, out++)
4550         {
4551                 out->normal[0] = LittleFloat(in->normal[0]);
4552                 out->normal[1] = LittleFloat(in->normal[1]);
4553                 out->normal[2] = LittleFloat(in->normal[2]);
4554                 out->dist = LittleFloat(in->dist);
4555                 PlaneClassify(out);
4556         }
4557 }
4558
4559 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4560 {
4561         q3dbrushside_t *in;
4562         q3mbrushside_t *out;
4563         int i, n, count;
4564
4565         in = (q3dbrushside_t *)(mod_base + l->fileofs);
4566         if (l->filelen % sizeof(*in))
4567                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4568         count = l->filelen / sizeof(*in);
4569         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4570
4571         loadmodel->brush.data_brushsides = out;
4572         loadmodel->brush.num_brushsides = count;
4573
4574         for (i = 0;i < count;i++, in++, out++)
4575         {
4576                 n = LittleLong(in->planeindex);
4577                 if (n < 0 || n >= loadmodel->brush.num_planes)
4578                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4579                 out->plane = loadmodel->brush.data_planes + n;
4580                 n = LittleLong(in->textureindex);
4581                 if (n < 0 || n >= loadmodel->num_textures)
4582                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4583                 out->texture = loadmodel->data_textures + n;
4584         }
4585 }
4586
4587 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4588 {
4589         q3dbrushside_ig_t *in;
4590         q3mbrushside_t *out;
4591         int i, n, count;
4592
4593         in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4594         if (l->filelen % sizeof(*in))
4595                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4596         count = l->filelen / sizeof(*in);
4597         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4598
4599         loadmodel->brush.data_brushsides = out;
4600         loadmodel->brush.num_brushsides = count;
4601
4602         for (i = 0;i < count;i++, in++, out++)
4603         {
4604                 n = LittleLong(in->planeindex);
4605                 if (n < 0 || n >= loadmodel->brush.num_planes)
4606                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4607                 out->plane = loadmodel->brush.data_planes + n;
4608                 n = LittleLong(in->textureindex);
4609                 if (n < 0 || n >= loadmodel->num_textures)
4610                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4611                 out->texture = loadmodel->data_textures + n;
4612         }
4613 }
4614
4615 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4616 {
4617         q3dbrush_t *in;
4618         q3mbrush_t *out;
4619         int i, j, n, c, count, maxplanes, q3surfaceflags;
4620         colplanef_t *planes;
4621
4622         in = (q3dbrush_t *)(mod_base + l->fileofs);
4623         if (l->filelen % sizeof(*in))
4624                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4625         count = l->filelen / sizeof(*in);
4626         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4627
4628         loadmodel->brush.data_brushes = out;
4629         loadmodel->brush.num_brushes = count;
4630
4631         maxplanes = 0;
4632         planes = NULL;
4633
4634         for (i = 0;i < count;i++, in++, out++)
4635         {
4636                 n = LittleLong(in->firstbrushside);
4637                 c = LittleLong(in->numbrushsides);
4638                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4639                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4640                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4641                 out->numbrushsides = c;
4642                 n = LittleLong(in->textureindex);
4643                 if (n < 0 || n >= loadmodel->num_textures)
4644                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4645                 out->texture = loadmodel->data_textures + n;
4646
4647                 // make a list of mplane_t structs to construct a colbrush from
4648                 if (maxplanes < out->numbrushsides)
4649                 {
4650                         maxplanes = out->numbrushsides;
4651                         if (planes)
4652                                 Mem_Free(planes);
4653                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4654                 }
4655                 q3surfaceflags = 0;
4656                 for (j = 0;j < out->numbrushsides;j++)
4657                 {
4658                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4659                         planes[j].dist = out->firstbrushside[j].plane->dist;
4660                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4661                         planes[j].texture = out->firstbrushside[j].texture;
4662                         q3surfaceflags |= planes[j].q3surfaceflags;
4663                 }
4664                 // make the colbrush from the planes
4665                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4666
4667                 // this whole loop can take a while (e.g. on redstarrepublic4)
4668                 CL_KeepaliveMessage(false);
4669         }
4670         if (planes)
4671                 Mem_Free(planes);
4672 }
4673
4674 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4675 {
4676         q3deffect_t *in;
4677         q3deffect_t *out;
4678         int i, n, count;
4679
4680         in = (q3deffect_t *)(mod_base + l->fileofs);
4681         if (l->filelen % sizeof(*in))
4682                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4683         count = l->filelen / sizeof(*in);
4684         out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4685
4686         loadmodel->brushq3.data_effects = out;
4687         loadmodel->brushq3.num_effects = count;
4688
4689         for (i = 0;i < count;i++, in++, out++)
4690         {
4691                 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4692                 n = LittleLong(in->brushindex);
4693                 if (n >= loadmodel->brush.num_brushes)
4694                 {
4695                         Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4696                         n = -1;
4697                 }
4698                 out->brushindex = n;
4699                 out->unknown = LittleLong(in->unknown);
4700         }
4701 }
4702
4703 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4704 {
4705         q3dvertex_t *in;
4706         int i, count;
4707
4708         in = (q3dvertex_t *)(mod_base + l->fileofs);
4709         if (l->filelen % sizeof(*in))
4710                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4711         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4712         loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4713         loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4714         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4715         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4716         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4717
4718         for (i = 0;i < count;i++, in++)
4719         {
4720                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4721                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4722                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4723                 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4724                 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4725                 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4726                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4727                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4728                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4729                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4730                 // svector/tvector are calculated later in face loading
4731                 if(mod_q3bsp_sRGBlightmaps.integer)
4732                 {
4733                         // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
4734                         // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
4735                         // working like this may be odd, but matches q3map2 -gamma 2.2
4736                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4737                         {
4738                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4739                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4740                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4741                                 // we fix the brightness consistently via lightmapscale
4742                         }
4743                         else
4744                         {
4745                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
4746                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
4747                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
4748                         }
4749                 }
4750                 else
4751                 {
4752                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4753                         {
4754                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4755                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4756                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4757                         }
4758                         else
4759                         {
4760                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4761                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4762                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4763                         }
4764                 }
4765                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4766                 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4767                         loadmodel->lit = true;
4768         }
4769 }
4770
4771 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4772 {
4773         int *in;
4774         int *out;
4775         int i, count;
4776
4777         in = (int *)(mod_base + l->fileofs);
4778         if (l->filelen % sizeof(int[3]))
4779                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4780         count = l->filelen / sizeof(*in);
4781
4782         if(!loadmodel->brushq3.num_vertices)
4783         {
4784                 if (count)
4785                         Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4786                 loadmodel->brushq3.num_triangles = 0;
4787                 return;
4788         }
4789
4790         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4791         loadmodel->brushq3.num_triangles = count / 3;
4792         loadmodel->brushq3.data_element3i = out;
4793
4794         for (i = 0;i < count;i++, in++, out++)
4795         {
4796                 *out = LittleLong(*in);
4797                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4798                 {
4799                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4800                         *out = 0;
4801                 }
4802         }
4803 }
4804
4805 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4806 {
4807         q3dlightmap_t *input_pointer;
4808         int i;
4809         int j;
4810         int k;
4811         int count;
4812         int powerx;
4813         int powery;
4814         int powerxy;
4815         int powerdxy;
4816         int endlightmap;
4817         int mergegoal;
4818         int lightmapindex;
4819         int realcount;
4820         int realindex;
4821         int mergedwidth;
4822         int mergedheight;
4823         int mergedcolumns;
4824         int mergedrows;
4825         int mergedrowsxcolumns;
4826         int size;
4827         int bytesperpixel;
4828         int rgbmap[3];
4829         unsigned char *c;
4830         unsigned char *mergedpixels;
4831         unsigned char *mergeddeluxepixels;
4832         unsigned char *mergebuf;
4833         char mapname[MAX_QPATH];
4834         qboolean external;
4835         unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4836         char vabuf[1024];
4837
4838         // defaults for q3bsp
4839         size = 128;
4840         bytesperpixel = 3;
4841         rgbmap[0] = 2;
4842         rgbmap[1] = 1;
4843         rgbmap[2] = 0;
4844         external = false;
4845         loadmodel->brushq3.lightmapsize = 128;
4846
4847         if (cls.state == ca_dedicated)
4848                 return;
4849
4850         if(mod_q3bsp_nolightmaps.integer)
4851         {
4852                 return;
4853         }
4854         else if(l->filelen)
4855         {
4856                 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4857                 if (developer_loading.integer)
4858                         Con_Printf("Using internal lightmaps\n");
4859                 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4860                 if (l->filelen % sizeof(*input_pointer))
4861                         Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4862                 count = l->filelen / sizeof(*input_pointer);
4863                 for(i = 0; i < count; ++i)
4864                         inpixels[i] = input_pointer[i].rgb;
4865         }
4866         else
4867         {
4868                 // no internal lightmaps
4869                 // try external lightmaps
4870                 if (developer_loading.integer)
4871                         Con_Printf("Using external lightmaps\n");
4872                 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4873                 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
4874                 if(!inpixels[0])
4875                         return;
4876
4877                 // using EXTERNAL lightmaps instead
4878                 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4879                 {
4880                         Mem_Free(inpixels[0]);
4881                         Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4882                 }
4883
4884                 size = image_width;
4885                 bytesperpixel = 4;
4886                 rgbmap[0] = 0;
4887                 rgbmap[1] = 1;
4888                 rgbmap[2] = 2;
4889                 external = true;
4890
4891                 for(count = 1; ; ++count)
4892                 {
4893                         inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
4894                         if(!inpixels[count])
4895                                 break; // we got all of them
4896                         if(image_width != size || image_height != size)
4897                         {
4898                                 Mem_Free(inpixels[count]);
4899                                 inpixels[count] = NULL;
4900                                 Con_Printf("Mod_Q3BSP_LoadLightmaps: mismatched lightmap size in %s - external lightmap %s/lm_%04d does not match earlier ones\n", loadmodel->name, mapname, count);
4901                                 break;
4902                         }
4903                 }
4904         }
4905
4906         loadmodel->brushq3.lightmapsize = size;
4907         loadmodel->brushq3.num_originallightmaps = count;
4908
4909         // now check the surfaces to see if any of them index an odd numbered
4910         // lightmap, if so this is not a deluxemapped bsp file
4911         //
4912         // also check what lightmaps are actually used, because q3map2 sometimes
4913         // (always?) makes an unused one at the end, which
4914         // q3map2 sometimes (or always?) makes a second blank lightmap for no
4915         // reason when only one lightmap is used, which can throw off the
4916         // deluxemapping detection method, so check 2-lightmap bsp's specifically
4917         // to see if the second lightmap is blank, if so it is not deluxemapped.
4918         // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4919         // in Mod_Q3BSP_LoadEntities was failed
4920         if (!loadmodel->brushq3.deluxemapping)
4921         {
4922                 loadmodel->brushq3.deluxemapping = !(count & 1);
4923                 loadmodel->brushq3.deluxemapping_modelspace = true;
4924                 endlightmap = 0;
4925                 if (loadmodel->brushq3.deluxemapping)
4926                 {
4927                         int facecount = faceslump->filelen / sizeof(q3dface_t);
4928                         q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4929                         for (i = 0;i < facecount;i++)
4930                         {
4931                                 j = LittleLong(faces[i].lightmapindex);
4932                                 if (j >= 0)
4933                                 {
4934                                         endlightmap = max(endlightmap, j + 1);
4935                                         if ((j & 1) || j + 1 >= count)
4936                                         {
4937                                                 loadmodel->brushq3.deluxemapping = false;
4938                                                 break;
4939                                         }
4940                                 }
4941                         }
4942                 }
4943
4944                 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4945                 // reason when only one lightmap is used, which can throw off the
4946                 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4947                 // to see if the second lightmap is blank, if so it is not deluxemapped.
4948                 //
4949                 // further research has shown q3map2 sometimes creates a deluxemap and two
4950                 // blank lightmaps, which must be handled properly as well
4951                 if (endlightmap == 1 && count > 1)
4952                 {
4953                         c = inpixels[1];
4954                         for (i = 0;i < size*size;i++)
4955                         {
4956                                 if (c[bytesperpixel*i + rgbmap[0]])
4957                                         break;
4958                                 if (c[bytesperpixel*i + rgbmap[1]])
4959                                         break;
4960                                 if (c[bytesperpixel*i + rgbmap[2]])
4961                                         break;
4962                         }
4963                         if (i == size*size)
4964                         {
4965                                 // all pixels in the unused lightmap were black...
4966                                 loadmodel->brushq3.deluxemapping = false;
4967                         }
4968                 }
4969         }
4970
4971         Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4972
4973         // figure out what the most reasonable merge power is within limits
4974
4975         // find the appropriate NxN dimensions to merge to, to avoid wasted space
4976         realcount = count >> (int)loadmodel->brushq3.deluxemapping;
4977
4978         // figure out how big the merged texture has to be
4979         mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
4980         mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
4981         while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
4982                 mergegoal /= 2;
4983         mergedwidth = mergegoal;
4984         mergedheight = mergegoal;
4985         // choose non-square size (2x1 aspect) if only half the space is used;
4986         // this really only happens when the entire set fits in one texture, if
4987         // there are multiple textures, we don't worry about shrinking the last
4988         // one to fit, because the driver prefers the same texture size on
4989         // consecutive draw calls...
4990         if (mergedwidth * mergedheight / 2 >= size*size*realcount)
4991                 mergedheight /= 2;
4992
4993         loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
4994         loadmodel->brushq3.num_lightmapmergedheightpower = 0;
4995         while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
4996                 loadmodel->brushq3.num_lightmapmergedwidthpower++;
4997         while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
4998                 loadmodel->brushq3.num_lightmapmergedheightpower++;
4999         loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5000
5001         powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5002         powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5003         powerxy = powerx+powery;
5004         powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5005
5006         mergedcolumns = 1 << powerx;
5007         mergedrows = 1 << powery;
5008         mergedrowsxcolumns = 1 << powerxy;
5009
5010         loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5011         loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5012         if (loadmodel->brushq3.deluxemapping)
5013                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5014
5015         // allocate a texture pool if we need it
5016         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5017                 loadmodel->texturepool = R_AllocTexturePool();
5018
5019         mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5020         mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5021         for (i = 0;i < count;i++)
5022         {
5023                 // figure out which merged lightmap texture this fits into
5024                 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5025                 lightmapindex = i >> powerdxy;
5026
5027                 // choose the destination address
5028                 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5029                 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5030                 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5031                         Con_DPrintf("copying original lightmap %i (%ix%i) to %i (at %i,%i)\n", i, size, size, lightmapindex, (realindex & (mergedcolumns-1))*size, ((realindex >> powerx) & (mergedrows-1))*size);
5032
5033                 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5034                 for (j = 0;j < size;j++)
5035                 for (k = 0;k < size;k++)
5036                 {
5037                         mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5038                         mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5039                         mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5040                         mergebuf[(j*mergedwidth+k)*4+3] = 255;
5041                 }
5042
5043                 // upload texture if this was the last tile being written to the texture
5044                 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5045                 {
5046                         if (loadmodel->brushq3.deluxemapping && (i & 1))
5047                                 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5048                         else
5049                         {
5050                                 if(mod_q3bsp_sRGBlightmaps.integer)
5051                                 {
5052                                         textype_t t;
5053                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5054                                         {
5055                                                 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5056                                                 // we fix the brightness consistently via lightmapscale
5057                                         }
5058                                         else
5059                                                 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5060                                         loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, t, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5061                                 }
5062                                 else
5063                                 {
5064                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5065                                                 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5066                                         loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5067                                 }
5068                         }
5069                 }
5070         }
5071
5072         if (mergeddeluxepixels)
5073                 Mem_Free(mergeddeluxepixels);
5074         Mem_Free(mergedpixels);
5075         if(external)
5076         {
5077                 for(i = 0; i < count; ++i)
5078                         Mem_Free(inpixels[i]);
5079         }
5080 }
5081
5082 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5083 {
5084         int j, k, cnt, tri;
5085         float *mins, *maxs;
5086         const float *vert;
5087         *collisionstride = stride;
5088         if(stride > 0)
5089         {
5090                 cnt = (num_triangles + stride - 1) / stride;
5091                 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5092                 for(j = 0; j < cnt; ++j)
5093                 {
5094                         mins = &((*collisionbbox6f)[6 * j + 0]);
5095                         maxs = &((*collisionbbox6f)[6 * j + 3]);
5096                         for(k = 0; k < stride; ++k)
5097                         {
5098                                 tri = j * stride + k;
5099                                 if(tri >= num_triangles)
5100                                         break;
5101                                 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5102                                 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5103                                 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5104                                 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5105                                 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5106                                 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5107                                 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5108                                 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5109                                 if(vert[0] < mins[0]) mins[0] = vert[0];
5110                                 if(vert[1] < mins[1]) mins[1] = vert[1];
5111                                 if(vert[2] < mins[2]) mins[2] = vert[2];
5112                                 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5113                                 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5114                                 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5115                                 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5116                                 if(vert[0] < mins[0]) mins[0] = vert[0];
5117                                 if(vert[1] < mins[1]) mins[1] = vert[1];
5118                                 if(vert[2] < mins[2]) mins[2] = vert[2];
5119                                 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5120                                 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5121                                 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5122                         }
5123                 }
5124         }
5125         else
5126                 *collisionbbox6f = NULL;
5127 }
5128
5129 typedef struct patchtess_s
5130 {
5131         patchinfo_t info;
5132
5133         // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5134         int surface_id;
5135         float lodgroup[6];
5136         float *originalvertex3f;
5137 } patchtess_t;
5138
5139 #define PATCHTESS_SAME_LODGROUP(a,b) \
5140         ( \
5141                 (a).lodgroup[0] == (b).lodgroup[0] && \
5142                 (a).lodgroup[1] == (b).lodgroup[1] && \
5143                 (a).lodgroup[2] == (b).lodgroup[2] && \
5144                 (a).lodgroup[3] == (b).lodgroup[3] && \
5145                 (a).lodgroup[4] == (b).lodgroup[4] && \
5146                 (a).lodgroup[5] == (b).lodgroup[5] \
5147         )
5148
5149 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5150 {
5151         q3dface_t *in, *oldin;
5152         msurface_t *out, *oldout;
5153         int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshvertices, meshtriangles, collisionvertices, collisiontriangles, numvertices, numtriangles, cxtess, cytess;
5154         float lightmaptcbase[2], lightmaptcscale[2];
5155         //int *originalelement3i;
5156         //int *originalneighbor3i;
5157         float *originalvertex3f;
5158         //float *originalsvector3f;
5159         //float *originaltvector3f;
5160         float *originalnormal3f;
5161         float *originalcolor4f;
5162         float *originaltexcoordtexture2f;
5163         float *originaltexcoordlightmap2f;
5164         float *surfacecollisionvertex3f;
5165         int *surfacecollisionelement3i;
5166         float *v;
5167         patchtess_t *patchtess = NULL;
5168         int patchtesscount = 0;
5169         qboolean again;
5170
5171         in = (q3dface_t *)(mod_base + l->fileofs);
5172         if (l->filelen % sizeof(*in))
5173                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5174         count = l->filelen / sizeof(*in);
5175         out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5176
5177         loadmodel->data_surfaces = out;
5178         loadmodel->num_surfaces = count;
5179
5180         if(count > 0)
5181                 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5182
5183         i = 0;
5184         oldi = i;
5185         oldin = in;
5186         oldout = out;
5187         meshvertices = 0;
5188         meshtriangles = 0;
5189         for (;i < count;i++, in++, out++)
5190         {
5191                 // check face type first
5192                 type = LittleLong(in->type);
5193                 if (type != Q3FACETYPE_FLAT
5194                  && type != Q3FACETYPE_PATCH
5195                  && type != Q3FACETYPE_MESH
5196                  && type != Q3FACETYPE_FLARE)
5197                 {
5198                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5199                         continue;
5200                 }
5201
5202                 n = LittleLong(in->textureindex);
5203                 if (n < 0 || n >= loadmodel->num_textures)
5204                 {
5205                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5206                         continue;
5207                 }
5208                 out->texture = loadmodel->data_textures + n;
5209                 n = LittleLong(in->effectindex);
5210                 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5211                 {
5212                         if (developer_extra.integer)
5213                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5214                         n = -1;
5215                 }
5216                 if (n == -1)
5217                         out->effect = NULL;
5218                 else
5219                         out->effect = loadmodel->brushq3.data_effects + n;
5220
5221                 if (cls.state != ca_dedicated)
5222                 {
5223                         out->lightmaptexture = NULL;
5224                         out->deluxemaptexture = r_texture_blanknormalmap;
5225                         n = LittleLong(in->lightmapindex);
5226                         if (n < 0)
5227                                 n = -1;
5228                         else if (n >= loadmodel->brushq3.num_originallightmaps)
5229                         {
5230                                 if(loadmodel->brushq3.num_originallightmaps != 0)
5231                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5232                                 n = -1;
5233                         }
5234                         else
5235                         {
5236                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5237                                 if (loadmodel->brushq3.deluxemapping)
5238                                         out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5239                                 loadmodel->lit = true;
5240                         }
5241                 }
5242
5243                 firstvertex = LittleLong(in->firstvertex);
5244                 numvertices = LittleLong(in->numvertices);
5245                 firstelement = LittleLong(in->firstelement);
5246                 numtriangles = LittleLong(in->numelements) / 3;
5247                 if (numtriangles * 3 != LittleLong(in->numelements))
5248                 {
5249                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): numelements %i is not a multiple of 3\n", i, out->texture->name, LittleLong(in->numelements));
5250                         continue;
5251                 }
5252                 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5253                 {
5254                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid vertex range %i : %i (%i vertices)\n", i, out->texture->name, firstvertex, firstvertex + numvertices, loadmodel->brushq3.num_vertices);
5255                         continue;
5256                 }
5257                 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5258                 {
5259                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid element range %i : %i (%i elements)\n", i, out->texture->name, firstelement, firstelement + numtriangles * 3, loadmodel->brushq3.num_triangles * 3);
5260                         continue;
5261                 }
5262                 switch(type)
5263                 {
5264                 case Q3FACETYPE_FLAT:
5265                 case Q3FACETYPE_MESH:
5266                         // no processing necessary
5267                         break;
5268                 case Q3FACETYPE_PATCH:
5269                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5270                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5271                         if (numvertices != (patchsize[0] * patchsize[1]) || patchsize[0] < 3 || patchsize[1] < 3 || !(patchsize[0] & 1) || !(patchsize[1] & 1) || patchsize[0] * patchsize[1] >= min(r_subdivisions_maxvertices.integer, r_subdivisions_collision_maxvertices.integer))
5272                         {
5273                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5274                                 continue;
5275                         }
5276                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5277
5278                         // convert patch to Q3FACETYPE_MESH
5279                         xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5280                         ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5281                         // bound to user settings
5282                         xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5283                         ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5284                         // bound to sanity settings
5285                         xtess = bound(0, xtess, 1024);
5286                         ytess = bound(0, ytess, 1024);
5287
5288                         // lower quality collision patches! Same procedure as before, but different cvars
5289                         // convert patch to Q3FACETYPE_MESH
5290                         cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5291                         cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5292                         // bound to user settings
5293                         cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5294                         cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5295                         // bound to sanity settings
5296                         cxtess = bound(0, cxtess, 1024);
5297                         cytess = bound(0, cytess, 1024);
5298
5299                         // store it for the LOD grouping step
5300                         patchtess[patchtesscount].info.xsize = patchsize[0];
5301                         patchtess[patchtesscount].info.ysize = patchsize[1];
5302                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5303                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5304                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5305                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5306         
5307                         patchtess[patchtesscount].surface_id = i;
5308                         patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5309                         patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5310                         patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5311                         patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5312                         patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5313                         patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5314                         patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5315                         ++patchtesscount;
5316                         break;
5317                 case Q3FACETYPE_FLARE:
5318                         if (developer_extra.integer)
5319                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5320                         // don't render it
5321                         continue;
5322                 }
5323                 out->num_vertices = numvertices;
5324                 out->num_triangles = numtriangles;
5325                 meshvertices += out->num_vertices;
5326                 meshtriangles += out->num_triangles;
5327         }
5328
5329         // Fix patches tesselations so that they make no seams
5330         do
5331         {
5332                 again = false;
5333                 for(i = 0; i < patchtesscount; ++i)
5334                 {
5335                         for(j = i+1; j < patchtesscount; ++j)
5336                         {
5337                                 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5338                                         continue;
5339
5340                                 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5341                                         again = true;
5342                         }
5343                 }
5344         }
5345         while (again);
5346
5347         // Calculate resulting number of triangles
5348         collisionvertices = 0;
5349         collisiontriangles = 0;
5350         for(i = 0; i < patchtesscount; ++i)
5351         {
5352                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5353                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5354                 numvertices = finalwidth * finalheight;
5355                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5356
5357                 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5358                 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5359                 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5360                 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5361
5362                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5363                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5364                 numvertices = finalwidth * finalheight;
5365                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5366
5367                 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5368                 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5369                 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5370                 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5371         }
5372
5373         i = oldi;
5374         in = oldin;
5375         out = oldout;
5376         Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5377         if (collisiontriangles)
5378         {
5379                 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5380                 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5381         }
5382         meshvertices = 0;
5383         meshtriangles = 0;
5384         collisionvertices = 0;
5385         collisiontriangles = 0;
5386         for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5387         {
5388                 if (out->num_vertices < 3 || out->num_triangles < 1)
5389                         continue;
5390
5391                 type = LittleLong(in->type);
5392                 firstvertex = LittleLong(in->firstvertex);
5393                 firstelement = LittleLong(in->firstelement);
5394                 out->num_firstvertex = meshvertices;
5395                 out->num_firsttriangle = meshtriangles;
5396                 out->num_firstcollisiontriangle = collisiontriangles;
5397                 switch(type)
5398                 {
5399                 case Q3FACETYPE_FLAT:
5400                 case Q3FACETYPE_MESH:
5401                         // no processing necessary, except for lightmap merging
5402                         for (j = 0;j < out->num_vertices;j++)
5403                         {
5404                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5405                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5406                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5407                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5408                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5409                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5410                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5411                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5412                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5413                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5414                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5415                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5416                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5417                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5418                         }
5419                         for (j = 0;j < out->num_triangles*3;j++)
5420                                 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5421                         break;
5422                 case Q3FACETYPE_PATCH:
5423                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5424                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5425                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5426                         originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5427                         originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5428                         originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5429                         originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5430
5431                         xtess = ytess = cxtess = cytess = -1;
5432                         for(j = 0; j < patchtesscount; ++j)
5433                                 if(patchtess[j].surface_id == i)
5434                                 {
5435                                         xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5436                                         ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5437                                         cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5438                                         cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5439                                         break;
5440                                 }
5441                         if(xtess == -1)
5442                         {
5443                                 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5444                                 xtess = ytess = cxtess = cytess = 0;
5445                         }
5446
5447                         finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5448                         finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5449                         finalvertices = finalwidth * finalheight;
5450                         oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5451                         type = Q3FACETYPE_MESH;
5452                         // generate geometry
5453                         // (note: normals are skipped because they get recalculated)
5454                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5455                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5456                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5457                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5458                         Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5459                         Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5460
5461                         out->num_triangles = Mod_RemoveDegenerateTriangles(out->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), loadmodel->surfmesh.data_vertex3f);
5462
5463                         if (developer_extra.integer)
5464                         {
5465                                 if (out->num_triangles < finaltriangles)
5466                                         Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->num_vertices, finaltriangles, finaltriangles - out->num_triangles, out->num_triangles);
5467                                 else
5468                                         Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->num_vertices, out->num_triangles);
5469                         }
5470                         // q3map does not put in collision brushes for curves... ugh
5471                         // build the lower quality collision geometry
5472                         finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5473                         finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5474                         finalvertices = finalwidth * finalheight;
5475                         oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5476
5477                         // legacy collision geometry implementation
5478                         out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5479                         out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5480                         out->num_collisionvertices = finalvertices;
5481                         out->num_collisiontriangles = finaltriangles;
5482                         Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5483                         Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5484
5485                         //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5486                         Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5487
5488                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5489
5490                         // now optimize the collision mesh by finding triangle bboxes...
5491                         Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5492                         Mod_Q3BSP_BuildBBoxes(loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle, out->num_triangles, loadmodel->surfmesh.data_vertex3f, &out->deprecatedq3data_bbox6f, &out->deprecatedq3num_bboxstride, mod_q3bsp_curves_stride.integer);
5493
5494                         // store collision geometry for BIH collision tree
5495                         surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5496                         surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5497                         Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5498                         Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5499                         Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5500 #if 1
5501                         // remove this once the legacy code is removed
5502                         {
5503                                 int nc = out->num_collisiontriangles;
5504 #endif
5505                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5506 #if 1
5507                                 if(nc != out->num_collisiontriangles)
5508                                 {
5509                                         Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5510                                 }
5511                         }
5512 #endif
5513
5514                         if (developer_extra.integer)
5515                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
5516
5517                         collisionvertices += finalvertices;
5518                         collisiontriangles += out->num_collisiontriangles;
5519                         break;
5520                 default:
5521                         break;
5522                 }
5523                 meshvertices += out->num_vertices;
5524                 meshtriangles += out->num_triangles;
5525                 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5526                         if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
5527                                 invalidelements++;
5528                 if (invalidelements)
5529                 {
5530                         Con_Printf("Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
5531                         for (j = 0;j < out->num_triangles * 3;j++)
5532                         {
5533                                 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5534                                 if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
5535                                         (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5536                         }
5537                         Con_Print("\n");
5538                 }
5539                 // calculate a bounding box
5540                 VectorClear(out->mins);
5541                 VectorClear(out->maxs);
5542                 if (out->num_vertices)
5543                 {
5544                         if (cls.state != ca_dedicated && out->lightmaptexture)
5545                         {
5546                                 // figure out which part of the merged lightmap this fits into
5547                                 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5548                                 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5549                                 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5550                                 lightmapindex &= mergewidth * mergeheight - 1;
5551                                 lightmaptcscale[0] = 1.0f / mergewidth;
5552                                 lightmaptcscale[1] = 1.0f / mergeheight;
5553                                 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5554                                 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5555                                 // modify the lightmap texcoords to match this region of the merged lightmap
5556                                 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5557                                 {
5558                                         v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5559                                         v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5560                                 }
5561                         }
5562                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5563                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5564                         for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5565                         {
5566                                 out->mins[0] = min(out->mins[0], v[0]);
5567                                 out->maxs[0] = max(out->maxs[0], v[0]);
5568                                 out->mins[1] = min(out->mins[1], v[1]);
5569                                 out->maxs[1] = max(out->maxs[1], v[1]);
5570                                 out->mins[2] = min(out->mins[2], v[2]);
5571                                 out->maxs[2] = max(out->maxs[2], v[2]);
5572                         }
5573                         out->mins[0] -= 1.0f;
5574                         out->mins[1] -= 1.0f;
5575                         out->mins[2] -= 1.0f;
5576                         out->maxs[0] += 1.0f;
5577                         out->maxs[1] += 1.0f;
5578                         out->maxs[2] += 1.0f;
5579                 }
5580                 // set lightmap styles for consistency with q1bsp
5581                 //out->lightmapinfo->styles[0] = 0;
5582                 //out->lightmapinfo->styles[1] = 255;
5583                 //out->lightmapinfo->styles[2] = 255;
5584                 //out->lightmapinfo->styles[3] = 255;
5585         }
5586
5587         i = oldi;
5588         out = oldout;
5589         for (;i < count;i++, out++)
5590         {
5591                 if(out->num_vertices && out->num_triangles)
5592                         continue;
5593                 if(out->num_vertices == 0)
5594                 {
5595                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5596                         if(out->num_triangles == 0)
5597                                 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5598                 }
5599                 else if(out->num_triangles == 0)
5600                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s, near %f %f %f) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)",
5601                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5602                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5603                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5604         }
5605
5606         // for per pixel lighting
5607         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
5608
5609         // generate ushort elements array if possible
5610         if (loadmodel->surfmesh.data_element3s)
5611                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5612                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5613
5614         // free the no longer needed vertex data
5615         loadmodel->brushq3.num_vertices = 0;
5616         if (loadmodel->brushq3.data_vertex3f)
5617                 Mem_Free(loadmodel->brushq3.data_vertex3f);
5618         loadmodel->brushq3.data_vertex3f = NULL;
5619         loadmodel->brushq3.data_normal3f = NULL;
5620         loadmodel->brushq3.data_texcoordtexture2f = NULL;
5621         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5622         loadmodel->brushq3.data_color4f = NULL;
5623         // free the no longer needed triangle data
5624         loadmodel->brushq3.num_triangles = 0;
5625         if (loadmodel->brushq3.data_element3i)
5626                 Mem_Free(loadmodel->brushq3.data_element3i);
5627         loadmodel->brushq3.data_element3i = NULL;
5628
5629         if(patchtess)
5630                 Mem_Free(patchtess);
5631 }
5632
5633 static void Mod_Q3BSP_LoadModels(lump_t *l)
5634 {
5635         q3dmodel_t *in;
5636         q3dmodel_t *out;
5637         int i, j, n, c, count;
5638
5639         in = (q3dmodel_t *)(mod_base + l->fileofs);
5640         if (l->filelen % sizeof(*in))
5641                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5642         count = l->filelen / sizeof(*in);
5643         out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5644
5645         loadmodel->brushq3.data_models = out;
5646         loadmodel->brushq3.num_models = count;
5647
5648         for (i = 0;i < count;i++, in++, out++)
5649         {
5650                 for (j = 0;j < 3;j++)
5651                 {
5652                         out->mins[j] = LittleFloat(in->mins[j]);
5653                         out->maxs[j] = LittleFloat(in->maxs[j]);
5654                 }
5655                 n = LittleLong(in->firstface);
5656                 c = LittleLong(in->numfaces);
5657                 if (n < 0 || n + c > loadmodel->num_surfaces)
5658                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5659                 out->firstface = n;
5660                 out->numfaces = c;
5661                 n = LittleLong(in->firstbrush);
5662                 c = LittleLong(in->numbrushes);
5663                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5664                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5665                 out->firstbrush = n;
5666                 out->numbrushes = c;
5667         }
5668 }
5669
5670 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5671 {
5672         int *in;
5673         int *out;
5674         int i, n, count;
5675
5676         in = (int *)(mod_base + l->fileofs);
5677         if (l->filelen % sizeof(*in))
5678                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5679         count = l->filelen / sizeof(*in);
5680         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5681
5682         loadmodel->brush.data_leafbrushes = out;
5683         loadmodel->brush.num_leafbrushes = count;
5684
5685         for (i = 0;i < count;i++, in++, out++)
5686         {
5687                 n = LittleLong(*in);
5688                 if (n < 0 || n >= loadmodel->brush.num_brushes)
5689                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5690                 *out = n;
5691         }
5692 }
5693
5694 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5695 {
5696         int *in;
5697         int *out;
5698         int i, n, count;
5699
5700         in = (int *)(mod_base + l->fileofs);
5701         if (l->filelen % sizeof(*in))
5702                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5703         count = l->filelen / sizeof(*in);
5704         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5705
5706         loadmodel->brush.data_leafsurfaces = out;
5707         loadmodel->brush.num_leafsurfaces = count;
5708
5709         for (i = 0;i < count;i++, in++, out++)
5710         {
5711                 n = LittleLong(*in);
5712                 if (n < 0 || n >= loadmodel->num_surfaces)
5713                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5714                 *out = n;
5715         }
5716 }
5717
5718 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5719 {
5720         q3dleaf_t *in;
5721         mleaf_t *out;
5722         int i, j, n, c, count;
5723
5724         in = (q3dleaf_t *)(mod_base + l->fileofs);
5725         if (l->filelen % sizeof(*in))
5726                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5727         count = l->filelen / sizeof(*in);
5728         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5729
5730         loadmodel->brush.data_leafs = out;
5731         loadmodel->brush.num_leafs = count;
5732
5733         for (i = 0;i < count;i++, in++, out++)
5734         {
5735                 out->parent = NULL;
5736                 out->plane = NULL;
5737                 out->clusterindex = LittleLong(in->clusterindex);
5738                 out->areaindex = LittleLong(in->areaindex);
5739                 for (j = 0;j < 3;j++)
5740                 {
5741                         // yes the mins/maxs are ints
5742                         out->mins[j] = LittleLong(in->mins[j]) - 1;
5743                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5744                 }
5745                 n = LittleLong(in->firstleafface);
5746                 c = LittleLong(in->numleaffaces);
5747                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5748                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5749                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5750                 out->numleafsurfaces = c;
5751                 n = LittleLong(in->firstleafbrush);
5752                 c = LittleLong(in->numleafbrushes);
5753                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5754                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5755                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5756                 out->numleafbrushes = c;
5757         }
5758 }
5759
5760 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5761 {
5762         q3dnode_t *in;
5763         mnode_t *out;
5764         int i, j, n, count;
5765
5766         in = (q3dnode_t *)(mod_base + l->fileofs);
5767         if (l->filelen % sizeof(*in))
5768                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5769         count = l->filelen / sizeof(*in);
5770         if (count == 0)
5771                 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5772         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5773
5774         loadmodel->brush.data_nodes = out;
5775         loadmodel->brush.num_nodes = count;
5776
5777         for (i = 0;i < count;i++, in++, out++)
5778         {
5779                 out->parent = NULL;
5780                 n = LittleLong(in->planeindex);
5781                 if (n < 0 || n >= loadmodel->brush.num_planes)
5782                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5783                 out->plane = loadmodel->brush.data_planes + n;
5784                 for (j = 0;j < 2;j++)
5785                 {
5786                         n = LittleLong(in->childrenindex[j]);
5787                         if (n >= 0)
5788                         {
5789                                 if (n >= loadmodel->brush.num_nodes)
5790                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5791                                 out->children[j] = loadmodel->brush.data_nodes + n;
5792                         }
5793                         else
5794                         {
5795                                 n = -1 - n;
5796                                 if (n >= loadmodel->brush.num_leafs)
5797                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5798                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5799                         }
5800                 }
5801                 for (j = 0;j < 3;j++)
5802                 {
5803                         // yes the mins/maxs are ints
5804                         out->mins[j] = LittleLong(in->mins[j]) - 1;
5805                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5806                 }
5807         }
5808
5809         // set the parent pointers
5810         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5811 }
5812
5813 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5814 {
5815         q3dlightgrid_t *in;
5816         q3dlightgrid_t *out;
5817         int count;
5818         int i;
5819
5820         in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5821         if (l->filelen % sizeof(*in))
5822                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5823         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5824         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5825         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5826         loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5827         loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5828         loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5829         loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5830         loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5831         loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5832         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5833         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5834         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5835         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5836         Matrix4x4_CreateScale3(&loadmodel->brushq3.num_lightgrid_indexfromworld, loadmodel->brushq3.num_lightgrid_scale[0], loadmodel->brushq3.num_lightgrid_scale[1], loadmodel->brushq3.num_lightgrid_scale[2]);
5837         Matrix4x4_ConcatTranslate(&loadmodel->brushq3.num_lightgrid_indexfromworld, -loadmodel->brushq3.num_lightgrid_imins[0] * loadmodel->brushq3.num_lightgrid_cellsize[0], -loadmodel->brushq3.num_lightgrid_imins[1] * loadmodel->brushq3.num_lightgrid_cellsize[1], -loadmodel->brushq3.num_lightgrid_imins[2] * loadmodel->brushq3.num_lightgrid_cellsize[2]);
5838
5839         // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5840         if (l->filelen)
5841         {
5842                 if (l->filelen < count * (int)sizeof(*in))
5843                 {
5844                         Con_Printf("Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)", l->filelen, (int)(count * sizeof(*in)), loadmodel->brushq3.num_lightgrid_isize[0], loadmodel->brushq3.num_lightgrid_isize[1], loadmodel->brushq3.num_lightgrid_isize[2]);
5845                         return; // ignore the grid if we cannot understand it
5846                 }
5847                 if (l->filelen != count * (int)sizeof(*in))
5848                         Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5849                 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5850                 loadmodel->brushq3.data_lightgrid = out;
5851                 loadmodel->brushq3.num_lightgrid = count;
5852                 // no swapping or validation necessary
5853                 memcpy(out, in, count * (int)sizeof(*out));
5854
5855                 if(mod_q3bsp_sRGBlightmaps.integer)
5856                 {
5857                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5858                         {
5859                                 // we fix the brightness consistently via lightmapscale
5860                         }
5861                         else
5862                         {
5863                                 for(i = 0; i < count; ++i)
5864                                 {
5865                                         out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5866                                         out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5867                                         out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5868                                         out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
5869                                         out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
5870                                         out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
5871                                 }
5872                         }
5873                 }
5874                 else
5875                 {
5876                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5877                         {
5878                                 for(i = 0; i < count; ++i)
5879                                 {
5880                                         out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5881                                         out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5882                                         out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5883                                         out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
5884                                         out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
5885                                         out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
5886                                 }
5887                         }
5888                         else
5889                         {
5890                                 // all is good
5891                         }
5892                 }
5893         }
5894 }
5895
5896 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5897 {
5898         q3dpvs_t *in;
5899         int totalchains;
5900
5901         if (l->filelen == 0)
5902         {
5903                 int i;
5904                 // unvised maps often have cluster indices even without pvs, so check
5905                 // leafs to find real number of clusters
5906                 loadmodel->brush.num_pvsclusters = 1;
5907                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5908                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5909
5910                 // create clusters
5911                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5912                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5913                 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5914                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5915                 return;
5916         }
5917
5918         in = (q3dpvs_t *)(mod_base + l->fileofs);
5919         if (l->filelen < 9)
5920                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5921
5922         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5923         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5924         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5925                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5926         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5927         if (l->filelen < totalchains + (int)sizeof(*in))
5928                 Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, (int)(totalchains + sizeof(*in)), l->filelen);
5929
5930         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5931         memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5932 }
5933
5934 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5935 {
5936         int i, j, k, index[3];
5937         float transformed[3], blend1, blend2, blend, stylescale = 1;
5938         q3dlightgrid_t *a, *s;
5939
5940         // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5941         switch(vid.renderpath)
5942         {
5943         case RENDERPATH_GL20:
5944         case RENDERPATH_D3D9:
5945         case RENDERPATH_D3D10:
5946         case RENDERPATH_D3D11:
5947         case RENDERPATH_SOFT:
5948         case RENDERPATH_GLES2:
5949                 // LordHavoc: FIXME: is this true?
5950                 stylescale = 1; // added while render
5951                 break;
5952         case RENDERPATH_GL11:
5953         case RENDERPATH_GL13:
5954         case RENDERPATH_GLES1:
5955                 stylescale = r_refdef.scene.rtlightstylevalue[0];
5956                 break;
5957         }
5958
5959         if (!model->brushq3.num_lightgrid)
5960         {
5961                 ambientcolor[0] = stylescale;
5962                 ambientcolor[1] = stylescale;
5963                 ambientcolor[2] = stylescale;
5964                 return;
5965         }
5966
5967         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5968         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5969         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5970         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5971         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5972         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5973         index[0] = (int)floor(transformed[0]);
5974         index[1] = (int)floor(transformed[1]);
5975         index[2] = (int)floor(transformed[2]);
5976         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5977
5978         // now lerp the values
5979         VectorClear(diffusenormal);
5980         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5981         for (k = 0;k < 2;k++)
5982         {
5983                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5984                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5985                         continue;
5986                 for (j = 0;j < 2;j++)
5987                 {
5988                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5989                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5990                                 continue;
5991                         for (i = 0;i < 2;i++)
5992                         {
5993                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5994                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5995                                         continue;
5996                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5997                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5998                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5999                                 // this uses the mod_md3_sin table because the values are
6000                                 // already in the 0-255 range, the 64+ bias fetches a cosine
6001                                 // instead of a sine value
6002                                 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6003                                 diffusenormal[1] += blend * (mod_md3_sin[     s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6004                                 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6005                                 //Con_Printf("blend %f: ambient %i %i %i, diffuse %i %i %i, diffusepitch %i diffuseyaw %i (%f %f, normal %f %f %f)\n", blend, s->ambientrgb[0], s->ambientrgb[1], s->ambientrgb[2], s->diffusergb[0], s->diffusergb[1], s->diffusergb[2], s->diffusepitch, s->diffuseyaw, pitch, yaw, (cos(yaw) * cospitch), (sin(yaw) * cospitch), (-sin(pitch)));
6006                         }
6007                 }
6008         }
6009
6010         // normalize the light direction before turning
6011         VectorNormalize(diffusenormal);
6012         //Con_Printf("result: ambient %f %f %f diffuse %f %f %f diffusenormal %f %f %f\n", ambientcolor[0], ambientcolor[1], ambientcolor[2], diffusecolor[0], diffusecolor[1], diffusecolor[2], diffusenormal[0], diffusenormal[1], diffusenormal[2]);
6013 }
6014
6015 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6016 {
6017         double t1, t2;
6018         double midf, mid[3];
6019         int ret, side;
6020
6021         // check for empty
6022         while (node->plane)
6023         {
6024                 // find the point distances
6025                 mplane_t *plane = node->plane;
6026                 if (plane->type < 3)
6027                 {
6028                         t1 = p1[plane->type] - plane->dist;
6029                         t2 = p2[plane->type] - plane->dist;
6030                 }
6031                 else
6032                 {
6033                         t1 = DotProduct (plane->normal, p1) - plane->dist;
6034                         t2 = DotProduct (plane->normal, p2) - plane->dist;
6035                 }
6036
6037                 if (t1 < 0)
6038                 {
6039                         if (t2 < 0)
6040                         {
6041                                 node = node->children[1];
6042                                 continue;
6043                         }
6044                         side = 1;
6045                 }
6046                 else
6047                 {
6048                         if (t2 >= 0)
6049                         {
6050                                 node = node->children[0];
6051                                 continue;
6052                         }
6053                         side = 0;
6054                 }
6055
6056                 midf = t1 / (t1 - t2);
6057                 VectorLerp(p1, midf, p2, mid);
6058
6059                 // recurse both sides, front side first
6060                 // return 2 if empty is followed by solid (hit something)
6061                 // do not return 2 if both are solid or both empty,
6062                 // or if start is solid and end is empty
6063                 // as these degenerate cases usually indicate the eye is in solid and
6064                 // should see the target point anyway
6065                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side    ], p1, mid);
6066                 if (ret != 0)
6067                         return ret;
6068                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6069                 if (ret != 1)
6070                         return ret;
6071                 return 2;
6072         }
6073         return ((mleaf_t *)node)->clusterindex < 0;
6074 }
6075
6076 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6077 {
6078         if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6079         {
6080                 trace_t trace;
6081                 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6082                 return trace.fraction == 1;
6083         }
6084         else
6085         {
6086                 double tracestart[3], traceend[3];
6087                 VectorCopy(start, tracestart);
6088                 VectorCopy(end, traceend);
6089                 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6090         }
6091 }
6092
6093 void Mod_CollisionBIH_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
6094 {
6095         const bih_t *bih;
6096         const bih_leaf_t *leaf;
6097         const bih_node_t *node;
6098         const colbrushf_t *brush;
6099         int axis;
6100         int nodenum;
6101         int nodestackpos = 0;
6102         int nodestack[1024];
6103
6104         memset(trace, 0, sizeof(*trace));
6105         trace->fraction = 1;
6106         trace->realfraction = 1;
6107         trace->hitsupercontentsmask = hitsupercontentsmask;
6108
6109         bih = &model->collision_bih;
6110         if(!bih->nodes)
6111                 return;
6112
6113         nodenum = bih->rootnode;
6114         nodestack[nodestackpos++] = nodenum;
6115         while (nodestackpos)
6116         {
6117                 nodenum = nodestack[--nodestackpos];
6118                 node = bih->nodes + nodenum;
6119 #if 1
6120                 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6121                         continue;
6122 #endif
6123                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6124                 {
6125                         axis = node->type - BIH_SPLITX;
6126                         if (start[axis] >= node->frontmin)
6127                                 nodestack[nodestackpos++] = node->front;
6128                         if (start[axis] <= node->backmax)
6129                                 nodestack[nodestackpos++] = node->back;
6130                 }
6131                 else if (node->type == BIH_UNORDERED)
6132                 {
6133                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6134                         {
6135                                 leaf = bih->leafs + node->children[axis];
6136 #if 1
6137                                 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6138                                         continue;
6139 #endif
6140                                 switch(leaf->type)
6141                                 {
6142                                 case BIH_BRUSH:
6143                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6144                                         Collision_TracePointBrushFloat(trace, start, brush);
6145                                         break;
6146                                 case BIH_COLLISIONTRIANGLE:
6147                                         // collision triangle - skipped because they have no volume
6148                                         break;
6149                                 case BIH_RENDERTRIANGLE:
6150                                         // render triangle - skipped because they have no volume
6151                                         break;
6152                                 }
6153                         }
6154                 }
6155         }
6156 }
6157
6158 static void Mod_CollisionBIH_TraceLineShared(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, const bih_t *bih)
6159 {
6160         const bih_leaf_t *leaf;
6161         const bih_node_t *node;
6162         const colbrushf_t *brush;
6163         const int *e;
6164         const texture_t *texture;
6165         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6166         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6167         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6168
6169         if(!bih->nodes)
6170                 return;
6171
6172         if (VectorCompare(start, end))
6173         {
6174                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6175                 return;
6176         }
6177
6178         nodenum = bih->rootnode;
6179
6180         memset(trace, 0, sizeof(*trace));
6181         trace->fraction = 1;
6182         trace->realfraction = 1;
6183         trace->hitsupercontentsmask = hitsupercontentsmask;
6184
6185         // push first node
6186         nodestackline[nodestackpos][0] = start[0];
6187         nodestackline[nodestackpos][1] = start[1];
6188         nodestackline[nodestackpos][2] = start[2];
6189         nodestackline[nodestackpos][3] = end[0];
6190         nodestackline[nodestackpos][4] = end[1];
6191         nodestackline[nodestackpos][5] = end[2];
6192         nodestack[nodestackpos++] = nodenum;
6193         while (nodestackpos)
6194         {
6195                 nodenum = nodestack[--nodestackpos];
6196                 node = bih->nodes + nodenum;
6197                 VectorCopy(nodestackline[nodestackpos], nodestart);
6198                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6199                 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6200                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6201                         continue;
6202                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6203                 {
6204                         // recurse children of the split
6205                         axis = node->type - BIH_SPLITX;
6206                         d1 = node->backmax - nodestart[axis];
6207                         d2 = node->backmax - nodeend[axis];
6208                         d3 = nodestart[axis] - node->frontmin;
6209                         d4 = nodeend[axis] - node->frontmin;
6210                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6211                         {
6212                         case  0: /* >>>> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6213                         case  1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6214                         case  2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6215                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6216                         case  4: /* >><> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6217                         case  5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6218                         case  6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6219                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6220                         case  8: /* >>>< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6221                         case  9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6222                         case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6223                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6224                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6225                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6226                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6227                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
6228                         }
6229                 }
6230                 else if (node->type == BIH_UNORDERED)
6231                 {
6232                         // calculate sweep bounds for this node
6233                         // copy node bounds into local variables
6234                         VectorCopy(node->mins, nodebigmins);
6235                         VectorCopy(node->maxs, nodebigmaxs);
6236                         // clip line to this node bounds
6237                         axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6238                         axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6239                         axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6240                         // some of the line intersected the enlarged node box
6241                         // calculate sweep bounds for this node
6242                         sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6243                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6244                         {
6245                                 leaf = bih->leafs + node->children[axis];
6246                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6247                                         continue;
6248                                 switch(leaf->type)
6249                                 {
6250                                 case BIH_BRUSH:
6251                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6252                                         Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6253                                         break;
6254                                 case BIH_COLLISIONTRIANGLE:
6255                                         if (!mod_q3bsp_curves_collisions.integer)
6256                                                 continue;
6257                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6258                                         texture = model->data_textures + leaf->textureindex;
6259                                         Collision_TraceLineTriangleFloat(trace, start, end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6260                                         break;
6261                                 case BIH_RENDERTRIANGLE:
6262                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6263                                         texture = model->data_textures + leaf->textureindex;
6264                                         Collision_TraceLineTriangleFloat(trace, start, end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6265                                         break;
6266                                 }
6267                         }
6268                 }
6269         }
6270 }
6271
6272 void Mod_CollisionBIH_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6273 {
6274         if (VectorCompare(start, end))
6275         {
6276                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6277                 return;
6278         }
6279         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6280 }
6281
6282 void Mod_CollisionBIH_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *thisbrush_start, colbrushf_t *thisbrush_end, int hitsupercontentsmask)
6283 {
6284         const bih_t *bih;
6285         const bih_leaf_t *leaf;
6286         const bih_node_t *node;
6287         const colbrushf_t *brush;
6288         const int *e;
6289         const texture_t *texture;
6290         vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6291         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6292         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6293         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6294
6295         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6296         {
6297                 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6298                         Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6299                 else
6300                         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6301                 return;
6302         }
6303
6304         bih = &model->collision_bih;
6305         if(!bih->nodes)
6306                 return;
6307         nodenum = bih->rootnode;
6308
6309         // box trace, performed as brush trace
6310         memset(trace, 0, sizeof(*trace));
6311         trace->fraction = 1;
6312         trace->realfraction = 1;
6313         trace->hitsupercontentsmask = hitsupercontentsmask;
6314
6315         // calculate tracebox-like parameters for efficient culling
6316         VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6317         VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6318         VectorSubtract(thisbrush_start->mins, start, startmins);
6319         VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6320         VectorSubtract(thisbrush_end->mins, end, endmins);
6321         VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6322         mins[0] = min(startmins[0], endmins[0]);
6323         mins[1] = min(startmins[1], endmins[1]);
6324         mins[2] = min(startmins[2], endmins[2]);
6325         maxs[0] = max(startmaxs[0], endmaxs[0]);
6326         maxs[1] = max(startmaxs[1], endmaxs[1]);
6327         maxs[2] = max(startmaxs[2], endmaxs[2]);
6328
6329         // push first node
6330         nodestackline[nodestackpos][0] = start[0];
6331         nodestackline[nodestackpos][1] = start[1];
6332         nodestackline[nodestackpos][2] = start[2];
6333         nodestackline[nodestackpos][3] = end[0];
6334         nodestackline[nodestackpos][4] = end[1];
6335         nodestackline[nodestackpos][5] = end[2];
6336         nodestack[nodestackpos++] = nodenum;
6337         while (nodestackpos)
6338         {
6339                 nodenum = nodestack[--nodestackpos];
6340                 node = bih->nodes + nodenum;
6341                 VectorCopy(nodestackline[nodestackpos], nodestart);
6342                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6343                 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6344                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6345                         continue;
6346                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6347                 {
6348                         // recurse children of the split
6349                         axis = node->type - BIH_SPLITX;
6350                         d1 = node->backmax - nodestart[axis] - mins[axis];
6351                         d2 = node->backmax - nodeend[axis] - mins[axis];
6352                         d3 = nodestart[axis] - node->frontmin + maxs[axis];
6353                         d4 = nodeend[axis] - node->frontmin + maxs[axis];
6354                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6355                         {
6356                         case  0: /* >>>> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6357                         case  1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6358                         case  2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6359                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6360                         case  4: /* >><> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6361                         case  5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6362                         case  6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6363                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6364                         case  8: /* >>>< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6365                         case  9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6366                         case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6367                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6368                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6369                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6370                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6371                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
6372                         }
6373                 }
6374                 else if (node->type == BIH_UNORDERED)
6375                 {
6376                         // calculate sweep bounds for this node
6377                         // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6378                         VectorSubtract(node->mins, maxs, nodebigmins);
6379                         VectorSubtract(node->maxs, mins, nodebigmaxs);
6380                         // clip line to this node bounds
6381                         axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6382                         axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6383                         axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6384                         // some of the line intersected the enlarged node box
6385                         // calculate sweep bounds for this node
6386                         sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6387                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6388                         {
6389                                 leaf = bih->leafs + node->children[axis];
6390                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6391                                         continue;
6392                                 switch(leaf->type)
6393                                 {
6394                                 case BIH_BRUSH:
6395                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6396                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6397                                         break;
6398                                 case BIH_COLLISIONTRIANGLE:
6399                                         if (!mod_q3bsp_curves_collisions.integer)
6400                                                 continue;
6401                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6402                                         texture = model->data_textures + leaf->textureindex;
6403                                         Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6404                                         break;
6405                                 case BIH_RENDERTRIANGLE:
6406                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6407                                         texture = model->data_textures + leaf->textureindex;
6408                                         Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6409                                         break;
6410                                 }
6411                         }
6412                 }
6413         }
6414 }
6415
6416 void Mod_CollisionBIH_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
6417 {
6418         colboxbrushf_t thisbrush_start, thisbrush_end;
6419         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6420
6421         // box trace, performed as brush trace
6422         VectorAdd(start, boxmins, boxstartmins);
6423         VectorAdd(start, boxmaxs, boxstartmaxs);
6424         VectorAdd(end, boxmins, boxendmins);
6425         VectorAdd(end, boxmaxs, boxendmaxs);
6426         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6427         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6428         Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6429 }
6430
6431
6432 static int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6433 {
6434         trace_t trace;
6435         Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6436         return trace.startsupercontents;
6437 }
6438
6439 void Mod_CollisionBIH_TracePoint_Mesh(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
6440 {
6441 #if 0
6442         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6443         vec3_t end;
6444         int hitsupercontents;
6445         VectorSet(end, start[0], start[1], model->normalmins[2]);
6446 #endif
6447         memset(trace, 0, sizeof(*trace));
6448         trace->fraction = 1;
6449         trace->realfraction = 1;
6450         trace->hitsupercontentsmask = hitsupercontentsmask;
6451 #if 0
6452         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6453         hitsupercontents = trace->hitsupercontents;
6454         memset(trace, 0, sizeof(*trace));
6455         trace->fraction = 1;
6456         trace->realfraction = 1;
6457         trace->hitsupercontentsmask = hitsupercontentsmask;
6458         trace->startsupercontents = hitsupercontents;
6459 #endif
6460 }
6461
6462 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6463 {
6464 #if 0
6465         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6466         trace_t trace;
6467         vec3_t end;
6468         VectorSet(end, start[0], start[1], model->normalmins[2]);
6469         memset(&trace, 0, sizeof(trace));
6470         trace.fraction = 1;
6471         trace.realfraction = 1;
6472         trace.hitsupercontentsmask = 0;
6473         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6474         return trace.hitsupercontents;
6475 #else
6476         return 0;
6477 #endif
6478 }
6479
6480 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6481 {
6482         int i;
6483         mleaf_t *leaf;
6484         colbrushf_t *brush;
6485         // find which leaf the point is in
6486         while (node->plane)
6487                 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6488         // point trace the brushes
6489         leaf = (mleaf_t *)node;
6490         for (i = 0;i < leaf->numleafbrushes;i++)
6491         {
6492                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6493                 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6494                 {
6495                         brush->markframe = markframe;
6496                         Collision_TracePointBrushFloat(trace, point, brush);
6497                 }
6498         }
6499         // can't do point traces on curves (they have no thickness)
6500 }
6501
6502 static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t start, const vec3_t end, vec_t startfrac, vec_t endfrac, const vec3_t linestart, const vec3_t lineend, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
6503 {
6504         int i, startside, endside;
6505         float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6506         mleaf_t *leaf;
6507         msurface_t *surface;
6508         mplane_t *plane;
6509         colbrushf_t *brush;
6510         // walk the tree until we hit a leaf, recursing for any split cases
6511         while (node->plane)
6512         {
6513 #if 0
6514                 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6515                         return;
6516                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6517                 node = node->children[1];
6518 #else
6519                 // abort if this part of the bsp tree can not be hit by this trace
6520 //              if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6521 //                      return;
6522                 plane = node->plane;
6523                 // axial planes are much more common than non-axial, so an optimized
6524                 // axial case pays off here
6525                 if (plane->type < 3)
6526                 {
6527                         dist1 = start[plane->type] - plane->dist;
6528                         dist2 = end[plane->type] - plane->dist;
6529                 }
6530                 else
6531                 {
6532                         dist1 = DotProduct(start, plane->normal) - plane->dist;
6533                         dist2 = DotProduct(end, plane->normal) - plane->dist;
6534                 }
6535                 startside = dist1 < 0;
6536                 endside = dist2 < 0;
6537                 if (startside == endside)
6538                 {
6539                         // most of the time the line fragment is on one side of the plane
6540                         node = node->children[startside];
6541                 }
6542                 else
6543                 {
6544                         // line crosses node plane, split the line
6545                         dist1 = PlaneDiff(linestart, plane);
6546                         dist2 = PlaneDiff(lineend, plane);
6547                         midfrac = dist1 / (dist1 - dist2);
6548                         VectorLerp(linestart, midfrac, lineend, mid);
6549                         // take the near side first
6550                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6551                         // if we found an impact on the front side, don't waste time
6552                         // exploring the far side
6553                         if (midfrac <= trace->realfraction)
6554                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6555                         return;
6556                 }
6557 #endif
6558         }
6559         // abort if this part of the bsp tree can not be hit by this trace
6560 //      if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6561 //              return;
6562         // hit a leaf
6563         nodesegmentmins[0] = min(start[0], end[0]) - 1;
6564         nodesegmentmins[1] = min(start[1], end[1]) - 1;
6565         nodesegmentmins[2] = min(start[2], end[2]) - 1;
6566         nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6567         nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6568         nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6569         // line trace the brushes
6570         leaf = (mleaf_t *)node;
6571 #if 0
6572         if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6573                 return;
6574 #endif
6575         for (i = 0;i < leaf->numleafbrushes;i++)
6576         {
6577                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6578                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6579                 {
6580                         brush->markframe = markframe;
6581                         Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6582                 }
6583         }
6584         // can't do point traces on curves (they have no thickness)
6585         if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6586         {
6587                 // line trace the curves
6588                 for (i = 0;i < leaf->numleafsurfaces;i++)
6589                 {
6590                         surface = model->data_surfaces + leaf->firstleafsurface[i];
6591                         if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6592                         {
6593                                 surface->deprecatedq3collisionmarkframe = markframe;
6594                                 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6595                         }
6596                 }
6597         }
6598 }
6599
6600 static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
6601 {
6602         int i;
6603         int sides;
6604         mleaf_t *leaf;
6605         colbrushf_t *brush;
6606         msurface_t *surface;
6607         mplane_t *plane;
6608         float nodesegmentmins[3], nodesegmentmaxs[3];
6609         // walk the tree until we hit a leaf, recursing for any split cases
6610         while (node->plane)
6611         {
6612 #if 0
6613                 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6614                         return;
6615                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6616                 node = node->children[1];
6617 #else
6618                 // abort if this part of the bsp tree can not be hit by this trace
6619 //              if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6620 //                      return;
6621                 plane = node->plane;
6622                 // axial planes are much more common than non-axial, so an optimized
6623                 // axial case pays off here
6624                 if (plane->type < 3)
6625                 {
6626                         // this is an axial plane, compare bounding box directly to it and
6627                         // recurse sides accordingly
6628                         // recurse down node sides
6629                         // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6630                         //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6631                         //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6632                         sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6633                 }
6634                 else
6635                 {
6636                         // this is a non-axial plane, so check if the start and end boxes
6637                         // are both on one side of the plane to handle 'diagonal' cases
6638                         sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6639                 }
6640                 if (sides == 3)
6641                 {
6642                         // segment crosses plane
6643                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6644                         sides = 2;
6645                 }
6646                 // if sides == 0 then the trace itself is bogus (Not A Number values),
6647                 // in this case we simply pretend the trace hit nothing
6648                 if (sides == 0)
6649                         return; // ERROR: NAN bounding box!
6650                 // take whichever side the segment box is on
6651                 node = node->children[sides - 1];
6652 #endif
6653         }
6654         // abort if this part of the bsp tree can not be hit by this trace
6655 //      if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6656 //              return;
6657         nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6658         nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6659         nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6660         nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6661         nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6662         nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6663         // hit a leaf
6664         leaf = (mleaf_t *)node;
6665 #if 0
6666         if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6667                 return;
6668 #endif
6669         for (i = 0;i < leaf->numleafbrushes;i++)
6670         {
6671                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6672                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6673                 {
6674                         brush->markframe = markframe;
6675                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6676                 }
6677         }
6678         if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6679         {
6680                 for (i = 0;i < leaf->numleafsurfaces;i++)
6681                 {
6682                         surface = model->data_surfaces + leaf->firstleafsurface[i];
6683                         if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6684                         {
6685                                 surface->deprecatedq3collisionmarkframe = markframe;
6686                                 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6687                         }
6688                 }
6689         }
6690 }
6691
6692
6693 static int markframe = 0;
6694
6695 static void Mod_Q3BSP_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
6696 {
6697         int i;
6698         q3mbrush_t *brush;
6699         memset(trace, 0, sizeof(*trace));
6700         trace->fraction = 1;
6701         trace->realfraction = 1;
6702         trace->hitsupercontentsmask = hitsupercontentsmask;
6703         if (mod_collision_bih.integer)
6704                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6705         else if (model->brush.submodel)
6706         {
6707                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6708                         if (brush->colbrushf)
6709                                 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6710         }
6711         else
6712                 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6713 }
6714
6715 static void Mod_Q3BSP_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6716 {
6717         int i;
6718         float segmentmins[3], segmentmaxs[3];
6719         msurface_t *surface;
6720         q3mbrush_t *brush;
6721
6722         if (VectorCompare(start, end))
6723         {
6724                 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6725                 return;
6726         }
6727
6728         memset(trace, 0, sizeof(*trace));
6729         trace->fraction = 1;
6730         trace->realfraction = 1;
6731         trace->hitsupercontentsmask = hitsupercontentsmask;
6732         segmentmins[0] = min(start[0], end[0]) - 1;
6733         segmentmins[1] = min(start[1], end[1]) - 1;
6734         segmentmins[2] = min(start[2], end[2]) - 1;
6735         segmentmaxs[0] = max(start[0], end[0]) + 1;
6736         segmentmaxs[1] = max(start[1], end[1]) + 1;
6737         segmentmaxs[2] = max(start[2], end[2]) + 1;
6738         if (mod_collision_bih.integer)
6739                 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6740         else if (model->brush.submodel)
6741         {
6742                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6743                         if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6744                                 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6745                 if (mod_q3bsp_curves_collisions.integer)
6746                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6747                                 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6748                                         Collision_TraceLineTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6749         }
6750         else
6751                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6752 }
6753
6754 static void Mod_Q3BSP_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *start, colbrushf_t *end, int hitsupercontentsmask)
6755 {
6756         float segmentmins[3], segmentmaxs[3];
6757         int i;
6758         msurface_t *surface;
6759         q3mbrush_t *brush;
6760
6761         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6762         {
6763                 if (VectorCompare(start->mins, end->mins))
6764                         Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6765                 else
6766                         Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6767                 return;
6768         }
6769
6770         // box trace, performed as brush trace
6771         memset(trace, 0, sizeof(*trace));
6772         trace->fraction = 1;
6773         trace->realfraction = 1;
6774         trace->hitsupercontentsmask = hitsupercontentsmask;
6775         segmentmins[0] = min(start->mins[0], end->mins[0]);
6776         segmentmins[1] = min(start->mins[1], end->mins[1]);
6777         segmentmins[2] = min(start->mins[2], end->mins[2]);
6778         segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6779         segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6780         segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6781         if (mod_collision_bih.integer)
6782                 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6783         else if (model->brush.submodel)
6784         {
6785                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6786                         if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6787                                 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6788                 if (mod_q3bsp_curves_collisions.integer)
6789                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6790                                 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6791                                         Collision_TraceBrushTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6792         }
6793         else
6794                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6795 }
6796
6797 static void Mod_Q3BSP_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
6798 {
6799         colboxbrushf_t thisbrush_start, thisbrush_end;
6800         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6801
6802         // box trace, performed as brush trace
6803         VectorAdd(start, boxmins, boxstartmins);
6804         VectorAdd(start, boxmaxs, boxstartmaxs);
6805         VectorAdd(end, boxmins, boxendmins);
6806         VectorAdd(end, boxmaxs, boxendmaxs);
6807         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6808         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6809         Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6810 }
6811
6812 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6813 {
6814         int i;
6815         int supercontents = 0;
6816         q3mbrush_t *brush;
6817         if (mod_collision_bih.integer)
6818         {
6819                 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
6820         }
6821         // test if the point is inside each brush
6822         else if (model->brush.submodel)
6823         {
6824                 // submodels are effectively one leaf
6825                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6826                         if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6827                                 supercontents |= brush->colbrushf->supercontents;
6828         }
6829         else
6830         {
6831                 mnode_t *node = model->brush.data_nodes;
6832                 mleaf_t *leaf;
6833                 // find which leaf the point is in
6834                 while (node->plane)
6835                         node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6836                 leaf = (mleaf_t *)node;
6837                 // now check the brushes in the leaf
6838                 for (i = 0;i < leaf->numleafbrushes;i++)
6839                 {
6840                         brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6841                         if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6842                                 supercontents |= brush->colbrushf->supercontents;
6843                 }
6844         }
6845         return supercontents;
6846 }
6847
6848 void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6849 {
6850         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6851 }
6852
6853
6854 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6855 {
6856         int j;
6857         int bihnumleafs;
6858         int bihmaxnodes;
6859         int brushindex;
6860         int triangleindex;
6861         int bihleafindex;
6862         int nummodelbrushes = model->nummodelbrushes;
6863         int nummodelsurfaces = model->nummodelsurfaces;
6864         const int *e;
6865         const int *collisionelement3i;
6866         const float *collisionvertex3f;
6867         const int *renderelement3i;
6868         const float *rendervertex3f;
6869         bih_leaf_t *bihleafs;
6870         bih_node_t *bihnodes;
6871         int *temp_leafsort;
6872         int *temp_leafsortscratch;
6873         const msurface_t *surface;
6874         const q3mbrush_t *brush;
6875
6876         // find out how many BIH leaf nodes we need
6877         bihnumleafs = 0;
6878         if (userendersurfaces)
6879         {
6880                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6881                         bihnumleafs += surface->num_triangles;
6882         }
6883         else
6884         {
6885                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6886                         if (brush->colbrushf)
6887                                 bihnumleafs++;
6888                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6889                 {
6890                         if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6891                                 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6892                         else
6893                                 bihnumleafs += surface->num_collisiontriangles;
6894                 }
6895         }
6896
6897         if (!bihnumleafs)
6898                 return NULL;
6899
6900         // allocate the memory for the BIH leaf nodes
6901         bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6902
6903         // now populate the BIH leaf nodes
6904         bihleafindex = 0;
6905
6906         // add render surfaces
6907         renderelement3i = model->surfmesh.data_element3i;
6908         rendervertex3f = model->surfmesh.data_vertex3f;
6909         for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6910         {
6911                 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6912                 {
6913                         if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6914                                 continue;
6915                         bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6916                         bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6917                         bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6918                         bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6919                         bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6920                         bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6921                         bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6922                         bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6923                         bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6924                         bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6925                         bihleafindex++;
6926                 }
6927         }
6928
6929         if (!userendersurfaces)
6930         {
6931                 // add collision brushes
6932                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6933                 {
6934                         if (!brush->colbrushf)
6935                                 continue;
6936                         bihleafs[bihleafindex].type = BIH_BRUSH;
6937                         bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6938                         bihleafs[bihleafindex].surfaceindex = -1;
6939                         bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6940                         VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6941                         VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6942                         bihleafindex++;
6943                 }
6944
6945                 // add collision surfaces
6946                 collisionelement3i = model->brush.data_collisionelement3i;
6947                 collisionvertex3f = model->brush.data_collisionvertex3f;
6948                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6949                 {
6950                         for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6951                         {
6952                                 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6953                                 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6954                                 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6955                                 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6956                                 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6957                                 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6958                                 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6959                                 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6960                                 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6961                                 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6962                                 bihleafindex++;
6963                         }
6964                 }
6965         }
6966
6967         // allocate buffers for the produced and temporary data
6968         bihmaxnodes = bihnumleafs + 1;
6969         bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6970         temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6971         temp_leafsortscratch = temp_leafsort + bihnumleafs;
6972
6973         // now build it
6974         BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6975
6976         // we're done with the temporary data
6977         Mem_Free(temp_leafsort);
6978
6979         // resize the BIH nodes array if it over-allocated
6980         if (out->maxnodes > out->numnodes)
6981         {
6982                 out->maxnodes = out->numnodes;
6983                 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
6984         }
6985
6986         return out;
6987 }
6988
6989 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6990 {
6991         int supercontents = 0;
6992         if (nativecontents & CONTENTSQ3_SOLID)
6993                 supercontents |= SUPERCONTENTS_SOLID;
6994         if (nativecontents & CONTENTSQ3_WATER)
6995                 supercontents |= SUPERCONTENTS_WATER;
6996         if (nativecontents & CONTENTSQ3_SLIME)
6997                 supercontents |= SUPERCONTENTS_SLIME;
6998         if (nativecontents & CONTENTSQ3_LAVA)
6999                 supercontents |= SUPERCONTENTS_LAVA;
7000         if (nativecontents & CONTENTSQ3_BODY)
7001                 supercontents |= SUPERCONTENTS_BODY;
7002         if (nativecontents & CONTENTSQ3_CORPSE)
7003                 supercontents |= SUPERCONTENTS_CORPSE;
7004         if (nativecontents & CONTENTSQ3_NODROP)
7005                 supercontents |= SUPERCONTENTS_NODROP;
7006         if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7007                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7008         if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7009                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7010         if (nativecontents & CONTENTSQ3_DONOTENTER)
7011                 supercontents |= SUPERCONTENTS_DONOTENTER;
7012         if (nativecontents & CONTENTSQ3_BOTCLIP)
7013                 supercontents |= SUPERCONTENTS_BOTCLIP;
7014         if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7015                 supercontents |= SUPERCONTENTS_OPAQUE;
7016         return supercontents;
7017 }
7018
7019 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7020 {
7021         int nativecontents = 0;
7022         if (supercontents & SUPERCONTENTS_SOLID)
7023                 nativecontents |= CONTENTSQ3_SOLID;
7024         if (supercontents & SUPERCONTENTS_WATER)
7025                 nativecontents |= CONTENTSQ3_WATER;
7026         if (supercontents & SUPERCONTENTS_SLIME)
7027                 nativecontents |= CONTENTSQ3_SLIME;
7028         if (supercontents & SUPERCONTENTS_LAVA)
7029                 nativecontents |= CONTENTSQ3_LAVA;
7030         if (supercontents & SUPERCONTENTS_BODY)
7031                 nativecontents |= CONTENTSQ3_BODY;
7032         if (supercontents & SUPERCONTENTS_CORPSE)
7033                 nativecontents |= CONTENTSQ3_CORPSE;
7034         if (supercontents & SUPERCONTENTS_NODROP)
7035                 nativecontents |= CONTENTSQ3_NODROP;
7036         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7037                 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7038         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7039                 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7040         if (supercontents & SUPERCONTENTS_DONOTENTER)
7041                 nativecontents |= CONTENTSQ3_DONOTENTER;
7042         if (supercontents & SUPERCONTENTS_BOTCLIP)
7043                 nativecontents |= CONTENTSQ3_BOTCLIP;
7044         if (!(supercontents & SUPERCONTENTS_OPAQUE))
7045                 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7046         return nativecontents;
7047 }
7048
7049 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7050 {
7051         int numleafs;
7052         while (node->plane)
7053         {
7054                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7055                 node = node->children[1];
7056         }
7057         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7058         if (loadmodel->brush.num_leafs < numleafs)
7059                 loadmodel->brush.num_leafs = numleafs;
7060 }
7061
7062 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7063 {
7064         int i, j, lumps;
7065         q3dheader_t *header;
7066         float corner[3], yawradius, modelradius;
7067
7068         mod->modeldatatypestring = "Q3BSP";
7069
7070         mod->type = mod_brushq3;
7071         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7072         mod->numskins = 1;
7073
7074         header = (q3dheader_t *)buffer;
7075         if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7076                 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7077
7078         i = LittleLong(header->version);
7079         if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7080                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7081
7082         mod->soundfromcenter = true;
7083         mod->TraceBox = Mod_Q3BSP_TraceBox;
7084         mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7085         mod->TraceLine = Mod_Q3BSP_TraceLine;
7086         mod->TracePoint = Mod_Q3BSP_TracePoint;
7087         mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7088         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7089         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7090         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7091         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7092         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7093         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7094         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7095         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7096         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7097         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7098         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7099         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7100         mod->brush.AmbientSoundLevelsForPoint = NULL;
7101         mod->brush.RoundUpToHullSize = NULL;
7102         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7103         mod->Draw = R_Q1BSP_Draw;
7104         mod->DrawDepth = R_Q1BSP_DrawDepth;
7105         mod->DrawDebug = R_Q1BSP_DrawDebug;
7106         mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7107         mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7108         mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7109         mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7110         mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7111         mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7112         mod->DrawLight = R_Q1BSP_DrawLight;
7113
7114         mod_base = (unsigned char *)header;
7115
7116         // swap all the lumps
7117         header->ident = LittleLong(header->ident);
7118         header->version = LittleLong(header->version);
7119         lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7120         for (i = 0;i < lumps;i++)
7121         {
7122                 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7123                 if((char *) bufferend < (char *) buffer + j)
7124                         Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7125                 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7126                 if((char *) bufferend < (char *) buffer + j)
7127                         Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7128         }
7129         /*
7130          * NO, do NOT clear them!
7131          * they contain actual data referenced by other stuff.
7132          * Instead, before using the advertisements lump, check header->versio
7133          * again!
7134          * Sorry, but otherwise it breaks memory of the first lump.
7135         for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7136         {
7137                 header->lumps[i].fileofs = 0;
7138                 header->lumps[i].filelen = 0;
7139         }
7140         */
7141
7142         mod->brush.qw_md4sum = 0;
7143         mod->brush.qw_md4sum2 = 0;
7144         for (i = 0;i < lumps;i++)
7145         {
7146                 if (i == Q3LUMP_ENTITIES)
7147                         continue;
7148                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7149                 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7150                         continue;
7151                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7152
7153                 // all this checksumming can take a while, so let's send keepalives here too
7154                 CL_KeepaliveMessage(false);
7155         }
7156
7157         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7158         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7159         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7160         if (header->version == Q3BSPVERSION_IG)
7161                 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7162         else
7163                 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7164         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7165         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7166         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7167         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7168         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7169         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7170         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7171         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7172         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7173         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7174         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7175         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7176         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7177         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7178
7179         // the MakePortals code works fine on the q3bsp data as well
7180         if (mod_bsp_portalize.integer)
7181                 Mod_Q1BSP_MakePortals();
7182
7183         // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7184         loadmodel->brush.supportwateralpha = true;
7185
7186         // make a single combined shadow mesh to allow optimized shadow volume creation
7187         Mod_Q1BSP_CreateShadowMesh(loadmodel);
7188
7189         loadmodel->brush.num_leafs = 0;
7190         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7191
7192         if (loadmodel->brush.numsubmodels)
7193                 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7194
7195         mod = loadmodel;
7196         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7197         {
7198                 if (i > 0)
7199                 {
7200                         char name[10];
7201                         // duplicate the basic information
7202                         dpsnprintf(name, sizeof(name), "*%i", i);
7203                         mod = Mod_FindName(name, loadmodel->name);
7204                         // copy the base model to this one
7205                         *mod = *loadmodel;
7206                         // rename the clone back to its proper name
7207                         strlcpy(mod->name, name, sizeof(mod->name));
7208                         mod->brush.parentmodel = loadmodel;
7209                         // textures and memory belong to the main model
7210                         mod->texturepool = NULL;
7211                         mod->mempool = NULL;
7212                         mod->brush.GetPVS = NULL;
7213                         mod->brush.FatPVS = NULL;
7214                         mod->brush.BoxTouchingPVS = NULL;
7215                         mod->brush.BoxTouchingLeafPVS = NULL;
7216                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7217                         mod->brush.FindBoxClusters = NULL;
7218                         mod->brush.LightPoint = NULL;
7219                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7220                 }
7221                 mod->brush.submodel = i;
7222                 if (loadmodel->brush.submodels)
7223                         loadmodel->brush.submodels[i] = mod;
7224
7225                 // make the model surface list (used by shadowing/lighting)
7226                 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7227                 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7228                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7229                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7230                 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7231                 Mod_MakeSortedSurfaces(mod);
7232
7233                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7234                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7235                 // enlarge the bounding box to enclose all geometry of this model,
7236                 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7237                 // which can in turn mess up the farclip (as well as culling when
7238                 // outside the level - an unimportant concern)
7239
7240                 //printf("Editing model %d... BEFORE re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7241                 for (j = 0;j < mod->nummodelsurfaces;j++)
7242                 {
7243                         const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7244                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7245                         int k;
7246                         if (!surface->num_vertices)
7247                                 continue;
7248                         for (k = 0;k < surface->num_vertices;k++, v += 3)
7249                         {
7250                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7251                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7252                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7253                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7254                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7255                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7256                         }
7257                 }
7258                 //printf("Editing model %d... AFTER re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7259                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7260                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7261                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7262                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7263                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7264                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7265                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7266                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7267                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7268                 mod->yawmins[2] = mod->normalmins[2];
7269                 mod->yawmaxs[2] = mod->normalmaxs[2];
7270                 mod->radius = modelradius;
7271                 mod->radius2 = modelradius * modelradius;
7272
7273                 // this gets altered below if sky or water is used
7274                 mod->DrawSky = NULL;
7275                 mod->DrawAddWaterPlanes = NULL;
7276
7277                 for (j = 0;j < mod->nummodelsurfaces;j++)
7278                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7279                                 break;
7280                 if (j < mod->nummodelsurfaces)
7281                         mod->DrawSky = R_Q1BSP_DrawSky;
7282
7283                 for (j = 0;j < mod->nummodelsurfaces;j++)
7284                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7285                                 break;
7286                 if (j < mod->nummodelsurfaces)
7287                         mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7288
7289                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7290                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7291
7292                 // generate VBOs and other shared data before cloning submodels
7293                 if (i == 0)
7294                         Mod_BuildVBOs();
7295         }
7296
7297         if (mod_q3bsp_sRGBlightmaps.integer)
7298         {
7299                 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7300                 {
7301                         // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7302                         // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7303                         // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7304                         // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7305                         //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7306                 }
7307                 else // if this is NOT set, regular rendering looks right by this requirement anyway
7308                 {
7309                         /*
7310                         // we want color 1 to do the same as without sRGB
7311                         // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7312                         loadmodel->lightmapscale *= 2.476923f; // fixes max level
7313                         */
7314
7315                         // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7316                         // we need to undo that
7317                         loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7318                 }
7319         }
7320
7321         Con_DPrintf("Stats for q3bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
7322 }
7323
7324 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7325 {
7326         int i = LittleLong(((int *)buffer)[1]);
7327         if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7328                 Mod_Q3BSP_Load(mod,buffer, bufferend);
7329         else if (i == Q2BSPVERSION)
7330                 Mod_Q2BSP_Load(mod,buffer, bufferend);
7331         else
7332                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7333 }
7334
7335 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7336 {
7337         Host_Error("Mod_MAP_Load: not yet implemented");
7338 }
7339
7340 typedef struct objvertex_s
7341 {
7342         int nextindex;
7343         int submodelindex;
7344         int textureindex;
7345         float v[3];
7346         float vt[2];
7347         float vn[3];
7348 }
7349 objvertex_t;
7350
7351 static unsigned char nobsp_pvs[1] = {1};
7352
7353 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7354 {
7355         const char *textbase = (char *)buffer, *text = textbase;
7356         char *s;
7357         char *argv[512];
7358         char line[1024];
7359         char materialname[MAX_QPATH];
7360         int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7361         int index1, index2, index3;
7362         objvertex_t vfirst, vprev, vcurrent;
7363         int argc;
7364         int linelen;
7365         int numtriangles = 0;
7366         int maxtriangles = 0;
7367         objvertex_t *vertices = NULL;
7368         int linenumber = 0;
7369         int maxtextures = 0, numtextures = 0, textureindex = 0;
7370         int maxv = 0, numv = 1;
7371         int maxvt = 0, numvt = 1;
7372         int maxvn = 0, numvn = 1;
7373         char *texturenames = NULL;
7374         float dist, modelradius, modelyawradius, yawradius;
7375         float *v = NULL;
7376         float *vt = NULL;
7377         float *vn = NULL;
7378         float mins[3];
7379         float maxs[3];
7380         float corner[3];
7381         objvertex_t *thisvertex = NULL;
7382         int vertexhashindex;
7383         int *vertexhashtable = NULL;
7384         objvertex_t *vertexhashdata = NULL;
7385         objvertex_t *vdata = NULL;
7386         int vertexhashsize = 0;
7387         int vertexhashcount = 0;
7388         skinfile_t *skinfiles = NULL;
7389         unsigned char *data = NULL;
7390         int *submodelfirstsurface;
7391         msurface_t *surface;
7392         msurface_t *tempsurfaces;
7393
7394         memset(&vfirst, 0, sizeof(vfirst));
7395         memset(&vprev, 0, sizeof(vprev));
7396         memset(&vcurrent, 0, sizeof(vcurrent));
7397
7398         dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7399
7400         loadmodel->modeldatatypestring = "OBJ";
7401
7402         loadmodel->type = mod_obj;
7403         loadmodel->soundfromcenter = true;
7404         loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7405         loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7406         loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7407         loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7408         loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7409         loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7410         loadmodel->brush.TraceLineOfSight = NULL;
7411         loadmodel->brush.SuperContentsFromNativeContents = NULL;
7412         loadmodel->brush.NativeContentsFromSuperContents = NULL;
7413         loadmodel->brush.GetPVS = NULL;
7414         loadmodel->brush.FatPVS = NULL;
7415         loadmodel->brush.BoxTouchingPVS = NULL;
7416         loadmodel->brush.BoxTouchingLeafPVS = NULL;
7417         loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7418         loadmodel->brush.FindBoxClusters = NULL;
7419         loadmodel->brush.LightPoint = NULL;
7420         loadmodel->brush.FindNonSolidLocation = NULL;
7421         loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7422         loadmodel->brush.RoundUpToHullSize = NULL;
7423         loadmodel->brush.PointInLeaf = NULL;
7424         loadmodel->Draw = R_Q1BSP_Draw;
7425         loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7426         loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7427         loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7428         loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7429         loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7430         loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7431         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7432         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7433         loadmodel->DrawLight = R_Q1BSP_DrawLight;
7434
7435         skinfiles = Mod_LoadSkinFiles();
7436         if (loadmodel->numskins < 1)
7437                 loadmodel->numskins = 1;
7438
7439         // make skinscenes for the skins (no groups)
7440         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7441         for (i = 0;i < loadmodel->numskins;i++)
7442         {
7443                 loadmodel->skinscenes[i].firstframe = i;
7444                 loadmodel->skinscenes[i].framecount = 1;
7445                 loadmodel->skinscenes[i].loop = true;
7446                 loadmodel->skinscenes[i].framerate = 10;
7447         }
7448
7449         VectorClear(mins);
7450         VectorClear(maxs);
7451
7452         // we always have model 0, i.e. the first "submodel"
7453         loadmodel->brush.numsubmodels = 1;
7454
7455         // parse the OBJ text now
7456         for(;;)
7457         {
7458                 static char emptyarg[1] = "";
7459                 if (!*text)
7460                         break;
7461                 linenumber++;
7462                 linelen = 0;
7463                 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7464                         line[linelen] = text[linelen];
7465                 line[linelen] = 0;
7466                 for (argc = 0;argc < 4;argc++)
7467                         argv[argc] = emptyarg;
7468                 argc = 0;
7469                 s = line;
7470                 while (*s == ' ' || *s == '\t')
7471                         s++;
7472                 while (*s)
7473                 {
7474                         argv[argc++] = s;
7475                         while (*s > ' ')
7476                                 s++;
7477                         if (!*s)
7478                                 break;
7479                         *s++ = 0;
7480                         while (*s == ' ' || *s == '\t')
7481                                 s++;
7482                 }
7483                 text += linelen;
7484                 if (*text == '\r')
7485                         text++;
7486                 if (*text == '\n')
7487                         text++;
7488                 if (!argc)
7489                         continue;
7490                 if (argv[0][0] == '#')
7491                         continue;
7492                 if (!strcmp(argv[0], "v"))
7493                 {
7494                         if (maxv <= numv)
7495                         {
7496                                 maxv = max(maxv * 2, 1024);
7497                                 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7498                         }
7499                         v[numv*3+0] = atof(argv[1]);
7500                         v[numv*3+2] = atof(argv[2]);
7501                         v[numv*3+1] = atof(argv[3]);
7502                         numv++;
7503                 }
7504                 else if (!strcmp(argv[0], "vt"))
7505                 {
7506                         if (maxvt <= numvt)
7507                         {
7508                                 maxvt = max(maxvt * 2, 1024);
7509                                 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7510                         }
7511                         vt[numvt*2+0] = atof(argv[1]);
7512                         vt[numvt*2+1] = 1-atof(argv[2]);
7513                         numvt++;
7514                 }
7515                 else if (!strcmp(argv[0], "vn"))
7516                 {
7517                         if (maxvn <= numvn)
7518                         {
7519                                 maxvn = max(maxvn * 2, 1024);
7520                                 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7521                         }
7522                         vn[numvn*3+0] = atof(argv[1]);
7523                         vn[numvn*3+2] = atof(argv[2]);
7524                         vn[numvn*3+1] = atof(argv[3]);
7525                         numvn++;
7526                 }
7527                 else if (!strcmp(argv[0], "f"))
7528                 {
7529                         if (!numtextures)
7530                         {
7531                                 if (maxtextures <= numtextures)
7532                                 {
7533                                         maxtextures = max(maxtextures * 2, 256);
7534                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7535                                 }
7536                                 textureindex = numtextures++;
7537                                 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7538                         }
7539                         for (j = 1;j < argc;j++)
7540                         {
7541                                 index1 = atoi(argv[j]);
7542                                 while(argv[j][0] && argv[j][0] != '/')
7543                                         argv[j]++;
7544                                 if (argv[j][0])
7545                                         argv[j]++;
7546                                 index2 = atoi(argv[j]);
7547                                 while(argv[j][0] && argv[j][0] != '/')
7548                                         argv[j]++;
7549                                 if (argv[j][0])
7550                                         argv[j]++;
7551                                 index3 = atoi(argv[j]);
7552                                 // negative refers to a recent vertex
7553                                 // zero means not specified
7554                                 // positive means an absolute vertex index
7555                                 if (index1 < 0)
7556                                         index1 = numv - index1;
7557                                 if (index2 < 0)
7558                                         index2 = numvt - index2;
7559                                 if (index3 < 0)
7560                                         index3 = numvn - index3;
7561                                 vcurrent.nextindex = -1;
7562                                 vcurrent.textureindex = textureindex;
7563                                 vcurrent.submodelindex = submodelindex;
7564                                 if (v && index1 >= 0 && index1 < numv)
7565                                         VectorCopy(v + 3*index1, vcurrent.v);
7566                                 if (vt && index2 >= 0 && index2 < numvt)
7567                                         Vector2Copy(vt + 2*index2, vcurrent.vt);
7568                                 if (vn && index3 >= 0 && index3 < numvn)
7569                                         VectorCopy(vn + 3*index3, vcurrent.vn);
7570                                 if (numtriangles == 0)
7571                                 {
7572                                         VectorCopy(vcurrent.v, mins);
7573                                         VectorCopy(vcurrent.v, maxs);
7574                                 }
7575                                 else
7576                                 {
7577                                         mins[0] = min(mins[0], vcurrent.v[0]);
7578                                         mins[1] = min(mins[1], vcurrent.v[1]);
7579                                         mins[2] = min(mins[2], vcurrent.v[2]);
7580                                         maxs[0] = max(maxs[0], vcurrent.v[0]);
7581                                         maxs[1] = max(maxs[1], vcurrent.v[1]);
7582                                         maxs[2] = max(maxs[2], vcurrent.v[2]);
7583                                 }
7584                                 if (j == 1)
7585                                         vfirst = vcurrent;
7586                                 else if (j >= 3)
7587                                 {
7588                                         if (maxtriangles <= numtriangles)
7589                                         {
7590                                                 maxtriangles = max(maxtriangles * 2, 32768);
7591                                                 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7592                                         }
7593                                         vertices[numtriangles*3+0] = vfirst;
7594                                         vertices[numtriangles*3+1] = vprev;
7595                                         vertices[numtriangles*3+2] = vcurrent;
7596                                         numtriangles++;
7597                                 }
7598                                 vprev = vcurrent;
7599                         }
7600                 }
7601                 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7602                 {
7603                         submodelindex = atof(argv[1]);
7604                         loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7605                 }
7606                 else if (!strcmp(argv[0], "usemtl"))
7607                 {
7608                         for (i = 0;i < numtextures;i++)
7609                                 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7610                                         break;
7611                         if (i < numtextures)
7612                                 textureindex = i;
7613                         else
7614                         {
7615                                 if (maxtextures <= numtextures)
7616                                 {
7617                                         maxtextures = max(maxtextures * 2, 256);
7618                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7619                                 }
7620                                 textureindex = numtextures++;
7621                                 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7622                         }
7623                 }
7624         }
7625
7626         // now that we have the OBJ data loaded as-is, we can convert it
7627
7628         // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7629         VectorCopy(mins, loadmodel->normalmins);
7630         VectorCopy(maxs, loadmodel->normalmaxs);
7631         dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7632         modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7633         modelyawradius = dist*dist+modelyawradius*modelyawradius;
7634         modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7635         modelradius = modelyawradius + modelradius * modelradius;
7636         modelyawradius = sqrt(modelyawradius);
7637         modelradius = sqrt(modelradius);
7638         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7639         loadmodel->yawmins[2] = loadmodel->normalmins[2];
7640         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] =  modelyawradius;
7641         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7642         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7643         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] =  modelradius;
7644         loadmodel->radius = modelradius;
7645         loadmodel->radius2 = modelradius * modelradius;
7646
7647         // allocate storage for triangles
7648         loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7649         // allocate vertex hash structures to build an optimal vertex subset
7650         vertexhashsize = numtriangles*2;
7651         vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7652         memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7653         vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7654         vertexhashcount = 0;
7655
7656         // gather surface stats for assigning vertex/triangle ranges
7657         firstvertex = 0;
7658         firsttriangle = 0;
7659         elementindex = 0;
7660         loadmodel->num_surfaces = 0;
7661         // allocate storage for the worst case number of surfaces, later we resize
7662         tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7663         submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7664         surface = tempsurfaces;
7665         for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7666         {
7667                 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7668                 for (textureindex = 0;textureindex < numtextures;textureindex++)
7669                 {
7670                         for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7671                         {
7672                                 thisvertex = vertices + vertexindex;
7673                                 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7674                                         break;
7675                         }
7676                         // skip the surface creation if there are no triangles for it
7677                         if (vertexindex == numtriangles*3)
7678                                 continue;
7679                         // create a surface for these vertices
7680                         surfacevertices = 0;
7681                         surfaceelements = 0;
7682                         // we hack in a texture index in the surface to be fixed up later...
7683                         surface->texture = (texture_t *)((size_t)textureindex);
7684                         // calculate bounds as we go
7685                         VectorCopy(thisvertex->v, surface->mins);
7686                         VectorCopy(thisvertex->v, surface->maxs);
7687                         for (;vertexindex < numtriangles*3;vertexindex++)
7688                         {
7689                                 thisvertex = vertices + vertexindex;
7690                                 if (thisvertex->submodelindex != submodelindex)
7691                                         continue;
7692                                 if (thisvertex->textureindex != textureindex)
7693                                         continue;
7694                                 // add vertex to surface bounds
7695                                 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7696                                 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7697                                 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7698                                 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7699                                 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7700                                 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7701                                 // add the vertex if it is not found in the merged set, and
7702                                 // get its index (triangle element) for the surface
7703                                 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7704                                 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7705                                 {
7706                                         vdata = vertexhashdata + i;
7707                                         if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7708                                                 break;
7709                                 }
7710                                 if (i < 0)
7711                                 {
7712                                         i = vertexhashcount++;
7713                                         vdata = vertexhashdata + i;
7714                                         *vdata = *thisvertex;
7715                                         vdata->nextindex = vertexhashtable[vertexhashindex];
7716                                         vertexhashtable[vertexhashindex] = i;
7717                                         surfacevertices++;
7718                                 }
7719                                 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7720                                 surfaceelements++;
7721                         }
7722                         surfacetriangles = surfaceelements / 3;
7723                         surface->num_vertices = surfacevertices;
7724                         surface->num_triangles = surfacetriangles;
7725                         surface->num_firstvertex = firstvertex;
7726                         surface->num_firsttriangle = firsttriangle;
7727                         firstvertex += surface->num_vertices;
7728                         firsttriangle += surface->num_triangles;
7729                         surface++;
7730                         loadmodel->num_surfaces++;
7731                 }
7732         }
7733         submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7734         numvertices = firstvertex;
7735         loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7736         tempsurfaces = NULL;
7737
7738         // allocate storage for final mesh data
7739         loadmodel->num_textures = numtextures * loadmodel->numskins;
7740         loadmodel->num_texturesperskin = numtextures;
7741         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + (r_enableshadowvolumes.integer ? numtriangles * sizeof(int[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7742         loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7743         loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7744         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7745         loadmodel->surfmesh.num_vertices = numvertices;
7746         loadmodel->surfmesh.num_triangles = numtriangles;
7747         if (r_enableshadowvolumes.integer)
7748                 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7749         loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7750         loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7751         loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7752         loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7753         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7754         if (loadmodel->surfmesh.num_vertices <= 65536)
7755                 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7756
7757         for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7758         {
7759                 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7760                 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7761                 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7762         }
7763
7764         // load the textures
7765         for (textureindex = 0;textureindex < numtextures;textureindex++)
7766                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7767         Mod_FreeSkinFiles(skinfiles);
7768
7769         // set the surface textures to their real values now that we loaded them...
7770         for (i = 0;i < loadmodel->num_surfaces;i++)
7771                 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7772
7773         // free data
7774         Mem_Free(vertices);
7775         Mem_Free(texturenames);
7776         Mem_Free(v);
7777         Mem_Free(vt);
7778         Mem_Free(vn);
7779         Mem_Free(vertexhashtable);
7780         Mem_Free(vertexhashdata);
7781
7782         // make a single combined shadow mesh to allow optimized shadow volume creation
7783         Mod_Q1BSP_CreateShadowMesh(loadmodel);
7784
7785         // compute all the mesh information that was not loaded from the file
7786         if (loadmodel->surfmesh.data_element3s)
7787                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7788                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7789         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7790         // generate normals if the file did not have them
7791         if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7792                 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
7793         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
7794         if (loadmodel->surfmesh.data_neighbor3i)
7795                 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7796
7797         // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7798         loadmodel->brush.num_visleafs = 1;
7799         loadmodel->brush.num_leafs = 1;
7800         loadmodel->brush.num_nodes = 0;
7801         loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7802         loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7803         loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7804         loadmodel->brush.num_pvsclusters = 1;
7805         loadmodel->brush.num_pvsclusterbytes = 1;
7806         loadmodel->brush.data_pvsclusters = nobsp_pvs;
7807         //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7808         //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7809         loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7810         VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7811         VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7812         loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7813         loadmodel->brush.data_leafs->clusterindex = 0;
7814         loadmodel->brush.data_leafs->areaindex = 0;
7815         loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7816         loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7817         loadmodel->brush.data_leafs->numleafbrushes = 0;
7818         loadmodel->brush.data_leafs->firstleafbrush = NULL;
7819         loadmodel->brush.supportwateralpha = true;
7820
7821         if (loadmodel->brush.numsubmodels)
7822                 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7823
7824         mod = loadmodel;
7825         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7826         {
7827                 if (i > 0)
7828                 {
7829                         char name[10];
7830                         // duplicate the basic information
7831                         dpsnprintf(name, sizeof(name), "*%i", i);
7832                         mod = Mod_FindName(name, loadmodel->name);
7833                         // copy the base model to this one
7834                         *mod = *loadmodel;
7835                         // rename the clone back to its proper name
7836                         strlcpy(mod->name, name, sizeof(mod->name));
7837                         mod->brush.parentmodel = loadmodel;
7838                         // textures and memory belong to the main model
7839                         mod->texturepool = NULL;
7840                         mod->mempool = NULL;
7841                         mod->brush.GetPVS = NULL;
7842                         mod->brush.FatPVS = NULL;
7843                         mod->brush.BoxTouchingPVS = NULL;
7844                         mod->brush.BoxTouchingLeafPVS = NULL;
7845                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7846                         mod->brush.FindBoxClusters = NULL;
7847                         mod->brush.LightPoint = NULL;
7848                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7849                 }
7850                 mod->brush.submodel = i;
7851                 if (loadmodel->brush.submodels)
7852                         loadmodel->brush.submodels[i] = mod;
7853
7854                 // make the model surface list (used by shadowing/lighting)
7855                 mod->firstmodelsurface = submodelfirstsurface[i];
7856                 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7857                 mod->firstmodelbrush = 0;
7858                 mod->nummodelbrushes = 0;
7859                 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7860                 Mod_MakeSortedSurfaces(mod);
7861
7862                 VectorClear(mod->normalmins);
7863                 VectorClear(mod->normalmaxs);
7864                 l = false;
7865                 for (j = 0;j < mod->nummodelsurfaces;j++)
7866                 {
7867                         const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7868                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7869                         int k;
7870                         if (!surface->num_vertices)
7871                                 continue;
7872                         if (!l)
7873                         {
7874                                 l = true;
7875                                 VectorCopy(v, mod->normalmins);
7876                                 VectorCopy(v, mod->normalmaxs);
7877                         }
7878                         for (k = 0;k < surface->num_vertices;k++, v += 3)
7879                         {
7880                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7881                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7882                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7883                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7884                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7885                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7886                         }
7887                 }
7888                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7889                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7890                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7891                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7892                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7893                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7894                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7895                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7896                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7897                 mod->yawmins[2] = mod->normalmins[2];
7898                 mod->yawmaxs[2] = mod->normalmaxs[2];
7899                 mod->radius = modelradius;
7900                 mod->radius2 = modelradius * modelradius;
7901
7902                 // this gets altered below if sky or water is used
7903                 mod->DrawSky = NULL;
7904                 mod->DrawAddWaterPlanes = NULL;
7905
7906                 for (j = 0;j < mod->nummodelsurfaces;j++)
7907                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7908                                 break;
7909                 if (j < mod->nummodelsurfaces)
7910                         mod->DrawSky = R_Q1BSP_DrawSky;
7911
7912                 for (j = 0;j < mod->nummodelsurfaces;j++)
7913                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7914                                 break;
7915                 if (j < mod->nummodelsurfaces)
7916                         mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7917
7918                 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
7919                 mod->render_bih = mod->collision_bih;
7920
7921                 // generate VBOs and other shared data before cloning submodels
7922                 if (i == 0)
7923                         Mod_BuildVBOs();
7924         }
7925         mod = loadmodel;
7926         Mem_Free(submodelfirstsurface);
7927
7928         Con_DPrintf("Stats for obj model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
7929 }