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