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