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