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