]> git.xonotic.org Git - xonotic/darkplaces.git/blob - model_brush.c
cmd: Check for empty cbuf when inserting too
[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 = {CF_CLIENT | CF_ARCHIVE, "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 = {CF_CLIENT | CF_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 = {CF_CLIENT, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {CF_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 = {CF_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 = {CF_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 = {CF_CLIENT, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {CF_CLIENT, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {CF_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 = {CF_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 = {CF_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 = {CF_CLIENT, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {CF_CLIENT, "r_trippy", "0", "easter egg"};
42 cvar_t r_fxaa = {CF_CLIENT | CF_ARCHIVE, "r_fxaa", "0", "fast approximate anti aliasing"};
43 cvar_t mod_noshader_default_offsetmapping = {CF_CLIENT | CF_ARCHIVE, "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 = {CF_CLIENT | CF_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 = {CF_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 = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
47 cvar_t mod_q3bsp_curves_collisions_stride = {CF_CLIENT | CF_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 = {CF_CLIENT | CF_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 = {CF_CLIENT | CF_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 = {CF_CLIENT | CF_SERVER, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
51 cvar_t mod_q3bsp_lightmapmergepower = {CF_CLIENT | CF_ARCHIVE, "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 = {CF_CLIENT | CF_ARCHIVE, "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 = {CF_CLIENT | CF_SERVER, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
54 cvar_t mod_q3bsp_sRGBlightmaps = {CF_CLIENT, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
55 cvar_t mod_q3bsp_lightgrid_texture = {CF_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 = {CF_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 = {CF_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 = {CF_CLIENT | CF_ARCHIVE, "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 = {CF_CLIENT | CF_ARCHIVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
60 cvar_t mod_q3shader_default_offsetmapping_bias = {CF_CLIENT | CF_ARCHIVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
61 cvar_t mod_q3shader_default_polygonfactor = {CF_CLIENT, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
62 cvar_t mod_q3shader_default_polygonoffset = {CF_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 = {CF_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 = {CF_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 = {CF_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 = {CF_CLIENT | CF_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 = {CF_CLIENT | CF_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 qbool 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(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(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(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(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(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(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         model_t *model;
471 }
472 findnonsolidlocationinfo_t;
473
474 static void Mod_BSP_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_BSP_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_BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
576                         }
577                 }
578         }
579 }
580
581 static void Mod_BSP_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_BSP_FindNonSolidLocation_r(info, node->children[0]);
588                 if (f <= info->bestdist)
589                         Mod_BSP_FindNonSolidLocation_r(info, node->children[1]);
590         }
591         else
592         {
593                 if (((mleaf_t *)node)->numleafsurfaces)
594                         Mod_BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
595         }
596 }
597
598 static void Mod_BSP_FindNonSolidLocation(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_BSP_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 qbool 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_BSP_LightPoint_RecursiveBSPNode(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_BSP_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(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_BSP_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 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 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_BSP_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_BSP_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_BSP_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_BSP_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_BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2282 {
2283         mmodel_t        *out;
2284         int                     i, j, count;
2285         int                     structsize = hullinfo ? (48+4*hullinfo->filehulls) : 48;
2286
2287         if (sb->cursize % structsize)
2288                 Host_Error ("Mod_BSP_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                 if(hullinfo)
2309                 {
2310                         for (j = 0; j < hullinfo->filehulls; j++)
2311                                 out->headnode[j] = MSG_ReadLittleLong(sb);
2312                         out->visleafs  = MSG_ReadLittleLong(sb);
2313                 }
2314                 else // Quake 2 has only one hull
2315                         out->headnode[0] = MSG_ReadLittleLong(sb);
2316
2317                 out->firstface = MSG_ReadLittleLong(sb);
2318                 out->numfaces  = MSG_ReadLittleLong(sb);
2319         }
2320 }
2321
2322 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2323 {
2324         medge_t *out;
2325         int     i, count;
2326         int             structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2327
2328         if (sb->cursize % structsize)
2329                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2330         count = sb->cursize / structsize;
2331         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2332
2333         loadmodel->brushq1.edges = out;
2334         loadmodel->brushq1.numedges = count;
2335
2336         for ( i=0 ; i<count ; i++, out++)
2337         {
2338                 if (loadmodel->brush.isbsp2)
2339                 {
2340                         out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2341                         out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2342                 }
2343                 else
2344                 {
2345                         out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2346                         out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2347                 }
2348                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2349                 {
2350                         Con_Printf("Mod_Q1BSP_LoadEdges: %s has invalid vertex indices in edge %i (vertices %i %i >= numvertices %i)\n", loadmodel->name, i, out->v[0], out->v[1], loadmodel->brushq1.numvertexes);
2351                         if(!loadmodel->brushq1.numvertexes)
2352                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2353                                 
2354                         out->v[0] = 0;
2355                         out->v[1] = 0;
2356                 }
2357         }
2358 }
2359
2360 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2361 {
2362         mtexinfo_t *out;
2363         int i, j, k, count, miptex;
2364         int structsize = 40;
2365
2366         if (sb->cursize % structsize)
2367                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2368         count = sb->cursize / structsize;
2369         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2370
2371         loadmodel->brushq1.texinfo = out;
2372         loadmodel->brushq1.numtexinfo = count;
2373
2374         for (i = 0;i < count;i++, out++)
2375         {
2376                 for (k = 0;k < 2;k++)
2377                         for (j = 0;j < 4;j++)
2378                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2379
2380                 miptex = MSG_ReadLittleLong(sb);
2381                 out->q1flags = MSG_ReadLittleLong(sb);
2382
2383                 if (out->q1flags & TEX_SPECIAL)
2384                 {
2385                         // if texture chosen is NULL or the shader needs a lightmap,
2386                         // force to notexture water shader
2387                         out->textureindex = loadmodel->num_textures - 1;
2388                 }
2389                 else
2390                 {
2391                         // if texture chosen is NULL, force to notexture
2392                         out->textureindex = loadmodel->num_textures - 2;
2393                 }
2394                 // see if the specified miptex is valid and try to use it instead
2395                 if (loadmodel->data_textures)
2396                 {
2397                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2398                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2399                         else
2400                                 out->textureindex = miptex;
2401                 }
2402         }
2403 }
2404
2405 #if 0
2406 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2407 {
2408         int             i, j;
2409         float   *v;
2410
2411         mins[0] = mins[1] = mins[2] = 9999;
2412         maxs[0] = maxs[1] = maxs[2] = -9999;
2413         v = verts;
2414         for (i = 0;i < numverts;i++)
2415         {
2416                 for (j = 0;j < 3;j++, v++)
2417                 {
2418                         if (*v < mins[j])
2419                                 mins[j] = *v;
2420                         if (*v > maxs[j])
2421                                 maxs[j] = *v;
2422                 }
2423         }
2424 }
2425
2426 #define MAX_SUBDIVPOLYTRIANGLES 4096
2427 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2428
2429 static int subdivpolyverts, subdivpolytriangles;
2430 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2431 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2432
2433 static int subdivpolylookupvert(vec3_t v)
2434 {
2435         int i;
2436         for (i = 0;i < subdivpolyverts;i++)
2437                 if (subdivpolyvert[i][0] == v[0]
2438                  && subdivpolyvert[i][1] == v[1]
2439                  && subdivpolyvert[i][2] == v[2])
2440                         return i;
2441         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2442                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2443         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2444         return subdivpolyverts++;
2445 }
2446
2447 static void SubdividePolygon(int numverts, float *verts)
2448 {
2449         int             i, i1, i2, i3, f, b, c, p;
2450         vec3_t  mins, maxs, front[256], back[256];
2451         float   m, *pv, *cv, dist[256], frac;
2452
2453         if (numverts > 250)
2454                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2455
2456         BoundPoly(numverts, verts, mins, maxs);
2457
2458         for (i = 0;i < 3;i++)
2459         {
2460                 m = (mins[i] + maxs[i]) * 0.5;
2461                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2462                 if (maxs[i] - m < 8)
2463                         continue;
2464                 if (m - mins[i] < 8)
2465                         continue;
2466
2467                 // cut it
2468                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2469                         dist[c] = cv[i] - m;
2470
2471                 f = b = 0;
2472                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2473                 {
2474                         if (dist[p] >= 0)
2475                         {
2476                                 VectorCopy(pv, front[f]);
2477                                 f++;
2478                         }
2479                         if (dist[p] <= 0)
2480                         {
2481                                 VectorCopy(pv, back[b]);
2482                                 b++;
2483                         }
2484                         if (dist[p] == 0 || dist[c] == 0)
2485                                 continue;
2486                         if ((dist[p] > 0) != (dist[c] > 0) )
2487                         {
2488                                 // clip point
2489                                 frac = dist[p] / (dist[p] - dist[c]);
2490                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2491                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2492                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2493                                 f++;
2494                                 b++;
2495                         }
2496                 }
2497
2498                 SubdividePolygon(f, front[0]);
2499                 SubdividePolygon(b, back[0]);
2500                 return;
2501         }
2502
2503         i1 = subdivpolylookupvert(verts);
2504         i2 = subdivpolylookupvert(verts + 3);
2505         for (i = 2;i < numverts;i++)
2506         {
2507                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2508                 {
2509                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2510                         return;
2511                 }
2512
2513                 i3 = subdivpolylookupvert(verts + i * 3);
2514                 subdivpolyindex[subdivpolytriangles][0] = i1;
2515                 subdivpolyindex[subdivpolytriangles][1] = i2;
2516                 subdivpolyindex[subdivpolytriangles][2] = i3;
2517                 i2 = i3;
2518                 subdivpolytriangles++;
2519         }
2520 }
2521
2522 //Breaks a polygon up along axial 64 unit
2523 //boundaries so that turbulent and sky warps
2524 //can be done reasonably.
2525 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2526 {
2527         int i, j;
2528         surfvertex_t *v;
2529         surfmesh_t *mesh;
2530
2531         subdivpolytriangles = 0;
2532         subdivpolyverts = 0;
2533         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2534         if (subdivpolytriangles < 1)
2535                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2536
2537         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2538         mesh->num_vertices = subdivpolyverts;
2539         mesh->num_triangles = subdivpolytriangles;
2540         mesh->vertex = (surfvertex_t *)(mesh + 1);
2541         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2542         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2543
2544         for (i = 0;i < mesh->num_triangles;i++)
2545                 for (j = 0;j < 3;j++)
2546                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2547
2548         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2549         {
2550                 VectorCopy(subdivpolyvert[i], v->v);
2551                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2552                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2553         }
2554 }
2555 #endif
2556
2557 extern cvar_t gl_max_lightmapsize;
2558 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2559 {
2560         msurface_t *surface;
2561         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2562         float texmins[2], texmaxs[2], val;
2563         rtexture_t *lightmaptexture, *deluxemaptexture;
2564         char vabuf[1024];
2565         int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2566
2567         if (sb->cursize % structsize)
2568                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2569         count = sb->cursize / structsize;
2570         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2571         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2572
2573         loadmodel->num_surfaces = count;
2574
2575         loadmodel->brushq1.firstrender = true;
2576         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2577
2578         totalverts = 0;
2579         totaltris = 0;
2580         for (surfacenum = 0;surfacenum < count;surfacenum++)
2581         {
2582                 if (loadmodel->brush.isbsp2)
2583                         numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2584                 else
2585                         numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2586                 totalverts += numedges;
2587                 totaltris += numedges - 2;
2588         }
2589
2590         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
2591
2592         lightmaptexture = NULL;
2593         deluxemaptexture = r_texture_blanknormalmap;
2594         lightmapnumber = 0;
2595         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2596         totallightmapsamples = 0;
2597
2598         totalverts = 0;
2599         totaltris = 0;
2600         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2601         {
2602                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2603                 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2604                 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2605                 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2606                 firstedge = MSG_ReadLittleLong(sb);
2607                 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2608                 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2609                 for (i = 0;i < MAXLIGHTMAPS;i++)
2610                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2611                 lightmapoffset = MSG_ReadLittleLong(sb);
2612
2613                 // FIXME: validate edges, texinfo, etc?
2614                 if ((unsigned int) firstedge > (unsigned int) loadmodel->brushq1.numsurfedges || (unsigned int) numedges > (unsigned int) loadmodel->brushq1.numsurfedges || (unsigned int) firstedge + (unsigned int) numedges > (unsigned int) loadmodel->brushq1.numsurfedges)
2615                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2616                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2617                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2618                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2619                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2620
2621                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2622                 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2623
2624                 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2625                 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2626                         lightmapoffset = -1;
2627
2628                 //surface->flags = surface->texture->flags;
2629                 //if (LittleShort(in->side))
2630                 //      surface->flags |= SURF_PLANEBACK;
2631                 //surface->plane = loadmodel->brush.data_planes + planenum;
2632
2633                 surface->num_firstvertex = totalverts;
2634                 surface->num_vertices = numedges;
2635                 surface->num_firsttriangle = totaltris;
2636                 surface->num_triangles = numedges - 2;
2637                 totalverts += numedges;
2638                 totaltris += numedges - 2;
2639
2640                 // convert edges back to a normal polygon
2641                 for (i = 0;i < surface->num_vertices;i++)
2642                 {
2643                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2644                         float s, t;
2645                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2646                         if (lindex >= 0)
2647                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2648                         else
2649                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2650                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2651                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2652                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2653                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2654                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2655                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2656                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2657                 }
2658
2659                 for (i = 0;i < surface->num_triangles;i++)
2660                 {
2661                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2662                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2663                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2664                 }
2665
2666                 // compile additional data about the surface geometry
2667                 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
2668                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
2669                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2670
2671                 // generate surface extents information
2672                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2673                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2674                 for (i = 1;i < surface->num_vertices;i++)
2675                 {
2676                         for (j = 0;j < 2;j++)
2677                         {
2678                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2679                                 texmins[j] = min(texmins[j], val);
2680                                 texmaxs[j] = max(texmaxs[j], val);
2681                         }
2682                 }
2683                 for (i = 0;i < 2;i++)
2684                 {
2685                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2686                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2687                 }
2688
2689                 smax = surface->lightmapinfo->extents[0] >> 4;
2690                 tmax = surface->lightmapinfo->extents[1] >> 4;
2691                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2692                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2693
2694                 // lighting info
2695                 surface->lightmaptexture = NULL;
2696                 surface->deluxemaptexture = r_texture_blanknormalmap;
2697                 if (lightmapoffset == -1)
2698                 {
2699                         surface->lightmapinfo->samples = NULL;
2700 #if 1
2701                         // give non-lightmapped water a 1x white lightmap
2702                         if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2703                         {
2704                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2705                                 surface->lightmapinfo->styles[0] = 0;
2706                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2707                         }
2708 #endif
2709                 }
2710                 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LadyHavoc: HalfLife map (bsp version 30)
2711                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2712                 else // LadyHavoc: white lighting (bsp version 29)
2713                 {
2714                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2715                         if (loadmodel->brushq1.nmaplightdata)
2716                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2717                 }
2718
2719                 // check if we should apply a lightmap to this
2720                 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2721                 {
2722                         if (ssize > 256 || tsize > 256)
2723                                 Host_Error("Bad surface extents");
2724
2725                         if (lightmapsize < ssize)
2726                                 lightmapsize = ssize;
2727                         if (lightmapsize < tsize)
2728                                 lightmapsize = tsize;
2729
2730                         totallightmapsamples += ssize*tsize;
2731
2732                         // force lightmap upload on first time seeing the surface
2733                         //
2734                         // additionally this is used by the later code to see if a
2735                         // lightmap is needed on this surface (rather than duplicating the
2736                         // logic above)
2737                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2738                         loadmodel->lit = true;
2739                 }
2740         }
2741
2742         // small maps (such as ammo boxes especially) don't need big lightmap
2743         // textures, so this code tries to guess a good size based on
2744         // totallightmapsamples (size of the lightmaps lump basically), as well as
2745         // trying to max out the size if there is a lot of lightmap data to store
2746         // additionally, never choose a lightmapsize that is smaller than the
2747         // largest surface encountered (as it would fail)
2748         i = lightmapsize;
2749         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2750                 ;
2751
2752         // now that we've decided the lightmap texture size, we can do the rest
2753         if (cls.state != ca_dedicated)
2754         {
2755                 int stainmapsize = 0;
2756                 mod_alloclightmap_state_t allocState;
2757
2758                 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2759                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2760                 {
2761                         int iu, iv, lightmapx = 0, lightmapy = 0;
2762                         float u, v, ubase, vbase, uscale, vscale;
2763
2764                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2765                                 continue;
2766
2767                         smax = surface->lightmapinfo->extents[0] >> 4;
2768                         tmax = surface->lightmapinfo->extents[1] >> 4;
2769                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2770                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2771                         stainmapsize += ssize * tsize * 3;
2772
2773                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2774                         {
2775                                 // allocate a texture pool if we need it
2776                                 if (loadmodel->texturepool == NULL)
2777                                         loadmodel->texturepool = R_AllocTexturePool();
2778                                 // could not find room, make a new lightmap
2779                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2780                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2781                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2782                                 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2783                                 if (loadmodel->brushq1.nmaplightdata)
2784                                         loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2785                                 lightmapnumber++;
2786                                 Mod_AllocLightmap_Reset(&allocState);
2787                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2788                         }
2789                         surface->lightmaptexture = lightmaptexture;
2790                         surface->deluxemaptexture = deluxemaptexture;
2791                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2792                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2793
2794                         uscale = 1.0f / (float)lightmapsize;
2795                         vscale = 1.0f / (float)lightmapsize;
2796                         ubase = lightmapx * uscale;
2797                         vbase = lightmapy * vscale;
2798
2799                         for (i = 0;i < surface->num_vertices;i++)
2800                         {
2801                                 u = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3]) + 8 - surface->lightmapinfo->texturemins[0]) * (1.0 / 16.0);
2802                                 v = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3]) + 8 - surface->lightmapinfo->texturemins[1]) * (1.0 / 16.0);
2803                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2804                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2805                                 // LadyHavoc: calc lightmap data offset for vertex lighting to use
2806                                 iu = (int) u;
2807                                 iv = (int) v;
2808                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2809                         }
2810                 }
2811
2812                 if (cl_stainmaps.integer)
2813                 {
2814                         // allocate stainmaps for permanent marks on walls and clear white
2815                         unsigned char *stainsamples = NULL;
2816                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2817                         memset(stainsamples, 255, stainmapsize);
2818                         // assign pointers
2819                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2820                         {
2821                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2822                                         continue;
2823                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2824                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2825                                 surface->lightmapinfo->stainsamples = stainsamples;
2826                                 stainsamples += ssize * tsize * 3;
2827                         }
2828                 }
2829         }
2830
2831         // generate ushort elements array if possible
2832         if (loadmodel->surfmesh.data_element3s)
2833                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2834                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2835 }
2836
2837 static void Mod_BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2838 {
2839         //if (node->parent)
2840         //      Host_Error("Mod_BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2841         node->parent = parent;
2842         if (node->plane)
2843         {
2844                 // this is a node, recurse to children
2845                 Mod_BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2846                 Mod_BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2847                 // combine supercontents of children
2848                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2849         }
2850         else
2851         {
2852                 int j;
2853                 mleaf_t *leaf = (mleaf_t *)node;
2854                 // if this is a leaf, calculate supercontents mask from all collidable
2855                 // primitives in the leaf (brushes and collision surfaces)
2856                 // also flag if the leaf contains any collision surfaces
2857                 leaf->combinedsupercontents = 0;
2858                 // combine the supercontents values of all brushes in this leaf
2859                 for (j = 0;j < leaf->numleafbrushes;j++)
2860                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2861                 // check if this leaf contains any collision surfaces (q3 patches)
2862                 for (j = 0;j < leaf->numleafsurfaces;j++)
2863                 {
2864                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2865                         if (surface->num_collisiontriangles)
2866                         {
2867                                 leaf->containscollisionsurfaces = true;
2868                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2869                         }
2870                 }
2871         }
2872 }
2873
2874 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2875 {
2876         int                     i, j, count, p, child[2];
2877         mnode_t         *out;
2878         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2879
2880         if (sb->cursize % structsize)
2881                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2882         count = sb->cursize / structsize;
2883         if (count == 0)
2884                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2885         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2886
2887         loadmodel->brush.data_nodes = out;
2888         loadmodel->brush.num_nodes = count;
2889
2890         for ( i=0 ; i<count ; i++, out++)
2891         {
2892                 p = MSG_ReadLittleLong(sb);
2893                 out->plane = loadmodel->brush.data_planes + p;
2894
2895                 if (loadmodel->brush.isbsp2rmqe)
2896                 {
2897                         child[0] = MSG_ReadLittleLong(sb);
2898                         child[1] = MSG_ReadLittleLong(sb);
2899                         out->mins[0] = MSG_ReadLittleShort(sb);
2900                         out->mins[1] = MSG_ReadLittleShort(sb);
2901                         out->mins[2] = MSG_ReadLittleShort(sb);
2902                         out->maxs[0] = MSG_ReadLittleShort(sb);
2903                         out->maxs[1] = MSG_ReadLittleShort(sb);
2904                         out->maxs[2] = MSG_ReadLittleShort(sb);
2905                         out->firstsurface = MSG_ReadLittleLong(sb);
2906                         out->numsurfaces = MSG_ReadLittleLong(sb);
2907                 }
2908                 else if (loadmodel->brush.isbsp2)
2909                 {
2910                         child[0] = MSG_ReadLittleLong(sb);
2911                         child[1] = MSG_ReadLittleLong(sb);
2912                         out->mins[0] = MSG_ReadLittleFloat(sb);
2913                         out->mins[1] = MSG_ReadLittleFloat(sb);
2914                         out->mins[2] = MSG_ReadLittleFloat(sb);
2915                         out->maxs[0] = MSG_ReadLittleFloat(sb);
2916                         out->maxs[1] = MSG_ReadLittleFloat(sb);
2917                         out->maxs[2] = MSG_ReadLittleFloat(sb);
2918                         out->firstsurface = MSG_ReadLittleLong(sb);
2919                         out->numsurfaces = MSG_ReadLittleLong(sb);
2920                 }
2921                 else
2922                 {
2923                         child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2924                         child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2925                         if (child[0] >= count)
2926                                 child[0] -= 65536;
2927                         if (child[1] >= count)
2928                                 child[1] -= 65536;
2929
2930                         out->mins[0] = MSG_ReadLittleShort(sb);
2931                         out->mins[1] = MSG_ReadLittleShort(sb);
2932                         out->mins[2] = MSG_ReadLittleShort(sb);
2933                         out->maxs[0] = MSG_ReadLittleShort(sb);
2934                         out->maxs[1] = MSG_ReadLittleShort(sb);
2935                         out->maxs[2] = MSG_ReadLittleShort(sb);
2936
2937                         out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2938                         out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2939                 }
2940
2941                 for (j=0 ; j<2 ; j++)
2942                 {
2943                         // LadyHavoc: this code supports broken bsp files produced by
2944                         // arguire qbsp which can produce more than 32768 nodes, any value
2945                         // below count is assumed to be a node number, any other value is
2946                         // assumed to be a leaf number
2947                         p = child[j];
2948                         if (p >= 0)
2949                         {
2950                                 if (p < loadmodel->brush.num_nodes)
2951                                         out->children[j] = loadmodel->brush.data_nodes + p;
2952                                 else
2953                                 {
2954                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2955                                         // map it to the solid leaf
2956                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2957                                 }
2958                         }
2959                         else
2960                         {
2961                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2962                                 p = -(p+1);
2963                                 if (p < loadmodel->brush.num_leafs)
2964                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2965                                 else
2966                                 {
2967                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2968                                         // map it to the solid leaf
2969                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2970                                 }
2971                         }
2972                 }
2973         }
2974
2975         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);        // sets nodes and leafs
2976 }
2977
2978 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2979 {
2980         mleaf_t *out;
2981         int i, j, count, p, firstmarksurface, nummarksurfaces;
2982         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2983
2984         if (sb->cursize % structsize)
2985                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2986         count = sb->cursize / structsize;
2987         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2988
2989         loadmodel->brush.data_leafs = out;
2990         loadmodel->brush.num_leafs = count;
2991         // get visleafs from the submodel data
2992         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2993         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2994         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2995         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2996
2997         // FIXME: this function could really benefit from some error checking
2998         for ( i=0 ; i<count ; i++, out++)
2999         {
3000                 out->contents = MSG_ReadLittleLong(sb);
3001
3002                 out->clusterindex = i - 1;
3003                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
3004                         out->clusterindex = -1;
3005
3006                 p = MSG_ReadLittleLong(sb);
3007                 // ignore visofs errors on leaf 0 (solid)
3008                 if (p >= 0 && out->clusterindex >= 0)
3009                 {
3010                         if (p >= loadmodel->brushq1.num_compressedpvs)
3011                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
3012                         else
3013                                 Mod_BSP_DecompressVis(loadmodel->brushq1.data_compressedpvs + p, loadmodel->brushq1.data_compressedpvs + loadmodel->brushq1.num_compressedpvs, loadmodel->brush.data_pvsclusters + out->clusterindex * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (out->clusterindex + 1) * loadmodel->brush.num_pvsclusterbytes);
3014                 }
3015
3016                 if (loadmodel->brush.isbsp2rmqe)
3017                 {
3018                         out->mins[0] = MSG_ReadLittleShort(sb);
3019                         out->mins[1] = MSG_ReadLittleShort(sb);
3020                         out->mins[2] = MSG_ReadLittleShort(sb);
3021                         out->maxs[0] = MSG_ReadLittleShort(sb);
3022                         out->maxs[1] = MSG_ReadLittleShort(sb);
3023                         out->maxs[2] = MSG_ReadLittleShort(sb);
3024         
3025                         firstmarksurface = MSG_ReadLittleLong(sb);
3026                         nummarksurfaces = MSG_ReadLittleLong(sb);
3027                 }
3028                 else if (loadmodel->brush.isbsp2)
3029                 {
3030                         out->mins[0] = MSG_ReadLittleFloat(sb);
3031                         out->mins[1] = MSG_ReadLittleFloat(sb);
3032                         out->mins[2] = MSG_ReadLittleFloat(sb);
3033                         out->maxs[0] = MSG_ReadLittleFloat(sb);
3034                         out->maxs[1] = MSG_ReadLittleFloat(sb);
3035                         out->maxs[2] = MSG_ReadLittleFloat(sb);
3036         
3037                         firstmarksurface = MSG_ReadLittleLong(sb);
3038                         nummarksurfaces = MSG_ReadLittleLong(sb);
3039                 }
3040                 else
3041                 {
3042                         out->mins[0] = MSG_ReadLittleShort(sb);
3043                         out->mins[1] = MSG_ReadLittleShort(sb);
3044                         out->mins[2] = MSG_ReadLittleShort(sb);
3045                         out->maxs[0] = MSG_ReadLittleShort(sb);
3046                         out->maxs[1] = MSG_ReadLittleShort(sb);
3047                         out->maxs[2] = MSG_ReadLittleShort(sb);
3048         
3049                         firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
3050                         nummarksurfaces  = (unsigned short)MSG_ReadLittleShort(sb);
3051                 }
3052
3053                 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
3054                 {
3055                         out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3056                         out->numleafsurfaces = nummarksurfaces;
3057                 }
3058                 else
3059                 {
3060                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3061                         out->firstleafsurface = NULL;
3062                         out->numleafsurfaces = 0;
3063                 }
3064
3065                 for (j = 0;j < 4;j++)
3066                         out->ambient_sound_level[j] = MSG_ReadByte(sb);
3067         }
3068 }
3069
3070 static qbool Mod_Q1BSP_CheckWaterAlphaSupport(void)
3071 {
3072         int i, j;
3073         mleaf_t *leaf;
3074         const unsigned char *pvs;
3075         // if there's no vis data, assume supported (because everything is visible all the time)
3076         if (!loadmodel->brush.data_pvsclusters)
3077                 return true;
3078         // check all liquid leafs to see if they can see into empty leafs, if any
3079         // can we can assume this map supports r_wateralpha
3080         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3081         {
3082                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3083                 {
3084                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3085                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
3086                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3087                                         return true;
3088                 }
3089         }
3090         return false;
3091 }
3092
3093 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3094 {
3095         mclipnode_t *out;
3096         int                     i, count;
3097         hull_t          *hull;
3098         int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3099
3100         if (sb->cursize % structsize)
3101                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3102         count = sb->cursize / structsize;
3103         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3104
3105         loadmodel->brushq1.clipnodes = out;
3106         loadmodel->brushq1.numclipnodes = count;
3107
3108         for (i = 1; i < MAX_MAP_HULLS; i++)
3109         {
3110                 hull = &loadmodel->brushq1.hulls[i];
3111                 hull->clipnodes = out;
3112                 hull->firstclipnode = 0;
3113                 hull->lastclipnode = count-1;
3114                 hull->planes = loadmodel->brush.data_planes;
3115                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3116                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3117                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3118                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3119                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3120                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3121                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3122         }
3123
3124         for (i=0 ; i<count ; i++, out++)
3125         {
3126                 out->planenum = MSG_ReadLittleLong(sb);
3127                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3128                         Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3129                 if (loadmodel->brush.isbsp2)
3130                 {
3131                         out->children[0] = MSG_ReadLittleLong(sb);
3132                         out->children[1] = MSG_ReadLittleLong(sb);
3133                         if (out->children[0] >= count)
3134                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3135                         if (out->children[1] >= count)
3136                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3137                 }
3138                 else
3139                 {
3140                         // LadyHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3141                         out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3142                         out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3143                         if (out->children[0] >= count)
3144                                 out->children[0] -= 65536;
3145                         if (out->children[1] >= count)
3146                                 out->children[1] -= 65536;
3147                 }
3148         }
3149 }
3150
3151 //Duplicate the drawing hull structure as a clipping hull
3152 static void Mod_Q1BSP_MakeHull0(void)
3153 {
3154         mnode_t         *in;
3155         mclipnode_t *out;
3156         int                     i;
3157         hull_t          *hull;
3158
3159         hull = &loadmodel->brushq1.hulls[0];
3160
3161         in = loadmodel->brush.data_nodes;
3162         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3163
3164         hull->clipnodes = out;
3165         hull->firstclipnode = 0;
3166         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3167         hull->planes = loadmodel->brush.data_planes;
3168
3169         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3170         {
3171                 out->planenum = in->plane - loadmodel->brush.data_planes;
3172                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3173                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3174         }
3175 }
3176
3177 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3178 {
3179         int i, j;
3180         int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3181
3182         if (sb->cursize % structsize)
3183                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3184         loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3185         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3186
3187         if (loadmodel->brush.isbsp2)
3188         {
3189                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3190                 {
3191                         j = MSG_ReadLittleLong(sb);
3192                         if (j < 0 || j >= loadmodel->num_surfaces)
3193                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3194                         loadmodel->brush.data_leafsurfaces[i] = j;
3195                 }
3196         }
3197         else
3198         {
3199                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3200                 {
3201                         j = (unsigned short) MSG_ReadLittleShort(sb);
3202                         if (j >= loadmodel->num_surfaces)
3203                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3204                         loadmodel->brush.data_leafsurfaces[i] = j;
3205                 }
3206         }
3207 }
3208
3209 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3210 {
3211         int             i;
3212         int structsize = 4;
3213
3214         if (sb->cursize % structsize)
3215                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3216         loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3217         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3218
3219         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3220                 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3221 }
3222
3223
3224 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3225 {
3226         int                     i;
3227         mplane_t        *out;
3228         int structsize = 20;
3229
3230         if (sb->cursize % structsize)
3231                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3232         loadmodel->brush.num_planes = sb->cursize / structsize;
3233         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3234
3235         for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3236         {
3237                 out->normal[0] = MSG_ReadLittleFloat(sb);
3238                 out->normal[1] = MSG_ReadLittleFloat(sb);
3239                 out->normal[2] = MSG_ReadLittleFloat(sb);
3240                 out->dist = MSG_ReadLittleFloat(sb);
3241                 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3242                 PlaneClassify(out);
3243         }
3244 }
3245
3246 // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
3247 static void Mod_Q1BSP_AssignNoShadowSkySurfaces(model_t *mod)
3248 {
3249         int surfaceindex;
3250         msurface_t *surface;
3251         vec3_t center;
3252         int contents;
3253         for (surfaceindex = mod->submodelsurfaces_start; surfaceindex < mod->submodelsurfaces_end;surfaceindex++)
3254         {
3255                 surface = mod->data_surfaces + surfaceindex;
3256                 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3257                 {
3258                         // check if the point behind the surface polygon is SOLID or SKY contents
3259                         VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
3260                         contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
3261                         if (!(contents & SUPERCONTENTS_SOLID))
3262                                 surface->texture = surface->texture->skynoshadowtexture;
3263                 }
3264         }
3265 }
3266
3267 static void Mod_Q1BSP_LoadMapBrushes(void)
3268 {
3269 #if 0
3270 // unfinished
3271         int submodel, numbrushes;
3272         qbool firstbrush;
3273         char *text, *maptext;
3274         char mapfilename[MAX_QPATH];
3275         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3276         strlcat (mapfilename, ".map", sizeof (mapfilename));
3277         maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3278         if (!maptext)
3279                 return;
3280         text = maptext;
3281         if (!COM_ParseToken_Simple(&data, false, false, true))
3282                 return; // error
3283         submodel = 0;
3284         for (;;)
3285         {
3286                 if (!COM_ParseToken_Simple(&data, false, false, true))
3287                         break;
3288                 if (com_token[0] != '{')
3289                         return; // error
3290                 // entity
3291                 firstbrush = true;
3292                 numbrushes = 0;
3293                 maxbrushes = 256;
3294                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3295                 for (;;)
3296                 {
3297                         if (!COM_ParseToken_Simple(&data, false, false, true))
3298                                 return; // error
3299                         if (com_token[0] == '}')
3300                                 break; // end of entity
3301                         if (com_token[0] == '{')
3302                         {
3303                                 // brush
3304                                 if (firstbrush)
3305                                 {
3306                                         if (submodel)
3307                                         {
3308                                                 if (submodel > loadmodel->brush.numsubmodels)
3309                                                 {
3310                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3311                                                         model = NULL;
3312                                                 }
3313                                                 else
3314                                                         model = loadmodel->brush.submodels[submodel];
3315                                         }
3316                                         else
3317                                                 model = loadmodel;
3318                                 }
3319                                 for (;;)
3320                                 {
3321                                         if (!COM_ParseToken_Simple(&data, false, false, true))
3322                                                 return; // error
3323                                         if (com_token[0] == '}')
3324                                                 break; // end of brush
3325                                         // each brush face should be this format:
3326                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3327                                         // FIXME: support hl .map format
3328                                         for (pointnum = 0;pointnum < 3;pointnum++)
3329                                         {
3330                                                 COM_ParseToken_Simple(&data, false, false, true);
3331                                                 for (componentnum = 0;componentnum < 3;componentnum++)
3332                                                 {
3333                                                         COM_ParseToken_Simple(&data, false, false, true);
3334                                                         point[pointnum][componentnum] = atof(com_token);
3335                                                 }
3336                                                 COM_ParseToken_Simple(&data, false, false, true);
3337                                         }
3338                                         COM_ParseToken_Simple(&data, false, false, true);
3339                                         strlcpy(facetexture, com_token, sizeof(facetexture));
3340                                         COM_ParseToken_Simple(&data, false, false, true);
3341                                         //scroll_s = atof(com_token);
3342                                         COM_ParseToken_Simple(&data, false, false, true);
3343                                         //scroll_t = atof(com_token);
3344                                         COM_ParseToken_Simple(&data, false, false, true);
3345                                         //rotate = atof(com_token);
3346                                         COM_ParseToken_Simple(&data, false, false, true);
3347                                         //scale_s = atof(com_token);
3348                                         COM_ParseToken_Simple(&data, false, false, true);
3349                                         //scale_t = atof(com_token);
3350                                         TriangleNormal(point[0], point[1], point[2], planenormal);
3351                                         VectorNormalizeDouble(planenormal);
3352                                         planedist = DotProduct(point[0], planenormal);
3353                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3354                                 }
3355                                 continue;
3356                         }
3357                 }
3358         }
3359 #endif
3360 }
3361
3362
3363 #define MAX_PORTALPOINTS 64
3364
3365 typedef struct portal_s
3366 {
3367         mplane_t plane;
3368         mnode_t *nodes[2];              // [0] = front side of plane
3369         struct portal_s *next[2];
3370         int numpoints;
3371         double points[3*MAX_PORTALPOINTS];
3372         struct portal_s *chain; // all portals are linked into a list
3373 }
3374 portal_t;
3375
3376 static memexpandablearray_t portalarray;
3377
3378 static void Mod_BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3379 {
3380         // process only nodes (leafs already had their box calculated)
3381         if (!node->plane)
3382                 return;
3383
3384         // calculate children first
3385         Mod_BSP_RecursiveRecalcNodeBBox(node->children[0]);
3386         Mod_BSP_RecursiveRecalcNodeBBox(node->children[1]);
3387
3388         // make combined bounding box from children
3389         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3390         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3391         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3392         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3393         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3394         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3395 }
3396
3397 static void Mod_BSP_FinalizePortals(void)
3398 {
3399         int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3400         portal_t *p;
3401         mportal_t *portal;
3402         mvertex_t *point;
3403         mleaf_t *leaf, *endleaf;
3404
3405         // tally up portal and point counts and recalculate bounding boxes for all
3406         // leafs (because qbsp is very sloppy)
3407         leaf = loadmodel->brush.data_leafs;
3408         endleaf = leaf + loadmodel->brush.num_leafs;
3409         if (mod_recalculatenodeboxes.integer)
3410         {
3411                 for (;leaf < endleaf;leaf++)
3412                 {
3413                         VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
3414                         VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3415                 }
3416         }
3417         numportals = 0;
3418         numpoints = 0;
3419         for (portalindex = 0;portalindex < portalrange;portalindex++)
3420         {
3421                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3422                 if (!p)
3423                         continue;
3424                 // note: this check must match the one below or it will usually corrupt memory
3425                 // 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
3426                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3427                 {
3428                         numportals += 2;
3429                         numpoints += p->numpoints * 2;
3430                 }
3431         }
3432         loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3433         loadmodel->brush.num_portals = numportals;
3434         loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3435         loadmodel->brush.num_portalpoints = numpoints;
3436         // clear all leaf portal chains
3437         for (i = 0;i < loadmodel->brush.num_leafs;i++)
3438                 loadmodel->brush.data_leafs[i].portals = NULL;
3439         // process all portals in the global portal chain, while freeing them
3440         portal = loadmodel->brush.data_portals;
3441         point = loadmodel->brush.data_portalpoints;
3442         for (portalindex = 0;portalindex < portalrange;portalindex++)
3443         {
3444                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3445                 if (!p)
3446                         continue;
3447                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3448                 {
3449                         // note: this check must match the one above or it will usually corrupt memory
3450                         // 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
3451                         if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3452                         {
3453                                 // first make the back to front portal(forward portal)
3454                                 portal->points = point;
3455                                 portal->numpoints = p->numpoints;
3456                                 portal->plane.dist = p->plane.dist;
3457                                 VectorCopy(p->plane.normal, portal->plane.normal);
3458                                 portal->here = (mleaf_t *)p->nodes[1];
3459                                 portal->past = (mleaf_t *)p->nodes[0];
3460                                 // copy points
3461                                 for (j = 0;j < portal->numpoints;j++)
3462                                 {
3463                                         VectorCopy(p->points + j*3, point->position);
3464                                         point++;
3465                                 }
3466                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3467                                 PlaneClassify(&portal->plane);
3468
3469                                 // link into leaf's portal chain
3470                                 portal->next = portal->here->portals;
3471                                 portal->here->portals = portal;
3472
3473                                 // advance to next portal
3474                                 portal++;
3475
3476                                 // then make the front to back portal(backward portal)
3477                                 portal->points = point;
3478                                 portal->numpoints = p->numpoints;
3479                                 portal->plane.dist = -p->plane.dist;
3480                                 VectorNegate(p->plane.normal, portal->plane.normal);
3481                                 portal->here = (mleaf_t *)p->nodes[0];
3482                                 portal->past = (mleaf_t *)p->nodes[1];
3483                                 // copy points
3484                                 for (j = portal->numpoints - 1;j >= 0;j--)
3485                                 {
3486                                         VectorCopy(p->points + j*3, point->position);
3487                                         point++;
3488                                 }
3489                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3490                                 PlaneClassify(&portal->plane);
3491
3492                                 // link into leaf's portal chain
3493                                 portal->next = portal->here->portals;
3494                                 portal->here->portals = portal;
3495
3496                                 // advance to next portal
3497                                 portal++;
3498                         }
3499                         // add the portal's polygon points to the leaf bounding boxes
3500                         if (mod_recalculatenodeboxes.integer)
3501                         {
3502                                 for (i = 0;i < 2;i++)
3503                                 {
3504                                         leaf = (mleaf_t *)p->nodes[i];
3505                                         for (j = 0;j < p->numpoints;j++)
3506                                         {
3507                                                 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3508                                                 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3509                                                 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3510                                                 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3511                                                 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3512                                                 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3513                                         }
3514                                 }
3515                         }
3516                 }
3517         }
3518         // now recalculate the node bounding boxes from the leafs
3519         if (mod_recalculatenodeboxes.integer)
3520                 Mod_BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3521 }
3522
3523 /*
3524 =============
3525 AddPortalToNodes
3526 =============
3527 */
3528 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3529 {
3530         if (!front)
3531                 Host_Error("AddPortalToNodes: NULL front node");
3532         if (!back)
3533                 Host_Error("AddPortalToNodes: NULL back node");
3534         if (p->nodes[0] || p->nodes[1])
3535                 Host_Error("AddPortalToNodes: already included");
3536         // 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
3537
3538         p->nodes[0] = front;
3539         p->next[0] = (portal_t *)front->portals;
3540         front->portals = (mportal_t *)p;
3541
3542         p->nodes[1] = back;
3543         p->next[1] = (portal_t *)back->portals;
3544         back->portals = (mportal_t *)p;
3545 }
3546
3547 /*
3548 =============
3549 RemovePortalFromNode
3550 =============
3551 */
3552 static void RemovePortalFromNodes(portal_t *portal)
3553 {
3554         int i;
3555         mnode_t *node;
3556         void **portalpointer;
3557         portal_t *t;
3558         for (i = 0;i < 2;i++)
3559         {
3560                 node = portal->nodes[i];
3561
3562                 portalpointer = (void **) &node->portals;
3563                 while (1)
3564                 {
3565                         t = (portal_t *)*portalpointer;
3566                         if (!t)
3567                                 Host_Error("RemovePortalFromNodes: portal not in leaf");
3568
3569                         if (t == portal)
3570                         {
3571                                 if (portal->nodes[0] == node)
3572                                 {
3573                                         *portalpointer = portal->next[0];
3574                                         portal->nodes[0] = NULL;
3575                                 }
3576                                 else if (portal->nodes[1] == node)
3577                                 {
3578                                         *portalpointer = portal->next[1];
3579                                         portal->nodes[1] = NULL;
3580                                 }
3581                                 else
3582                                         Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3583                                 break;
3584                         }
3585
3586                         if (t->nodes[0] == node)
3587                                 portalpointer = (void **) &t->next[0];
3588                         else if (t->nodes[1] == node)
3589                                 portalpointer = (void **) &t->next[1];
3590                         else
3591                                 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3592                 }
3593         }
3594 }
3595
3596 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3597 static double *portalpointsbuffer;
3598 static int portalpointsbufferoffset;
3599 static int portalpointsbuffersize;
3600 static void Mod_BSP_RecursiveNodePortals(mnode_t *node)
3601 {
3602         int i, side;
3603         mnode_t *front, *back, *other_node;
3604         mplane_t clipplane, *plane;
3605         portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3606         int numfrontpoints, numbackpoints;
3607         double *frontpoints, *backpoints;
3608
3609         // if a leaf, we're done
3610         if (!node->plane)
3611                 return;
3612
3613         // get some space for our clipping operations to use
3614         if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3615         {
3616                 portalpointsbuffersize = portalpointsbufferoffset * 2;
3617                 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3618         }
3619         frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3620         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3621         backpoints = portalpointsbuffer + portalpointsbufferoffset;
3622         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3623
3624         plane = node->plane;
3625
3626         front = node->children[0];
3627         back = node->children[1];
3628         if (front == back)
3629                 Host_Error("Mod_BSP_RecursiveNodePortals: corrupt node hierarchy");
3630
3631         // create the new portal by generating a polygon for the node plane,
3632         // and clipping it by all of the other portals(which came from nodes above this one)
3633         nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3634         nodeportal->plane = *plane;
3635
3636         // 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)
3637         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);
3638         nodeportal->numpoints = 4;
3639
3640         for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3641         {
3642                 clipplane = portal->plane;
3643                 if (portal->nodes[0] == portal->nodes[1])
3644                         Host_Error("Mod_BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3645                 if (portal->nodes[0] == node)
3646                         side = 0;
3647                 else if (portal->nodes[1] == node)
3648                 {
3649                         clipplane.dist = -clipplane.dist;
3650                         VectorNegate(clipplane.normal, clipplane.normal);
3651                         side = 1;
3652                 }
3653                 else
3654                 {
3655                         Host_Error("Mod_BSP_RecursiveNodePortals: mislinked portal");
3656                         side = 0; // hush warning
3657                 }
3658
3659                 for (i = 0;i < nodeportal->numpoints*3;i++)
3660                         frontpoints[i] = nodeportal->points[i];
3661                 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);
3662                 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3663                         break;
3664         }
3665
3666         if (nodeportal->numpoints < 3)
3667         {
3668                 Con_Print(CON_WARN "Mod_BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3669                 nodeportal->numpoints = 0;
3670         }
3671         else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3672         {
3673                 Con_Print(CON_WARN "Mod_BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3674                 nodeportal->numpoints = 0;
3675         }
3676
3677         AddPortalToNodes(nodeportal, front, back);
3678
3679         // split the portals of this node along this node's plane and assign them to the children of this node
3680         // (migrating the portals downward through the tree)
3681         for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3682         {
3683                 if (portal->nodes[0] == portal->nodes[1])
3684                         Host_Error("Mod_BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3685                 if (portal->nodes[0] == node)
3686                         side = 0;
3687                 else if (portal->nodes[1] == node)
3688                         side = 1;
3689                 else
3690                 {
3691                         Host_Error("Mod_BSP_RecursiveNodePortals: mislinked portal");
3692                         side = 0; // hush warning
3693                 }
3694                 nextportal = portal->next[side];
3695                 if (!portal->numpoints)
3696                         continue;
3697
3698                 other_node = portal->nodes[!side];
3699                 RemovePortalFromNodes(portal);
3700
3701                 // cut the portal into two portals, one on each side of the node plane
3702                 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);
3703
3704                 if (!numfrontpoints)
3705                 {
3706                         if (side == 0)
3707                                 AddPortalToNodes(portal, back, other_node);
3708                         else
3709                                 AddPortalToNodes(portal, other_node, back);
3710                         continue;
3711                 }
3712                 if (!numbackpoints)
3713                 {
3714                         if (side == 0)
3715                                 AddPortalToNodes(portal, front, other_node);
3716                         else
3717                                 AddPortalToNodes(portal, other_node, front);
3718                         continue;
3719                 }
3720
3721                 // the portal is split
3722                 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3723                 temp = splitportal->chain;
3724                 *splitportal = *portal;
3725                 splitportal->chain = temp;
3726                 for (i = 0;i < numbackpoints*3;i++)
3727                         splitportal->points[i] = backpoints[i];
3728                 splitportal->numpoints = numbackpoints;
3729                 for (i = 0;i < numfrontpoints*3;i++)
3730                         portal->points[i] = frontpoints[i];
3731                 portal->numpoints = numfrontpoints;
3732
3733                 if (side == 0)
3734                 {
3735                         AddPortalToNodes(portal, front, other_node);
3736                         AddPortalToNodes(splitportal, back, other_node);
3737                 }
3738                 else
3739                 {
3740                         AddPortalToNodes(portal, other_node, front);
3741                         AddPortalToNodes(splitportal, other_node, back);
3742                 }
3743         }
3744
3745         Mod_BSP_RecursiveNodePortals(front);
3746         Mod_BSP_RecursiveNodePortals(back);
3747
3748         portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3749 }
3750
3751 static void Mod_BSP_MakePortals(void)
3752 {
3753         Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3754         portalpointsbufferoffset = 0;
3755         portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3756         portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3757         Mod_BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3758         Mem_Free(portalpointsbuffer);
3759         portalpointsbuffer = NULL;
3760         portalpointsbufferoffset = 0;
3761         portalpointsbuffersize = 0;
3762         Mod_BSP_FinalizePortals();
3763         Mem_ExpandableArray_FreeArray(&portalarray);
3764 }
3765
3766 //Returns PVS data for a given point
3767 //(note: can return NULL)
3768 static unsigned char *Mod_BSP_GetPVS(model_t *model, const vec3_t p)
3769 {
3770         mnode_t *node;
3771         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3772         while (node->plane)
3773                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3774         if (((mleaf_t *)node)->clusterindex >= 0)
3775                 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3776         else
3777                 return NULL;
3778 }
3779
3780 static void Mod_BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
3781 {
3782         while (node->plane)
3783         {
3784                 float d = PlaneDiff(org, node->plane);
3785                 if (d > radius)
3786                         node = node->children[0];
3787                 else if (d < -radius)
3788                         node = node->children[1];
3789                 else
3790                 {
3791                         // go down both sides
3792                         Mod_BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3793                         node = node->children[1];
3794                 }
3795         }
3796         // if this leaf is in a cluster, accumulate the pvs bits
3797         if (((mleaf_t *)node)->clusterindex >= 0)
3798         {
3799                 int i;
3800                 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3801                 for (i = 0;i < pvsbytes;i++)
3802                         pvsbuffer[i] |= pvs[i];
3803         }
3804 }
3805
3806 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3807 //of the given point.
3808 static int Mod_BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qbool merge)
3809 {
3810         int bytes = model->brush.num_pvsclusterbytes;
3811         bytes = min(bytes, pvsbufferlength);
3812         if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_BSP_GetPVS(model, org))
3813         {
3814                 memset(pvsbuffer, 0xFF, bytes);
3815                 return bytes;
3816         }
3817         if (!merge)
3818                 memset(pvsbuffer, 0, bytes);
3819         Mod_BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3820         return bytes;
3821 }
3822
3823 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3824 {
3825         vec3_t size;
3826         const hull_t *hull;
3827
3828         VectorSubtract(inmaxs, inmins, size);
3829         if (cmodel->brush.ishlbsp)
3830         {
3831                 if (size[0] < 3)
3832                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3833                 else if (size[0] <= 32)
3834                 {
3835                         if (size[2] < 54) // pick the nearest of 36 or 72
3836                                 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3837                         else
3838                                 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3839                 }
3840                 else
3841                         hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3842         }
3843         else
3844         {
3845                 if (size[0] < 3)
3846                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3847                 else if (size[0] <= 32)
3848                         hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3849                 else
3850                         hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3851         }
3852         VectorCopy(inmins, outmins);
3853         VectorAdd(inmins, hull->clip_size, outmaxs);
3854 }
3855
3856 void Mod_CollisionBIH_TraceLineAgainstSurfaces(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);
3857
3858 void Mod_2PSB_Load(model_t *mod, void *buffer, void *bufferend)
3859 {
3860         mod->brush.isbsp2 = true;
3861         mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3862         mod->modeldatatypestring = "Q1BSP2rmqe";
3863         Mod_Q1BSP_Load(mod, buffer, bufferend);
3864 }
3865
3866 void Mod_BSP2_Load(model_t *mod, void *buffer, void *bufferend)
3867 {
3868         mod->brush.isbsp2 = true;
3869         mod->modeldatatypestring = "Q1BSP2";
3870         Mod_Q1BSP_Load(mod, buffer, bufferend);
3871 }
3872
3873 void Mod_HLBSP_Load(model_t *mod, void *buffer, void *bufferend)
3874 {
3875         mod->brush.ishlbsp = true;
3876         mod->modeldatatypestring = "HLBSP";
3877         Mod_Q1BSP_Load(mod, buffer, bufferend);
3878 }
3879
3880 void Mod_Q1BSP_Load(model_t *mod, void *buffer, void *bufferend)
3881 {
3882         int i, j, k;
3883         sizebuf_t lumpsb[HEADER_LUMPS];
3884         mmodel_t *bm;
3885         float dist, modelyawradius, modelradius;
3886         msurface_t *surface;
3887         hullinfo_t hullinfo;
3888         int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3889         model_brush_lightstyleinfo_t styleinfo[256];
3890         unsigned char *datapointer;
3891         sizebuf_t sb;
3892
3893         MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3894
3895         mod->type = mod_brushq1;
3896
3897         mod->brush.skymasking = true;
3898         i = MSG_ReadLittleLong(&sb);
3899
3900         if(!mod->modeldatatypestring)
3901                 mod->modeldatatypestring = "Q1BSP";
3902
3903 // fill in hull info
3904         VectorClear (hullinfo.hullsizes[0][0]);
3905         VectorClear (hullinfo.hullsizes[0][1]);
3906         if (mod->brush.ishlbsp)
3907         {
3908                 hullinfo.filehulls = 4;
3909                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3910                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3911                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3912                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3913                 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3914                 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3915         }
3916         else
3917         {
3918                 hullinfo.filehulls = 4;
3919                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3920                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3921                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3922                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3923         }
3924
3925 // read lumps
3926         for (i = 0; i < HEADER_LUMPS; i++)
3927         {
3928                 int offset = MSG_ReadLittleLong(&sb);
3929                 int size = MSG_ReadLittleLong(&sb);
3930                 if (offset < 0 || offset + size > sb.cursize)
3931                         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);
3932                 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3933         }
3934
3935         mod->soundfromcenter = true;
3936         mod->TraceBox = Mod_Q1BSP_TraceBox;
3937         mod->TraceLine = Mod_Q1BSP_TraceLine;
3938         mod->TracePoint = Mod_Q1BSP_TracePoint;
3939         mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3940         mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3941         mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3942         mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3943         mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3944         mod->brush.GetPVS = Mod_BSP_GetPVS;
3945         mod->brush.FatPVS = Mod_BSP_FatPVS;
3946         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
3947         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
3948         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
3949         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
3950         mod->brush.LightPoint = Mod_BSP_LightPoint;
3951         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
3952         mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3953         mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3954         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
3955         mod->Draw = R_Mod_Draw;
3956         mod->DrawDepth = R_Mod_DrawDepth;
3957         mod->DrawDebug = R_Mod_DrawDebug;
3958         mod->DrawPrepass = R_Mod_DrawPrepass;
3959         mod->GetLightInfo = R_Mod_GetLightInfo;
3960         mod->CompileShadowMap = R_Mod_CompileShadowMap;
3961         mod->DrawShadowMap = R_Mod_DrawShadowMap;
3962         mod->DrawLight = R_Mod_DrawLight;
3963
3964 // load into heap
3965
3966         mod->brush.qw_md4sum = 0;
3967         mod->brush.qw_md4sum2 = 0;
3968         for (i = 0;i < HEADER_LUMPS;i++)
3969         {
3970                 int temp;
3971                 if (i == LUMP_ENTITIES)
3972                         continue;
3973                 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3974                 mod->brush.qw_md4sum ^= LittleLong(temp);
3975                 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3976                         continue;
3977                 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3978         }
3979
3980         Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3981         Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3982         Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3983         Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3984         Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3985         Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3986         Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3987         Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3988         Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3989         Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3990         Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3991         // load submodels before leafs because they contain the number of vis leafs
3992         Mod_BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3993         Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3994         Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3995         Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3996
3997         for (i = 0; i < HEADER_LUMPS; i++)
3998                 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3999                         Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4000
4001         // check if the map supports transparent water rendering
4002         loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
4003
4004         // we don't need the compressed pvs data anymore
4005         if (mod->brushq1.data_compressedpvs)
4006                 Mem_Free(mod->brushq1.data_compressedpvs);
4007         mod->brushq1.data_compressedpvs = NULL;
4008         mod->brushq1.num_compressedpvs = 0;
4009
4010         Mod_Q1BSP_MakeHull0();
4011         if (mod_bsp_portalize.integer)
4012                 Mod_BSP_MakePortals();
4013
4014         mod->numframes = 2;             // regular and alternate animation
4015         mod->numskins = 1;
4016
4017         if (loadmodel->brush.numsubmodels)
4018                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
4019
4020         // LadyHavoc: to clear the fog around the original quake submodel code, I
4021         // will explain:
4022         // first of all, some background info on the submodels:
4023         // model 0 is the map model (the world, named maps/e1m1.bsp for example)
4024         // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
4025         // now the weird for loop itself:
4026         // the loop functions in an odd way, on each iteration it sets up the
4027         // current 'mod' model (which despite the confusing code IS the model of
4028         // the number i), at the end of the loop it duplicates the model to become
4029         // the next submodel, and loops back to set up the new submodel.
4030
4031         // LadyHavoc: now the explanation of my sane way (which works identically):
4032         // set up the world model, then on each submodel copy from the world model
4033         // and set up the submodel with the respective model info.
4034         totalstylesurfaces = 0;
4035         totalstyles = 0;
4036         for (i = 0;i < mod->brush.numsubmodels;i++)
4037         {
4038                 memset(stylecounts, 0, sizeof(stylecounts));
4039                 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4040                 {
4041                         surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4042                         for (j = 0;j < MAXLIGHTMAPS;j++)
4043                                 stylecounts[surface->lightmapinfo->styles[j]]++;
4044                 }
4045                 for (k = 0;k < 255;k++)
4046                 {
4047                         totalstyles++;
4048                         if (stylecounts[k])
4049                                 totalstylesurfaces += stylecounts[k];
4050                 }
4051         }
4052         datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4053         mod->modelsurfaces_sorted = (int*)datapointer;datapointer += mod->num_surfaces * sizeof(int);
4054         for (i = 0;i < mod->brush.numsubmodels;i++)
4055         {
4056                 // LadyHavoc: this code was originally at the end of this loop, but
4057                 // has been transformed to something more readable at the start here.
4058
4059                 if (i > 0)
4060                 {
4061                         char name[10];
4062                         // duplicate the basic information
4063                         dpsnprintf(name, sizeof(name), "*%i", i);
4064                         mod = Mod_FindName(name, loadmodel->name);
4065                         // copy the base model to this one
4066                         *mod = *loadmodel;
4067                         // rename the clone back to its proper name
4068                         strlcpy(mod->name, name, sizeof(mod->name));
4069                         mod->brush.parentmodel = loadmodel;
4070                         // textures and memory belong to the main model
4071                         mod->texturepool = NULL;
4072                         mod->mempool = NULL;
4073                         mod->brush.GetPVS = NULL;
4074                         mod->brush.FatPVS = NULL;
4075                         mod->brush.BoxTouchingPVS = NULL;
4076                         mod->brush.BoxTouchingLeafPVS = NULL;
4077                         mod->brush.BoxTouchingVisibleLeafs = NULL;
4078                         mod->brush.FindBoxClusters = NULL;
4079                         mod->brush.LightPoint = NULL;
4080                         mod->brush.AmbientSoundLevelsForPoint = NULL;
4081                 }
4082
4083                 mod->brush.submodel = i;
4084
4085                 if (loadmodel->brush.submodels)
4086                         loadmodel->brush.submodels[i] = mod;
4087
4088                 bm = &mod->brushq1.submodels[i];
4089
4090                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4091                 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4092                 {
4093                         mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4094                         mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4095                 }
4096
4097                 mod->submodelsurfaces_start = bm->firstface;
4098                 mod->submodelsurfaces_end = bm->firstface + bm->numfaces;
4099
4100                 // set node/leaf parents for this submodel
4101                 Mod_BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4102
4103                 // this has to occur after hull info has been set, as it uses Mod_Q1BSP_PointSuperContents
4104                 Mod_Q1BSP_AssignNoShadowSkySurfaces(mod);
4105
4106                 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4107                 // (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)
4108                 VectorCopy(bm->mins, mod->normalmins);
4109                 VectorCopy(bm->maxs, mod->normalmaxs);
4110                 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4111                 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4112                 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4113                 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4114                 modelradius = modelyawradius + modelradius * modelradius;
4115                 modelyawradius = sqrt(modelyawradius);
4116                 modelradius = sqrt(modelradius);
4117                 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4118                 mod->yawmins[2] = mod->normalmins[2];
4119                 mod->yawmaxs[0] = mod->yawmaxs[1] =  modelyawradius;
4120                 mod->yawmaxs[2] = mod->normalmaxs[2];
4121                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4122                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] =  modelradius;
4123                 mod->radius = modelradius;
4124                 mod->radius2 = modelradius * modelradius;
4125
4126                 Mod_SetDrawSkyAndWater(mod);
4127
4128                 if (mod->submodelsurfaces_start < mod->submodelsurfaces_end)
4129                 {
4130                         // build lightstyle update chains
4131                         // (used to rapidly mark lightmapupdateflags on many surfaces
4132                         // when d_lightstylevalue changes)
4133                         memset(stylecounts, 0, sizeof(stylecounts));
4134                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
4135                                 for (j = 0;j < MAXLIGHTMAPS;j++)
4136                                         stylecounts[mod->data_surfaces[k].lightmapinfo->styles[j]]++;
4137                         mod->brushq1.num_lightstyles = 0;
4138                         for (k = 0;k < 255;k++)
4139                         {
4140                                 if (stylecounts[k])
4141                                 {
4142                                         styleinfo[mod->brushq1.num_lightstyles].style = k;
4143                                         styleinfo[mod->brushq1.num_lightstyles].value = 0;
4144                                         styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4145                                         styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4146                                         remapstyles[k] = mod->brushq1.num_lightstyles;
4147                                         mod->brushq1.num_lightstyles++;
4148                                 }
4149                         }
4150                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
4151                         {
4152                                 surface = mod->data_surfaces + k;
4153                                 for (j = 0;j < MAXLIGHTMAPS;j++)
4154                                 {
4155                                         if (surface->lightmapinfo->styles[j] != 255)
4156                                         {
4157                                                 int r = remapstyles[surface->lightmapinfo->styles[j]];
4158                                                 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = k;
4159                                         }
4160                                 }
4161                         }
4162                         mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4163                         memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4164                 }
4165                 else
4166                 {
4167                         // LadyHavoc: empty submodel(lacrima.bsp has such a glitch)
4168                         Con_Printf(CON_WARN "warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4169                 }
4170                 //mod->brushq1.num_visleafs = bm->visleafs;
4171
4172                 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4173                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4174
4175                 if (mod_q1bsp_polygoncollisions.integer)
4176                 {
4177                         mod->collision_bih = mod->render_bih;
4178                         // point traces and contents checks still use the bsp tree
4179                         mod->TraceLine = Mod_CollisionBIH_TraceLine;
4180                         mod->TraceBox = Mod_CollisionBIH_TraceBox;
4181                         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4182                         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4183                 }
4184
4185                 // generate VBOs and other shared data before cloning submodels
4186                 if (i == 0)
4187                 {
4188                         Mod_BuildVBOs();
4189                         Mod_Q1BSP_LoadMapBrushes();
4190                         //Mod_Q1BSP_ProcessLightList();
4191                 }
4192         }
4193         mod = loadmodel;
4194
4195         // make the model surface list (used by shadowing/lighting)
4196         Mod_MakeSortedSurfaces(loadmodel);
4197
4198         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);
4199 }
4200
4201 int Mod_Q2BSP_SuperContentsFromNativeContents(int nativecontents)
4202 {
4203         int supercontents = 0;
4204         if (nativecontents & CONTENTSQ2_SOLID)
4205                 supercontents |= SUPERCONTENTS_SOLID;
4206         if (nativecontents & CONTENTSQ2_WATER)
4207                 supercontents |= SUPERCONTENTS_WATER;
4208         if (nativecontents & CONTENTSQ2_SLIME)
4209                 supercontents |= SUPERCONTENTS_SLIME;
4210         if (nativecontents & CONTENTSQ2_LAVA)
4211                 supercontents |= SUPERCONTENTS_LAVA;
4212         if (nativecontents & CONTENTSQ2_MONSTER)
4213                 supercontents |= SUPERCONTENTS_BODY;
4214         if (nativecontents & CONTENTSQ2_DEADMONSTER)
4215                 supercontents |= SUPERCONTENTS_CORPSE;
4216         if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4217                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4218         if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4219                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4220         if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4221                 supercontents |= SUPERCONTENTS_OPAQUE;
4222         return supercontents;
4223 }
4224
4225 int Mod_Q2BSP_NativeContentsFromSuperContents(int supercontents)
4226 {
4227         int nativecontents = 0;
4228         if (supercontents & SUPERCONTENTS_SOLID)
4229                 nativecontents |= CONTENTSQ2_SOLID;
4230         if (supercontents & SUPERCONTENTS_WATER)
4231                 nativecontents |= CONTENTSQ2_WATER;
4232         if (supercontents & SUPERCONTENTS_SLIME)
4233                 nativecontents |= CONTENTSQ2_SLIME;
4234         if (supercontents & SUPERCONTENTS_LAVA)
4235                 nativecontents |= CONTENTSQ2_LAVA;
4236         if (supercontents & SUPERCONTENTS_BODY)
4237                 nativecontents |= CONTENTSQ2_MONSTER;
4238         if (supercontents & SUPERCONTENTS_CORPSE)
4239                 nativecontents |= CONTENTSQ2_DEADMONSTER;
4240         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4241                 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4242         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4243                 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4244         if (!(supercontents & SUPERCONTENTS_OPAQUE))
4245                 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4246         return nativecontents;
4247 }
4248
4249 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4250 {
4251         int i, count;
4252         loadmodel->brushq1.num_compressedpvs = 0;
4253         loadmodel->brushq1.data_compressedpvs = NULL;
4254         loadmodel->brush.num_pvsclusters = 0;
4255         loadmodel->brush.num_pvsclusterbytes = 0;
4256         loadmodel->brush.data_pvsclusters = NULL;
4257
4258         if (!sb->cursize)
4259                 return;
4260
4261         count = MSG_ReadLittleLong(sb);
4262         loadmodel->brush.num_pvsclusters = count;
4263         loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4264         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4265         for (i = 0;i < count;i++)
4266         {
4267                 int pvsofs = MSG_ReadLittleLong(sb);
4268                 /*int phsofs = */MSG_ReadLittleLong(sb);
4269                 // decompress the vis data for this cluster
4270                 // (note this accesses the underlying data store of sb, which is kind of evil)
4271                 Mod_BSP_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);
4272         }
4273         // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4274         sb->readcount = sb->cursize;
4275 }
4276
4277 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4278 {
4279         int                     i, j, count, p, child[2];
4280         mnode_t         *out;
4281         int structsize = 28;
4282
4283         if (sb->cursize % structsize)
4284                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4285         count = sb->cursize / structsize;
4286         if (count == 0)
4287                 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4288         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4289
4290         loadmodel->brush.data_nodes = out;
4291         loadmodel->brush.num_nodes = count;
4292
4293         for ( i=0 ; i<count ; i++, out++)
4294         {
4295                 p = MSG_ReadLittleLong(sb);
4296                 out->plane = loadmodel->brush.data_planes + p;
4297                 child[0] = MSG_ReadLittleLong(sb);
4298                 child[1] = MSG_ReadLittleLong(sb);
4299                 out->mins[0] = MSG_ReadLittleShort(sb);
4300                 out->mins[1] = MSG_ReadLittleShort(sb);
4301                 out->mins[2] = MSG_ReadLittleShort(sb);
4302                 out->maxs[0] = MSG_ReadLittleShort(sb);
4303                 out->maxs[1] = MSG_ReadLittleShort(sb);
4304                 out->maxs[2] = MSG_ReadLittleShort(sb);
4305                 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4306                 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4307                 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4308                 {
4309                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4310                         out->firstsurface = 0;
4311                         out->numsurfaces = 0;
4312                 }
4313                 for (j=0 ; j<2 ; j++)
4314                 {
4315                         p = child[j];
4316                         if (p >= 0)
4317                         {
4318                                 if (p < loadmodel->brush.num_nodes)
4319                                         out->children[j] = loadmodel->brush.data_nodes + p;
4320                                 else
4321                                 {
4322                                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4323                                         // map it to the solid leaf
4324                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4325                                 }
4326                         }
4327                         else
4328                         {
4329                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4330                                 p = -(p+1);
4331                                 if (p < loadmodel->brush.num_leafs)
4332                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4333                                 else
4334                                 {
4335                                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4336                                         // map it to the solid leaf
4337                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4338                                 }
4339                         }
4340                 }
4341         }
4342
4343         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);        // sets nodes and leafs
4344 }
4345
4346 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4347 {
4348         mtexinfo_t *out;
4349         int i, l, count;
4350         int structsize = 76;
4351         int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4352         char filename[MAX_QPATH];
4353
4354         if (sb->cursize % structsize)
4355                 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4356         count = sb->cursize / structsize;
4357         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4358         loadmodel->brushq1.texinfo = out;
4359         loadmodel->brushq1.numtexinfo = count;
4360         loadmodel->num_texturesperskin = 0;
4361         loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4362
4363         for (i = 0;i < count;i++, out++)
4364         {
4365                 int j, k;
4366                 for (k = 0;k < 2;k++)
4367                         for (j = 0;j < 4;j++)
4368                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4369
4370                 out->q2flags = MSG_ReadLittleLong(sb);
4371                 out->q2value = MSG_ReadLittleLong(sb);
4372                 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4373                 out->q2texture[31] = 0; // make absolutely sure it is terminated
4374                 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4375
4376                 // find an existing match for the texture if possible
4377                 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4378                 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4379                         if (!strcmp(filename, loadmodel->data_textures[j].name)
4380                          && out->q2flags == loadmodel->data_textures[j].q2flags
4381                          && out->q2value == loadmodel->data_textures[j].q2value)
4382                                 break;
4383                 // if we don't find the texture, store the new texture
4384                 if (j == loadmodel->num_texturesperskin)
4385                 {
4386                         if (loadmodel->num_texturesperskin < maxtextures)
4387                         {
4388                                 texture_t *tx = loadmodel->data_textures + j;
4389                                 int q2flags = out->q2flags;
4390                                 unsigned char *walfile = NULL;
4391                                 fs_offset_t walfilesize = 0;
4392                                 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
4393                                 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4394                                 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4395                                 if (walfile)
4396                                 {
4397                                         int w, h;
4398                                         LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4399                                         tx->width = w;
4400                                         tx->height = h;
4401                                         Mem_Free(walfile);
4402                                 }
4403                                 else
4404                                 {
4405                                         tx->width = 16;
4406                                         tx->height = 16;
4407                                 }
4408                                 tx->q2flags = out->q2flags;
4409                                 tx->q2value = out->q2value;
4410                                 // also modify the texture to have the correct contents and such based on flags
4411                                 // note that we create multiple texture_t structures if q2flags differs
4412                                 if (q2flags & Q2SURF_LIGHT)
4413                                 {
4414                                         // doesn't mean anything to us
4415                                 }
4416                                 if (q2flags & Q2SURF_SLICK)
4417                                 {
4418                                         // would be nice to support...
4419                                 }
4420                                 if (q2flags & Q2SURF_SKY)
4421                                 {
4422                                         // sky is a rather specific thing
4423                                         q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4424                                         tx->basematerialflags = MATERIALFLAG_SKY;
4425                                         tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4426                                         tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4427                                 }
4428                                 if (q2flags & Q2SURF_WARP)
4429                                 {
4430                                         // we use a scroll instead of a warp
4431                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4432                                         // if it's also transparent, we can enable the WATERSHADER
4433                                         // but we do not set the WATERALPHA flag because we don't
4434                                         // want to honor r_wateralpha in q2bsp
4435                                         // (it would go against the artistic intent)
4436                                         if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4437                                                 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4438                                 }
4439                                 if (q2flags & Q2SURF_TRANS33)
4440                                 {
4441                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4442                                         tx->basealpha = 1.0f / 3.0f;
4443                                         tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4444                                         if (tx->q2contents & Q2CONTENTS_SOLID)
4445                                                 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4446                                 }
4447                                 if (q2flags & Q2SURF_TRANS66)
4448                                 {
4449                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4450                                         tx->basealpha = 2.0f / 3.0f;
4451                                         tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4452                                         if (tx->q2contents & Q2CONTENTS_SOLID)
4453                                                 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4454                                 }
4455                                 if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
4456                                 {
4457                                         tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4458                                         if (q2flags & Q2SURF_WARP)
4459                                                 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4460                                         else
4461                                                 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4462                                         tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4463                                 }
4464                                 if (q2flags & Q2SURF_ALPHATEST)
4465                                 {
4466                                         // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4467                                         tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4468                                 }
4469                                 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4470                                 {
4471                                         if (!mod_q2bsp_littransparentsurfaces.integer)
4472                                                 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4473                                 }
4474                                 if (q2flags & Q2SURF_NODRAW)
4475                                 {
4476                                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4477                                 }
4478                                 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4479                                         tx->q2contents |= Q2CONTENTS_DETAIL;
4480                                 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4481                                         tx->q2contents |= Q2CONTENTS_SOLID;
4482                                 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4483                                         tx->q2contents = 0;
4484                                 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(tx->q2contents);
4485                                 // set the current values to the base values
4486                                 tx->currentframe = tx;
4487                                 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
4488                                 tx->currentmaterialflags = tx->basematerialflags;
4489                                 loadmodel->num_texturesperskin++;
4490                                 loadmodel->num_textures = loadmodel->num_texturesperskin;
4491                         }
4492                         else
4493                         {
4494                                 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4495                                 j = 0; // use first texture and give up
4496                         }
4497                 }
4498                 // store the index we found for this texture
4499                 out->textureindex = j;
4500         }
4501
4502         // realloc the textures array now that we know how many we actually need
4503         loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4504
4505         // now assemble the texture chains
4506         // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier 
4507         for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4508         {
4509                 int j, k;
4510                 texture_t *t = loadmodel->data_textures + out->textureindex;
4511                 t->currentframe = t; // fix the reallocated pointer
4512
4513                 // if this is not animated, skip it
4514                 // if this is already processed, skip it (part of an existing sequence)
4515                 if (out->q2nexttexinfo == 0 || t->animated)
4516                         continue;
4517
4518                 // store the array of frames to use
4519                 t->animated = 2; // q2bsp animation
4520                 t->anim_total[0] = 0;
4521                 t->anim_total[1] = 0;
4522                 // gather up to 10 frames (we don't support more)
4523                 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)
4524                 {
4525                         // detect looping and stop there
4526                         if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4527                                 break;
4528                         t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4529                 }
4530                 // we could look for the +a sequence here if this is the +0 sequence,
4531                 // but it seems that quake2 did not implement that (even though the
4532                 // files exist in the baseq2 content)
4533
4534                 // write the frame sequence to all the textures involved (just like
4535                 // in the q1bsp loader)
4536                 //
4537                 // note that this can overwrite the rest of the sequence - so if the
4538                 // start of a sequence is found later than the other parts of the
4539                 // sequence, it will go back and rewrite them correctly.
4540                 for (k = 0;k < t->anim_total[0];k++)
4541                 {
4542                         texture_t *txk = t->anim_frames[0][k];
4543                         txk->animated = t->animated;
4544                         txk->anim_total[0] = t->anim_total[0];
4545                         for (l = 0;l < t->anim_total[0];l++)
4546                                 txk->anim_frames[0][l] = t->anim_frames[0][l];
4547                 }
4548         }
4549 }
4550
4551 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4552 {
4553         // LadyHavoc: this fits exactly the same format that we use in .lit files
4554         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4555         MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4556 }
4557
4558 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4559 {
4560         mleaf_t *out;
4561         int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4562         int structsize = 28;
4563
4564         if (sb->cursize % structsize)
4565                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4566         count = sb->cursize / structsize;
4567         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4568
4569         loadmodel->brush.data_leafs = out;
4570         loadmodel->brush.num_leafs = count;
4571
4572         // FIXME: this function could really benefit from some error checking
4573         for ( i=0 ; i<count ; i++, out++)
4574         {
4575                 out->contents = MSG_ReadLittleLong(sb);
4576                 out->clusterindex = MSG_ReadLittleShort(sb);
4577                 out->areaindex = MSG_ReadLittleShort(sb);
4578                 out->mins[0] = MSG_ReadLittleShort(sb);
4579                 out->mins[1] = MSG_ReadLittleShort(sb);
4580                 out->mins[2] = MSG_ReadLittleShort(sb);
4581                 out->maxs[0] = MSG_ReadLittleShort(sb);
4582                 out->maxs[1] = MSG_ReadLittleShort(sb);
4583                 out->maxs[2] = MSG_ReadLittleShort(sb);
4584         
4585                 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4586                 nummarksurfaces  = (unsigned short)MSG_ReadLittleShort(sb);
4587                 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4588                 nummarkbrushes  = (unsigned short)MSG_ReadLittleShort(sb);
4589
4590                 for (j = 0;j < 4;j++)
4591                         out->ambient_sound_level[j] = 0;
4592
4593                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4594                 {
4595                         Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4596                         out->clusterindex = -1;
4597                 }
4598
4599                 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4600                 {
4601                         out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4602                         out->numleafsurfaces = nummarksurfaces;
4603                 }
4604                 else
4605                 {
4606                         Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4607                         out->firstleafsurface = NULL;
4608                         out->numleafsurfaces = 0;
4609                 }
4610
4611                 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4612                 {
4613                         out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4614                         out->numleafbrushes = nummarkbrushes;
4615                 }
4616                 else
4617                 {
4618                         Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4619                         out->firstleafbrush = NULL;
4620                         out->numleafbrushes = 0;
4621                 }
4622         }
4623 }
4624
4625 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4626 {
4627         int i, j;
4628         int structsize = 2;
4629
4630         if (sb->cursize % structsize)
4631                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4632         loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4633         loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4634
4635         for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4636         {
4637                 j = (unsigned short) MSG_ReadLittleShort(sb);
4638                 if (j >= loadmodel->brush.num_brushes)
4639                         Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4640                 loadmodel->brush.data_leafbrushes[i] = j;
4641         }
4642 }
4643
4644 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4645 {
4646         q3mbrushside_t *out;
4647         int i, n, count;
4648         int structsize = 4;
4649
4650         if (sb->cursize % structsize)
4651                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4652         count = sb->cursize / structsize;
4653         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4654
4655         loadmodel->brush.data_brushsides = out;
4656         loadmodel->brush.num_brushsides = count;
4657
4658         for (i = 0;i < count;i++, out++)
4659         {
4660                 n = (unsigned short)MSG_ReadLittleShort(sb);
4661                 if (n < 0 || n >= loadmodel->brush.num_planes)
4662                         Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4663                 out->plane = loadmodel->brush.data_planes + n;
4664                 n = MSG_ReadLittleShort(sb);
4665                 if (n >= 0)
4666                 {
4667                         if (n >= loadmodel->brushq1.numtexinfo)
4668                                 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4669                         out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4670                 }
4671                 else
4672                 {
4673                         //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4674                         out->texture = &mod_q1bsp_texture_solid;
4675                 }
4676         }
4677 }
4678
4679 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4680 {
4681         q3mbrush_t *out;
4682         int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4683         colplanef_t *planes;
4684         int structsize = 12;
4685         qbool brushmissingtextures;
4686         int numbrushesmissingtextures = 0;
4687         int numcreatedtextures = 0;
4688
4689         if (sb->cursize % structsize)
4690                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4691         count = sb->cursize / structsize;
4692         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4693
4694         loadmodel->brush.data_brushes = out;
4695         loadmodel->brush.num_brushes = count;
4696
4697         maxplanes = 0;
4698         planes = NULL;
4699
4700         for (i = 0; i < count; i++, out++)
4701         {
4702                 firstside = MSG_ReadLittleLong(sb);
4703                 numsides = MSG_ReadLittleLong(sb);
4704                 contents = MSG_ReadLittleLong(sb);
4705                 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4706                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4707
4708                 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4709                 out->numbrushsides = numsides;
4710                 // convert the contents to our values
4711                 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(contents);
4712
4713                 // problem: q2bsp brushes have contents but not a texture
4714                 // problem: q2bsp brushsides *may* have a texture or may not
4715                 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4716                 // solution: nasty hacks
4717                 brushmissingtextures = false;
4718                 out->texture = NULL;
4719                 for (j = 0; j < out->numbrushsides; j++)
4720                 {
4721                         if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4722                                 brushmissingtextures = true;
4723                         else
4724                         {
4725                                 // if we can find a matching texture on a brush side we can use it instead of creating one
4726                                 if (out->firstbrushside[j].texture->supercontents == supercontents)
4727                                         out->texture = out->firstbrushside[j].texture;
4728                         }
4729                 }
4730                 if (brushmissingtextures || out->texture == NULL)
4731                 {
4732                         numbrushesmissingtextures++;
4733                         // if we didn't find any appropriate texture (matching contents), we'll have to create one
4734                         // we could search earlier ones for a matching one but that can be slow
4735                         if (out->texture == NULL)
4736                         {
4737                                 texture_t *validtexture;
4738                                 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4739                                 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4740                                 validtexture->surfaceflags = 0;
4741                                 validtexture->supercontents = supercontents;
4742                                 numcreatedtextures++;
4743                                 out->texture = validtexture;
4744                         }
4745                         // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4746                         for (j = 0; j < out->numbrushsides; j++)
4747                                 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4748                                         out->firstbrushside[j].texture = out->texture;
4749                 }
4750
4751                 // make a colbrush from the brush
4752                 q3surfaceflags = 0;
4753                 // make a list of mplane_t structs to construct a colbrush from
4754                 if (maxplanes < out->numbrushsides)
4755                 {
4756                         maxplanes = out->numbrushsides;
4757                         if (planes)
4758                                 Mem_Free(planes);
4759                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4760                 }
4761                 for (j = 0;j < out->numbrushsides;j++)
4762                 {
4763                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4764                         planes[j].dist = out->firstbrushside[j].plane->dist;
4765                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4766                         planes[j].texture = out->firstbrushside[j].texture;
4767                         q3surfaceflags |= planes[j].q3surfaceflags;
4768                 }
4769                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4770
4771                 // this whole loop can take a while (e.g. on redstarrepublic4)
4772                 CL_KeepaliveMessage(false);
4773         }
4774         if (planes)
4775                 Mem_Free(planes);
4776         if (numcreatedtextures)
4777                 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);
4778 }
4779
4780 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4781 {
4782         // 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)
4783         sb->readcount = sb->cursize;
4784 }
4785
4786 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4787 {
4788         // we currently don't use areas, they represent closable doors as vis blockers
4789         sb->readcount = sb->cursize;
4790 }
4791
4792 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4793 {
4794         // we currently don't use areas, they represent closable doors as vis blockers
4795         sb->readcount = sb->cursize;
4796 }
4797
4798 static void Mod_Q2BSP_FindSubmodelBrushRange_r(model_t *mod, mnode_t *node, int *first, int *last)
4799 {
4800         int i;
4801         mleaf_t *leaf;
4802         while (node->plane)
4803         {
4804                 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4805                 node = node->children[1];
4806         }
4807         leaf = (mleaf_t*)node;
4808         for (i = 0;i < leaf->numleafbrushes;i++)
4809         {
4810                 int brushnum = leaf->firstleafbrush[i];
4811                 if (*first > brushnum)
4812                         *first = brushnum;
4813                 if (*last < brushnum)
4814                         *last = brushnum;
4815         }
4816 }
4817
4818 static void Mod_Q2BSP_Load(model_t *mod, void *buffer, void *bufferend)
4819 {
4820         int i, j, k;
4821         sizebuf_t lumpsb[Q2HEADER_LUMPS];
4822         mmodel_t *bm;
4823         float dist, modelyawradius, modelradius;
4824         msurface_t *surface;
4825         int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4826         model_brush_lightstyleinfo_t styleinfo[256];
4827         unsigned char *datapointer;
4828         sizebuf_t sb;
4829
4830         MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4831
4832         mod->type = mod_brushq2;
4833
4834         mod->brush.ishlbsp = false;
4835         mod->brush.isbsp2rmqe = false;
4836         mod->brush.isbsp2 = false;
4837         mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4838         mod->brush.isq3bsp = false;
4839         mod->brush.skymasking = true;
4840         mod->modeldatatypestring = "Q2BSP";
4841
4842         i = MSG_ReadLittleLong(&sb);
4843         if (i != Q2BSPMAGIC)
4844                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4845
4846         i = MSG_ReadLittleLong(&sb);
4847         if (i != Q2BSPVERSION)
4848                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4849
4850 // read lumps
4851         for (i = 0; i < Q2HEADER_LUMPS; i++)
4852         {
4853                 int offset = MSG_ReadLittleLong(&sb);
4854                 int size = MSG_ReadLittleLong(&sb);
4855                 if (offset < 0 || offset + size > sb.cursize)
4856                         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);
4857                 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4858         }
4859
4860         mod->soundfromcenter = true;
4861         mod->TracePoint = Mod_CollisionBIH_TracePoint;
4862         mod->TraceLine = Mod_CollisionBIH_TraceLine;
4863         mod->TraceBox = Mod_CollisionBIH_TraceBox;
4864         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4865         mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4866         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4867         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4868         mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4869         mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4870         mod->brush.GetPVS = Mod_BSP_GetPVS;
4871         mod->brush.FatPVS = Mod_BSP_FatPVS;
4872         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
4873         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
4874         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
4875         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
4876         mod->brush.LightPoint = Mod_BSP_LightPoint;
4877         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
4878         mod->brush.AmbientSoundLevelsForPoint = NULL;
4879         mod->brush.RoundUpToHullSize = NULL;
4880         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
4881         mod->Draw = R_Mod_Draw;
4882         mod->DrawDepth = R_Mod_DrawDepth;
4883         mod->DrawDebug = R_Mod_DrawDebug;
4884         mod->DrawPrepass = R_Mod_DrawPrepass;
4885         mod->GetLightInfo = R_Mod_GetLightInfo;
4886         mod->CompileShadowMap = R_Mod_CompileShadowMap;
4887         mod->DrawShadowMap = R_Mod_DrawShadowMap;
4888         mod->DrawLight = R_Mod_DrawLight;
4889
4890 // load into heap
4891
4892         mod->brush.qw_md4sum = 0;
4893         mod->brush.qw_md4sum2 = 0;
4894         for (i = 0;i < Q2HEADER_LUMPS;i++)
4895         {
4896                 int temp;
4897                 if (i == Q2LUMP_ENTITIES)
4898                         continue;
4899                 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4900                 mod->brush.qw_md4sum ^= LittleLong(temp);
4901                 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4902                         continue;
4903                 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4904         }
4905
4906         // many of these functions are identical to Q1 loaders, so we use those where possible
4907         Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4908         Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4909         Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4910         Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4911         Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4912         Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4913         Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4914         Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4915         Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4916         Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4917         Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4918         Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4919         Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4920         Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4921         Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4922         Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4923         Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4924         Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4925         Mod_BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS], NULL);
4926
4927         for (i = 0; i < Q2HEADER_LUMPS; i++)
4928                 if (lumpsb[i].readcount != lumpsb[i].cursize)
4929                         Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4930
4931         // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4932         // doesn't enable the cvar, just indicates that transparent water is OK
4933         loadmodel->brush.supportwateralpha = true;
4934
4935         // we don't need the compressed pvs data anymore
4936         if (mod->brushq1.data_compressedpvs)
4937                 Mem_Free(mod->brushq1.data_compressedpvs);
4938         mod->brushq1.data_compressedpvs = NULL;
4939         mod->brushq1.num_compressedpvs = 0;
4940
4941         // the MakePortals code works fine on the q2bsp data as well
4942         if (mod_bsp_portalize.integer)
4943                 Mod_BSP_MakePortals();
4944
4945         mod->numframes = 0;             // q2bsp animations are kind of special, frame is unbounded...
4946         mod->numskins = 1;
4947
4948         if (loadmodel->brush.numsubmodels)
4949                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
4950
4951         totalstylesurfaces = 0;
4952         totalstyles = 0;
4953         for (i = 0;i < mod->brush.numsubmodels;i++)
4954         {
4955                 memset(stylecounts, 0, sizeof(stylecounts));
4956                 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4957                 {
4958                         surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4959                         for (j = 0;j < MAXLIGHTMAPS;j++)
4960                                 stylecounts[surface->lightmapinfo->styles[j]]++;
4961                 }
4962                 for (k = 0;k < 255;k++)
4963                 {
4964                         totalstyles++;
4965                         if (stylecounts[k])
4966                                 totalstylesurfaces += stylecounts[k];
4967                 }
4968         }
4969         datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4970         mod->modelsurfaces_sorted = (int*)datapointer; datapointer += mod->num_surfaces * sizeof(int);
4971         // set up the world model, then on each submodel copy from the world model
4972         // and set up the submodel with the respective model info.
4973         mod = loadmodel;
4974         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4975         {
4976                 mnode_t *rootnode = NULL;
4977                 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
4978                 if (i > 0)
4979                 {
4980                         char name[10];
4981                         // duplicate the basic information
4982                         dpsnprintf(name, sizeof(name), "*%i", i);
4983                         mod = Mod_FindName(name, loadmodel->name);
4984                         // copy the base model to this one
4985                         *mod = *loadmodel;
4986                         // rename the clone back to its proper name
4987                         strlcpy(mod->name, name, sizeof(mod->name));
4988                         mod->brush.parentmodel = loadmodel;
4989                         // textures and memory belong to the main model
4990                         mod->texturepool = NULL;
4991                         mod->mempool = NULL;
4992                         mod->brush.GetPVS = NULL;
4993                         mod->brush.FatPVS = NULL;
4994                         mod->brush.BoxTouchingPVS = NULL;
4995                         mod->brush.BoxTouchingLeafPVS = NULL;
4996                         mod->brush.BoxTouchingVisibleLeafs = NULL;
4997                         mod->brush.FindBoxClusters = NULL;
4998                         mod->brush.LightPoint = NULL;
4999                         mod->brush.AmbientSoundLevelsForPoint = NULL;
5000                 }
5001                 mod->brush.submodel = i;
5002                 if (loadmodel->brush.submodels)
5003                         loadmodel->brush.submodels[i] = mod;
5004
5005                 bm = &mod->brushq1.submodels[i];
5006
5007                 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5008                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5009
5010                 mod->submodelsurfaces_start = bm->firstface;
5011                 mod->submodelsurfaces_end = bm->firstface + bm->numfaces;
5012
5013                 // set node/leaf parents for this submodel
5014                 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5015                 // (this happens in base3.bsp)
5016                 if (bm->headnode[0] >= 0)
5017                         rootnode = mod->brush.data_nodes + bm->headnode[0];
5018                 else
5019                         rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5020                 Mod_BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5021
5022                 // make the model surface list (used by shadowing/lighting)
5023                 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5024                 if (firstbrush <= lastbrush)
5025                 {
5026                         mod->firstmodelbrush = firstbrush;
5027                         mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5028                 }
5029                 else
5030                 {
5031                         mod->firstmodelbrush = 0;
5032                         mod->nummodelbrushes = 0;
5033                 }
5034
5035                 VectorCopy(bm->mins, mod->normalmins);
5036                 VectorCopy(bm->maxs, mod->normalmaxs);
5037                 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5038                 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5039                 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5040                 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5041                 modelradius = modelyawradius + modelradius * modelradius;
5042                 modelyawradius = sqrt(modelyawradius);
5043                 modelradius = sqrt(modelradius);
5044                 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5045                 mod->yawmins[2] = mod->normalmins[2];
5046                 mod->yawmaxs[0] = mod->yawmaxs[1] =  modelyawradius;
5047                 mod->yawmaxs[2] = mod->normalmaxs[2];
5048                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5049                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] =  modelradius;
5050                 mod->radius = modelradius;
5051                 mod->radius2 = modelradius * modelradius;
5052
5053                 Mod_SetDrawSkyAndWater(mod);
5054
5055                 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5056                 if (mod->submodelsurfaces_start < mod->submodelsurfaces_end)
5057                 {
5058                         // build lightstyle update chains
5059                         // (used to rapidly mark lightmapupdateflags on many surfaces
5060                         // when d_lightstylevalue changes)
5061                         memset(stylecounts, 0, sizeof(stylecounts));
5062                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
5063                                 for (j = 0;j < MAXLIGHTMAPS;j++)
5064                                         stylecounts[mod->data_surfaces[k].lightmapinfo->styles[j]]++;
5065                         mod->brushq1.num_lightstyles = 0;
5066                         for (k = 0;k < 255;k++)
5067                         {
5068                                 if (stylecounts[k])
5069                                 {
5070                                         styleinfo[mod->brushq1.num_lightstyles].style = k;
5071                                         styleinfo[mod->brushq1.num_lightstyles].value = 0;
5072                                         styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5073                                         styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5074                                         remapstyles[k] = mod->brushq1.num_lightstyles;
5075                                         mod->brushq1.num_lightstyles++;
5076                                 }
5077                         }
5078                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
5079                         {
5080                                 surface = mod->data_surfaces + k;
5081                                 for (j = 0;j < MAXLIGHTMAPS;j++)
5082                                 {
5083                                         if (surface->lightmapinfo->styles[j] != 255)
5084                                         {
5085                                                 int r = remapstyles[surface->lightmapinfo->styles[j]];
5086                                                 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = k;
5087                                         }
5088                                 }
5089                         }
5090                         mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5091                         memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5092                 }
5093                 else
5094                 {
5095                         Con_Printf(CON_WARN "warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5096                 }
5097                 //mod->brushq1.num_visleafs = bm->visleafs;
5098
5099                 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5100                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5101
5102                 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5103                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5104
5105                 // generate VBOs and other shared data before cloning submodels
5106                 if (i == 0)
5107                         Mod_BuildVBOs();
5108         }
5109         mod = loadmodel;
5110
5111         // make the model surface list (used by shadowing/lighting)
5112         Mod_MakeSortedSurfaces(loadmodel);
5113
5114         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);
5115 }
5116
5117 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents);
5118 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents);
5119
5120 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5121 {
5122         const char *data;
5123         char key[128], value[MAX_INPUTLINE];
5124         float v[3];
5125         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5126         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5127         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5128         if (!l->filelen)
5129                 return;
5130         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5131         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5132         loadmodel->brush.entities[l->filelen] = 0;
5133         data = loadmodel->brush.entities;
5134         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5135         // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5136         loadmodel->brushq3.deluxemapping = false;
5137         if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5138         {
5139                 while (1)
5140                 {
5141                         if (!COM_ParseToken_Simple(&data, false, false, true))
5142                                 break; // error
5143                         if (com_token[0] == '}')
5144                                 break; // end of worldspawn
5145                         if (com_token[0] == '_')
5146                                 strlcpy(key, com_token + 1, sizeof(key));
5147                         else
5148                                 strlcpy(key, com_token, sizeof(key));
5149                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
5150                                 key[strlen(key)-1] = 0;
5151                         if (!COM_ParseToken_Simple(&data, false, false, true))
5152                                 break; // error
5153                         strlcpy(value, com_token, sizeof(value));
5154                         if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5155                         {
5156 #if _MSC_VER >= 1400
5157 #define sscanf sscanf_s
5158 #endif
5159 #if 0
5160                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5161                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5162 #else
5163                                 VectorSet(v, 64, 64, 128);
5164                                 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5165                                         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]);
5166                                 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5167                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5168 #endif
5169                         }
5170                         else if (!strcmp("deluxeMaps", key))
5171                         {
5172                                 if (!strcmp(com_token, "1"))
5173                                 {
5174                                         loadmodel->brushq3.deluxemapping = true;
5175                                         loadmodel->brushq3.deluxemapping_modelspace = true;
5176                                 }
5177                                 else if (!strcmp(com_token, "2"))
5178                                 {
5179                                         loadmodel->brushq3.deluxemapping = true;
5180                                         loadmodel->brushq3.deluxemapping_modelspace = false;
5181                                 }
5182                         }
5183                 }
5184         }
5185 }
5186
5187 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5188 {
5189         q3dtexture_t *in;
5190         texture_t *out;
5191         int i, count;
5192
5193         in = (q3dtexture_t *)(mod_base + l->fileofs);
5194         if (l->filelen % sizeof(*in))
5195                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5196         count = l->filelen / sizeof(*in);
5197         out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5198
5199         loadmodel->data_textures = out;
5200         loadmodel->num_textures = count;
5201         loadmodel->num_texturesperskin = loadmodel->num_textures;
5202
5203         for (i = 0;i < count;i++)
5204         {
5205                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5206                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5207                 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
5208                 // restore the surfaceflags and supercontents
5209                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5210                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5211         }
5212 }
5213
5214 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5215 {
5216         q3dplane_t *in;
5217         mplane_t *out;
5218         int i, count;
5219
5220         in = (q3dplane_t *)(mod_base + l->fileofs);
5221         if (l->filelen % sizeof(*in))
5222                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5223         count = l->filelen / sizeof(*in);
5224         out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5225
5226         loadmodel->brush.data_planes = out;
5227         loadmodel->brush.num_planes = count;
5228
5229         for (i = 0;i < count;i++, in++, out++)
5230         {
5231                 out->normal[0] = LittleFloat(in->normal[0]);
5232                 out->normal[1] = LittleFloat(in->normal[1]);
5233                 out->normal[2] = LittleFloat(in->normal[2]);
5234                 out->dist = LittleFloat(in->dist);
5235                 PlaneClassify(out);
5236         }
5237 }
5238
5239 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5240 {
5241         q3dbrushside_t *in;
5242         q3mbrushside_t *out;
5243         int i, n, count;
5244
5245         in = (q3dbrushside_t *)(mod_base + l->fileofs);
5246         if (l->filelen % sizeof(*in))
5247                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5248         count = l->filelen / sizeof(*in);
5249         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5250
5251         loadmodel->brush.data_brushsides = out;
5252         loadmodel->brush.num_brushsides = count;
5253
5254         for (i = 0;i < count;i++, in++, out++)
5255         {
5256                 n = LittleLong(in->planeindex);
5257                 if (n < 0 || n >= loadmodel->brush.num_planes)
5258                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5259                 out->plane = loadmodel->brush.data_planes + n;
5260                 n = LittleLong(in->textureindex);
5261                 if (n < 0 || n >= loadmodel->num_textures)
5262                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5263                 out->texture = loadmodel->data_textures + n;
5264         }
5265 }
5266
5267 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5268 {
5269         q3dbrushside_ig_t *in;
5270         q3mbrushside_t *out;
5271         int i, n, count;
5272
5273         in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5274         if (l->filelen % sizeof(*in))
5275                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5276         count = l->filelen / sizeof(*in);
5277         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5278
5279         loadmodel->brush.data_brushsides = out;
5280         loadmodel->brush.num_brushsides = count;
5281
5282         for (i = 0;i < count;i++, in++, out++)
5283         {
5284                 n = LittleLong(in->planeindex);
5285                 if (n < 0 || n >= loadmodel->brush.num_planes)
5286                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5287                 out->plane = loadmodel->brush.data_planes + n;
5288                 n = LittleLong(in->textureindex);
5289                 if (n < 0 || n >= loadmodel->num_textures)
5290                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5291                 out->texture = loadmodel->data_textures + n;
5292         }
5293 }
5294
5295 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5296 {
5297         q3dbrush_t *in;
5298         q3mbrush_t *out;
5299         int i, j, n, c, count, maxplanes, q3surfaceflags;
5300         colplanef_t *planes;
5301
5302         in = (q3dbrush_t *)(mod_base + l->fileofs);
5303         if (l->filelen % sizeof(*in))
5304                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5305         count = l->filelen / sizeof(*in);
5306         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5307
5308         loadmodel->brush.data_brushes = out;
5309         loadmodel->brush.num_brushes = count;
5310
5311         maxplanes = 0;
5312         planes = NULL;
5313
5314         for (i = 0;i < count;i++, in++, out++)
5315         {
5316                 n = LittleLong(in->firstbrushside);
5317                 c = LittleLong(in->numbrushsides);
5318                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5319                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5320                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5321                 out->numbrushsides = c;
5322                 n = LittleLong(in->textureindex);
5323                 if (n < 0 || n >= loadmodel->num_textures)
5324                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5325                 out->texture = loadmodel->data_textures + n;
5326
5327                 // make a list of mplane_t structs to construct a colbrush from
5328                 if (maxplanes < out->numbrushsides)
5329                 {
5330                         maxplanes = out->numbrushsides;
5331                         if (planes)
5332                                 Mem_Free(planes);
5333                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5334                 }
5335                 q3surfaceflags = 0;
5336                 for (j = 0;j < out->numbrushsides;j++)
5337                 {
5338                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5339                         planes[j].dist = out->firstbrushside[j].plane->dist;
5340                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5341                         planes[j].texture = out->firstbrushside[j].texture;
5342                         q3surfaceflags |= planes[j].q3surfaceflags;
5343                 }
5344                 // make the colbrush from the planes
5345                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5346
5347                 // this whole loop can take a while (e.g. on redstarrepublic4)
5348                 CL_KeepaliveMessage(false);
5349         }
5350         if (planes)
5351                 Mem_Free(planes);
5352 }
5353
5354 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5355 {
5356         q3deffect_t *in;
5357         q3deffect_t *out;
5358         int i, n, count;
5359
5360         in = (q3deffect_t *)(mod_base + l->fileofs);
5361         if (l->filelen % sizeof(*in))
5362                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5363         count = l->filelen / sizeof(*in);
5364         out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5365
5366         loadmodel->brushq3.data_effects = out;
5367         loadmodel->brushq3.num_effects = count;
5368
5369         for (i = 0;i < count;i++, in++, out++)
5370         {
5371                 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5372                 n = LittleLong(in->brushindex);
5373                 if (n >= loadmodel->brush.num_brushes)
5374                 {
5375                         Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5376                         n = -1;
5377                 }
5378                 out->brushindex = n;
5379                 out->unknown = LittleLong(in->unknown);
5380         }
5381 }
5382
5383 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5384 {
5385         q3dvertex_t *in;
5386         int i, count;
5387
5388         in = (q3dvertex_t *)(mod_base + l->fileofs);
5389         if (l->filelen % sizeof(*in))
5390                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5391         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5392         loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5393         loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5394         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5395         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5396         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5397
5398         for (i = 0;i < count;i++, in++)
5399         {
5400                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5401                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5402                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5403                 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5404                 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5405                 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5406                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5407                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5408                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5409                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5410                 // svector/tvector are calculated later in face loading
5411                 if(mod_q3bsp_sRGBlightmaps.integer)
5412                 {
5413                         // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5414                         // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5415                         // working like this may be odd, but matches q3map2 -gamma 2.2
5416                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5417                         {
5418                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5419                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5420                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5421                                 // we fix the brightness consistently via lightmapscale
5422                         }
5423                         else
5424                         {
5425                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5426                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5427                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5428                         }
5429                 }
5430                 else
5431                 {
5432                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5433                         {
5434                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5435                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5436                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5437                         }
5438                         else
5439                         {
5440                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5441                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5442                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5443                         }
5444                 }
5445                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5446                 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5447                         loadmodel->lit = true;
5448         }
5449 }
5450
5451 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5452 {
5453         int *in;
5454         int *out;
5455         int i, count;
5456
5457         in = (int *)(mod_base + l->fileofs);
5458         if (l->filelen % sizeof(int[3]))
5459                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5460         count = l->filelen / sizeof(*in);
5461
5462         if(!loadmodel->brushq3.num_vertices)
5463         {
5464                 if (count)
5465                         Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5466                 loadmodel->brushq3.num_triangles = 0;
5467                 return;
5468         }
5469
5470         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5471         loadmodel->brushq3.num_triangles = count / 3;
5472         loadmodel->brushq3.data_element3i = out;
5473
5474         for (i = 0;i < count;i++, in++, out++)
5475         {
5476                 *out = LittleLong(*in);
5477                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5478                 {
5479                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5480                         *out = 0;
5481                 }
5482         }
5483 }
5484
5485 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5486 {
5487         q3dlightmap_t *input_pointer;
5488         int i;
5489         int j;
5490         int k;
5491         int count;
5492         int powerx;
5493         int powery;
5494         int powerxy;
5495         int powerdxy;
5496         int endlightmap;
5497         int mergegoal;
5498         int lightmapindex;
5499         int realcount;
5500         int realindex;
5501         int mergedwidth;
5502         int mergedheight;
5503         int mergedcolumns;
5504         int mergedrows;
5505         int mergedrowsxcolumns;
5506         int size;
5507         int bytesperpixel;
5508         int rgbmap[3];
5509         unsigned char *c;
5510         unsigned char *mergedpixels;
5511         unsigned char *mergeddeluxepixels;
5512         unsigned char *mergebuf;
5513         char mapname[MAX_QPATH];
5514         qbool external;
5515         unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5516         char vabuf[1024];
5517
5518         // defaults for q3bsp
5519         size = 128;
5520         bytesperpixel = 3;
5521         rgbmap[0] = 2;
5522         rgbmap[1] = 1;
5523         rgbmap[2] = 0;
5524         external = false;
5525         loadmodel->brushq3.lightmapsize = 128;
5526
5527         if (cls.state == ca_dedicated)
5528                 return;
5529
5530         if(mod_q3bsp_nolightmaps.integer)
5531         {
5532                 return;
5533         }
5534         else if(l->filelen)
5535         {
5536                 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5537                 if (developer_loading.integer)
5538                         Con_Printf("Using internal lightmaps\n");
5539                 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5540                 if (l->filelen % sizeof(*input_pointer))
5541                         Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5542                 count = l->filelen / sizeof(*input_pointer);
5543                 for(i = 0; i < count; ++i)
5544                         inpixels[i] = input_pointer[i].rgb;
5545         }
5546         else
5547         {
5548                 // no internal lightmaps
5549                 // try external lightmaps
5550                 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5551                 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5552                 if(!inpixels[0])
5553                         return;
5554                 else
5555                         Con_Printf("Using external lightmaps\n");
5556
5557                 // using EXTERNAL lightmaps instead
5558                 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5559                         Con_Printf("Mod_Q3BSP_LoadLightmaps: irregularly sized external lightmap in %s",loadmodel->name);
5560
5561                 size = image_width;
5562                 bytesperpixel = 4;
5563                 rgbmap[0] = 0;
5564                 rgbmap[1] = 1;
5565                 rgbmap[2] = 2;
5566                 external = true;
5567
5568                 for(count = 1; ; ++count)
5569                 {
5570                         inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5571                         if(!inpixels[count])
5572                                 break; // we got all of them
5573                         if(image_width != size || image_height != size)
5574                         {
5575                                 Mem_Free(inpixels[count]);
5576                                 inpixels[count] = NULL;
5577                                 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);
5578                                 break;
5579                         }
5580                 }
5581         }
5582
5583         loadmodel->brushq3.lightmapsize = size;
5584         loadmodel->brushq3.num_originallightmaps = count;
5585
5586         // now check the surfaces to see if any of them index an odd numbered
5587         // lightmap, if so this is not a deluxemapped bsp file
5588         //
5589         // also check what lightmaps are actually used, because q3map2 sometimes
5590         // (always?) makes an unused one at the end, which
5591         // q3map2 sometimes (or always?) makes a second blank lightmap for no
5592         // reason when only one lightmap is used, which can throw off the
5593         // deluxemapping detection method, so check 2-lightmap bsp's specifically
5594         // to see if the second lightmap is blank, if so it is not deluxemapped.
5595         // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5596         // in Mod_Q3BSP_LoadEntities was failed
5597         if (!loadmodel->brushq3.deluxemapping)
5598         {
5599                 loadmodel->brushq3.deluxemapping = !(count & 1);
5600                 loadmodel->brushq3.deluxemapping_modelspace = true;
5601                 endlightmap = 0;
5602                 if (loadmodel->brushq3.deluxemapping)
5603                 {
5604                         int facecount = faceslump->filelen / sizeof(q3dface_t);
5605                         q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5606                         for (i = 0;i < facecount;i++)
5607                         {
5608                                 j = LittleLong(faces[i].lightmapindex);
5609                                 if (j >= 0)
5610                                 {
5611                                         endlightmap = max(endlightmap, j + 1);
5612                                         if ((j & 1) || j + 1 >= count)
5613                                         {
5614                                                 loadmodel->brushq3.deluxemapping = false;
5615                                                 break;
5616                                         }
5617                                 }
5618                         }
5619                 }
5620
5621                 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5622                 // reason when only one lightmap is used, which can throw off the
5623                 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5624                 // to see if the second lightmap is blank, if so it is not deluxemapped.
5625                 //
5626                 // further research has shown q3map2 sometimes creates a deluxemap and two
5627                 // blank lightmaps, which must be handled properly as well
5628                 if (endlightmap == 1 && count > 1)
5629                 {
5630                         c = inpixels[1];
5631                         for (i = 0;i < size*size;i++)
5632                         {
5633                                 if (c[bytesperpixel*i + rgbmap[0]])
5634                                         break;
5635                                 if (c[bytesperpixel*i + rgbmap[1]])
5636                                         break;
5637                                 if (c[bytesperpixel*i + rgbmap[2]])
5638                                         break;
5639                         }
5640                         if (i == size*size)
5641                         {
5642                                 // all pixels in the unused lightmap were black...
5643                                 loadmodel->brushq3.deluxemapping = false;
5644                         }
5645                 }
5646         }
5647
5648         Con_Printf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5649
5650         // figure out what the most reasonable merge power is within limits
5651
5652         // find the appropriate NxN dimensions to merge to, to avoid wasted space
5653         realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5654
5655         // figure out how big the merged texture has to be
5656         mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5657         mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5658         while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5659                 mergegoal /= 2;
5660         mergedwidth = mergegoal;
5661         mergedheight = mergegoal;
5662         // choose non-square size (2x1 aspect) if only half the space is used;
5663         // this really only happens when the entire set fits in one texture, if
5664         // there are multiple textures, we don't worry about shrinking the last
5665         // one to fit, because the driver prefers the same texture size on
5666         // consecutive draw calls...
5667         if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5668                 mergedheight /= 2;
5669
5670         loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5671         loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5672         while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5673                 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5674         while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5675                 loadmodel->brushq3.num_lightmapmergedheightpower++;
5676         loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5677
5678         powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5679         powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5680         powerxy = powerx+powery;
5681         powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5682
5683         mergedcolumns = 1 << powerx;
5684         mergedrows = 1 << powery;
5685         mergedrowsxcolumns = 1 << powerxy;
5686
5687         loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5688         loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5689         if (loadmodel->brushq3.deluxemapping)
5690                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5691
5692         mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5693         mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5694         for (i = 0;i < count;i++)
5695         {
5696                 // figure out which merged lightmap texture this fits into
5697                 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5698                 lightmapindex = i >> powerdxy;
5699
5700                 // choose the destination address
5701                 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5702                 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5703                 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5704                         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);
5705
5706                 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5707                 for (j = 0;j < size;j++)
5708                 for (k = 0;k < size;k++)
5709                 {
5710                         mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5711                         mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5712                         mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5713                         mergebuf[(j*mergedwidth+k)*4+3] = 255;
5714                 }
5715
5716                 // upload texture if this was the last tile being written to the texture
5717                 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5718                 {
5719                         if (loadmodel->brushq3.deluxemapping && (i & 1))
5720                                 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);
5721                         else
5722                         {
5723                                 if(mod_q3bsp_sRGBlightmaps.integer)
5724                                 {
5725                                         textype_t t;
5726                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5727                                         {
5728                                                 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5729                                                 // we fix the brightness consistently via lightmapscale
5730                                         }
5731                                         else
5732                                                 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5733                                         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);
5734                                 }
5735                                 else
5736                                 {
5737                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5738                                                 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5739                                         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);
5740                                 }
5741                         }
5742                 }
5743         }
5744
5745         if (mergeddeluxepixels)
5746                 Mem_Free(mergeddeluxepixels);
5747         Mem_Free(mergedpixels);
5748         if(external)
5749         {
5750                 for(i = 0; i < count; ++i)
5751                         Mem_Free(inpixels[i]);
5752         }
5753 }
5754
5755 typedef struct patchtess_s
5756 {
5757         patchinfo_t info;
5758
5759         // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5760         int surface_id;
5761         float lodgroup[6];
5762         float *originalvertex3f;
5763 } patchtess_t;
5764
5765 #define PATCHTESS_SAME_LODGROUP(a,b) \
5766         ( \
5767                 (a).lodgroup[0] == (b).lodgroup[0] && \
5768                 (a).lodgroup[1] == (b).lodgroup[1] && \
5769                 (a).lodgroup[2] == (b).lodgroup[2] && \
5770                 (a).lodgroup[3] == (b).lodgroup[3] && \
5771                 (a).lodgroup[4] == (b).lodgroup[4] && \
5772                 (a).lodgroup[5] == (b).lodgroup[5] \
5773         )
5774
5775 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5776 {
5777         q3dface_t *in, *oldin;
5778         msurface_t *out, *oldout;
5779         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;
5780         float lightmaptcbase[2], lightmaptcscale[2];
5781         //int *originalelement3i;
5782         float *originalvertex3f;
5783         //float *originalsvector3f;
5784         //float *originaltvector3f;
5785         float *originalnormal3f;
5786         float *originalcolor4f;
5787         float *originaltexcoordtexture2f;
5788         float *originaltexcoordlightmap2f;
5789         float *surfacecollisionvertex3f;
5790         int *surfacecollisionelement3i;
5791         float *v;
5792         patchtess_t *patchtess = NULL;
5793         int patchtesscount = 0;
5794         qbool again;
5795
5796         in = (q3dface_t *)(mod_base + l->fileofs);
5797         if (l->filelen % sizeof(*in))
5798                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5799         count = l->filelen / sizeof(*in);
5800         out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5801
5802         loadmodel->data_surfaces = out;
5803         loadmodel->num_surfaces = count;
5804
5805         if(count > 0)
5806                 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5807
5808         i = 0;
5809         oldi = i;
5810         oldin = in;
5811         oldout = out;
5812         meshvertices = 0;
5813         meshtriangles = 0;
5814         for (;i < count;i++, in++, out++)
5815         {
5816                 // check face type first
5817                 type = LittleLong(in->type);
5818                 if (type != Q3FACETYPE_FLAT
5819                  && type != Q3FACETYPE_PATCH
5820                  && type != Q3FACETYPE_MESH
5821                  && type != Q3FACETYPE_FLARE)
5822                 {
5823                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5824                         continue;
5825                 }
5826
5827                 n = LittleLong(in->textureindex);
5828                 if (n < 0 || n >= loadmodel->num_textures)
5829                 {
5830                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5831                         continue;
5832                 }
5833                 out->texture = loadmodel->data_textures + n;
5834                 n = LittleLong(in->effectindex);
5835                 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5836                 {
5837                         if (developer_extra.integer)
5838                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5839                         n = -1;
5840                 }
5841                 if (n == -1)
5842                         out->effect = NULL;
5843                 else
5844                         out->effect = loadmodel->brushq3.data_effects + n;
5845
5846                 if (cls.state != ca_dedicated)
5847                 {
5848                         out->lightmaptexture = NULL;
5849                         out->deluxemaptexture = r_texture_blanknormalmap;
5850                         n = LittleLong(in->lightmapindex);
5851                         if (n < 0)
5852                                 n = -1;
5853                         else if (n >= loadmodel->brushq3.num_originallightmaps)
5854                         {
5855                                 if(loadmodel->brushq3.num_originallightmaps != 0)
5856                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5857                                 n = -1;
5858                         }
5859                         else
5860                         {
5861                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5862                                 if (loadmodel->brushq3.deluxemapping)
5863                                         out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5864                                 loadmodel->lit = true;
5865                         }
5866                 }
5867
5868                 firstvertex = LittleLong(in->firstvertex);
5869                 numvertices = LittleLong(in->numvertices);
5870                 firstelement = LittleLong(in->firstelement);
5871                 numtriangles = LittleLong(in->numelements) / 3;
5872                 if (numtriangles * 3 != LittleLong(in->numelements))
5873                 {
5874                         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));
5875                         continue;
5876                 }
5877                 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5878                 {
5879                         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);
5880                         continue;
5881                 }
5882                 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5883                 {
5884                         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);
5885                         continue;
5886                 }
5887                 switch(type)
5888                 {
5889                 case Q3FACETYPE_FLAT:
5890                 case Q3FACETYPE_MESH:
5891                         // no processing necessary
5892                         break;
5893                 case Q3FACETYPE_PATCH:
5894                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5895                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5896                         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))
5897                         {
5898                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5899                                 continue;
5900                         }
5901                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5902
5903                         // convert patch to Q3FACETYPE_MESH
5904                         xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5905                         ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5906                         // bound to user settings
5907                         xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5908                         ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5909                         // bound to sanity settings
5910                         xtess = bound(0, xtess, 1024);
5911                         ytess = bound(0, ytess, 1024);
5912
5913                         // lower quality collision patches! Same procedure as before, but different cvars
5914                         // convert patch to Q3FACETYPE_MESH
5915                         cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5916                         cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5917                         // bound to user settings
5918                         cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5919                         cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5920                         // bound to sanity settings
5921                         cxtess = bound(0, cxtess, 1024);
5922                         cytess = bound(0, cytess, 1024);
5923
5924                         // store it for the LOD grouping step
5925                         patchtess[patchtesscount].info.xsize = patchsize[0];
5926                         patchtess[patchtesscount].info.ysize = patchsize[1];
5927                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5928                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5929                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5930                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5931         
5932                         patchtess[patchtesscount].surface_id = i;
5933                         patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5934                         patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5935                         patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5936                         patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5937                         patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5938                         patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5939                         patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5940                         ++patchtesscount;
5941                         break;
5942                 case Q3FACETYPE_FLARE:
5943                         if (developer_extra.integer)
5944                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5945                         // don't render it
5946                         continue;
5947                 }
5948                 out->num_vertices = numvertices;
5949                 out->num_triangles = numtriangles;
5950                 meshvertices += out->num_vertices;
5951                 meshtriangles += out->num_triangles;
5952         }
5953
5954         // Fix patches tesselations so that they make no seams
5955         do
5956         {
5957                 again = false;
5958                 for(i = 0; i < patchtesscount; ++i)
5959                 {
5960                         for(j = i+1; j < patchtesscount; ++j)
5961                         {
5962                                 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5963                                         continue;
5964
5965                                 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5966                                         again = true;
5967                         }
5968                 }
5969         }
5970         while (again);
5971
5972         // Calculate resulting number of triangles
5973         collisionvertices = 0;
5974         collisiontriangles = 0;
5975         for(i = 0; i < patchtesscount; ++i)
5976         {
5977                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5978                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5979                 numvertices = finalwidth * finalheight;
5980                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5981
5982                 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5983                 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5984                 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5985                 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5986
5987                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5988                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5989                 numvertices = finalwidth * finalheight;
5990                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5991
5992                 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5993                 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5994                 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5995                 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5996         }
5997
5998         i = oldi;
5999         in = oldin;
6000         out = oldout;
6001         Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true);
6002         if (collisiontriangles)
6003         {
6004                 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6005                 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6006         }
6007         meshvertices = 0;
6008         meshtriangles = 0;
6009         collisionvertices = 0;
6010         collisiontriangles = 0;
6011         for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6012         {
6013                 if (out->num_vertices < 3 || out->num_triangles < 1)
6014                         continue;
6015
6016                 type = LittleLong(in->type);
6017                 firstvertex = LittleLong(in->firstvertex);
6018                 firstelement = LittleLong(in->firstelement);
6019                 out->num_firstvertex = meshvertices;
6020                 out->num_firsttriangle = meshtriangles;
6021                 out->num_firstcollisiontriangle = collisiontriangles;
6022                 switch(type)
6023                 {
6024                 case Q3FACETYPE_FLAT:
6025                 case Q3FACETYPE_MESH:
6026                         // no processing necessary, except for lightmap merging
6027                         for (j = 0;j < out->num_vertices;j++)
6028                         {
6029                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6030                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6031                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6032                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6033                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6034                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6035                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6036                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6037                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6038                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6039                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6040                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6041                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6042                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6043                         }
6044                         for (j = 0;j < out->num_triangles*3;j++)
6045                                 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6046                         break;
6047                 case Q3FACETYPE_PATCH:
6048                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6049                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6050                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6051                         originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6052                         originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6053                         originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6054                         originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6055
6056                         xtess = ytess = cxtess = cytess = -1;
6057                         for(j = 0; j < patchtesscount; ++j)
6058                                 if(patchtess[j].surface_id == i)
6059                                 {
6060                                         xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6061                                         ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6062                                         cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6063                                         cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6064                                         break;
6065                                 }
6066                         if(xtess == -1)
6067                         {
6068                                 Con_Printf(CON_ERROR "ERROR: patch %d isn't preprocessed?!?\n", i);
6069                                 xtess = ytess = cxtess = cytess = 0;
6070                         }
6071
6072                         finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6073                         finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6074                         finalvertices = finalwidth * finalheight;
6075                         oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6076                         type = Q3FACETYPE_MESH;
6077                         // generate geometry
6078                         // (note: normals are skipped because they get recalculated)
6079                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6080                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6081                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6082                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6083                         Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6084                         Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6085
6086                         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);
6087
6088                         if (developer_extra.integer)
6089                         {
6090                                 if (out->num_triangles < finaltriangles)
6091                                         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);
6092                                 else
6093                                         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);
6094                         }
6095                         // q3map does not put in collision brushes for curves... ugh
6096                         // build the lower quality collision geometry
6097                         finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6098                         finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6099                         finalvertices = finalwidth * finalheight;
6100                         oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6101
6102                         // store collision geometry for BIH collision tree
6103                         out->num_collisionvertices = finalvertices;
6104                         out->num_collisiontriangles = finaltriangles;
6105                         surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6106                         surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6107                         Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6108                         Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6109                         Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6110                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6111
6112                         if (developer_extra.integer)
6113                                 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);
6114
6115                         collisionvertices += finalvertices;
6116                         collisiontriangles += out->num_collisiontriangles;
6117                         break;
6118                 default:
6119                         break;
6120                 }
6121                 meshvertices += out->num_vertices;
6122                 meshtriangles += out->num_triangles;
6123                 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6124                         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)
6125                                 invalidelements++;
6126                 if (invalidelements)
6127                 {
6128                         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);
6129                         for (j = 0;j < out->num_triangles * 3;j++)
6130                         {
6131                                 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6132                                 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)
6133                                         (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6134                         }
6135                         Con_Print("\n");
6136                 }
6137                 // calculate a bounding box
6138                 VectorClear(out->mins);
6139                 VectorClear(out->maxs);
6140                 if (out->num_vertices)
6141                 {
6142                         if (cls.state != ca_dedicated && out->lightmaptexture)
6143                         {
6144                                 // figure out which part of the merged lightmap this fits into
6145                                 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6146                                 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6147                                 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6148                                 lightmapindex &= mergewidth * mergeheight - 1;
6149                                 lightmaptcscale[0] = 1.0f / mergewidth;
6150                                 lightmaptcscale[1] = 1.0f / mergeheight;
6151                                 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6152                                 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6153                                 // modify the lightmap texcoords to match this region of the merged lightmap
6154                                 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6155                                 {
6156                                         v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6157                                         v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6158                                 }
6159                         }
6160                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6161                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6162                         for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6163                         {
6164                                 out->mins[0] = min(out->mins[0], v[0]);
6165                                 out->maxs[0] = max(out->maxs[0], v[0]);
6166                                 out->mins[1] = min(out->mins[1], v[1]);
6167                                 out->maxs[1] = max(out->maxs[1], v[1]);
6168                                 out->mins[2] = min(out->mins[2], v[2]);
6169                                 out->maxs[2] = max(out->maxs[2], v[2]);
6170                         }
6171                         out->mins[0] -= 1.0f;
6172                         out->mins[1] -= 1.0f;
6173                         out->mins[2] -= 1.0f;
6174                         out->maxs[0] += 1.0f;
6175                         out->maxs[1] += 1.0f;
6176                         out->maxs[2] += 1.0f;
6177                 }
6178                 // set lightmap styles for consistency with q1bsp
6179                 //out->lightmapinfo->styles[0] = 0;
6180                 //out->lightmapinfo->styles[1] = 255;
6181                 //out->lightmapinfo->styles[2] = 255;
6182                 //out->lightmapinfo->styles[3] = 255;
6183         }
6184
6185         i = oldi;
6186         out = oldout;
6187         for (;i < count;i++, out++)
6188         {
6189                 if(out->num_vertices && out->num_triangles)
6190                         continue;
6191                 if(out->num_vertices == 0)
6192                 {
6193                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6194                         if(out->num_triangles == 0)
6195                                 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6196                 }
6197                 else if(out->num_triangles == 0)
6198                         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)",
6199                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6200                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6201                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6202         }
6203
6204         // for per pixel lighting
6205         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);
6206
6207         // generate ushort elements array if possible
6208         if (loadmodel->surfmesh.data_element3s)
6209                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6210                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6211
6212         // free the no longer needed vertex data
6213         loadmodel->brushq3.num_vertices = 0;
6214         if (loadmodel->brushq3.data_vertex3f)
6215                 Mem_Free(loadmodel->brushq3.data_vertex3f);
6216         loadmodel->brushq3.data_vertex3f = NULL;
6217         loadmodel->brushq3.data_normal3f = NULL;
6218         loadmodel->brushq3.data_texcoordtexture2f = NULL;
6219         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6220         loadmodel->brushq3.data_color4f = NULL;
6221         // free the no longer needed triangle data
6222         loadmodel->brushq3.num_triangles = 0;
6223         if (loadmodel->brushq3.data_element3i)
6224                 Mem_Free(loadmodel->brushq3.data_element3i);
6225         loadmodel->brushq3.data_element3i = NULL;
6226
6227         if(patchtess)
6228                 Mem_Free(patchtess);
6229 }
6230
6231 static void Mod_Q3BSP_LoadModels(lump_t *l)
6232 {
6233         q3dmodel_t *in;
6234         q3dmodel_t *out;
6235         int i, j, n, c, count;
6236
6237         in = (q3dmodel_t *)(mod_base + l->fileofs);
6238         if (l->filelen % sizeof(*in))
6239                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6240         count = l->filelen / sizeof(*in);
6241         out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6242
6243         loadmodel->brushq3.data_models = out;
6244         loadmodel->brushq3.num_models = count;
6245
6246         for (i = 0;i < count;i++, in++, out++)
6247         {
6248                 for (j = 0;j < 3;j++)
6249                 {
6250                         out->mins[j] = LittleFloat(in->mins[j]);
6251                         out->maxs[j] = LittleFloat(in->maxs[j]);
6252                 }
6253                 n = LittleLong(in->firstface);
6254                 c = LittleLong(in->numfaces);
6255                 if (n < 0 || n + c > loadmodel->num_surfaces)
6256                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6257                 out->firstface = n;
6258                 out->numfaces = c;
6259                 n = LittleLong(in->firstbrush);
6260                 c = LittleLong(in->numbrushes);
6261                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6262                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6263                 out->firstbrush = n;
6264                 out->numbrushes = c;
6265         }
6266 }
6267
6268 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6269 {
6270         int *in;
6271         int *out;
6272         int i, n, count;
6273
6274         in = (int *)(mod_base + l->fileofs);
6275         if (l->filelen % sizeof(*in))
6276                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6277         count = l->filelen / sizeof(*in);
6278         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6279
6280         loadmodel->brush.data_leafbrushes = out;
6281         loadmodel->brush.num_leafbrushes = count;
6282
6283         for (i = 0;i < count;i++, in++, out++)
6284         {
6285                 n = LittleLong(*in);
6286                 if (n < 0 || n >= loadmodel->brush.num_brushes)
6287                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6288                 *out = n;
6289         }
6290 }
6291
6292 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6293 {
6294         int *in;
6295         int *out;
6296         int i, n, count;
6297
6298         in = (int *)(mod_base + l->fileofs);
6299         if (l->filelen % sizeof(*in))
6300                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6301         count = l->filelen / sizeof(*in);
6302         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6303
6304         loadmodel->brush.data_leafsurfaces = out;
6305         loadmodel->brush.num_leafsurfaces = count;
6306
6307         for (i = 0;i < count;i++, in++, out++)
6308         {
6309                 n = LittleLong(*in);
6310                 if (n < 0 || n >= loadmodel->num_surfaces)
6311                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6312                 *out = n;
6313         }
6314 }
6315
6316 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6317 {
6318         q3dleaf_t *in;
6319         mleaf_t *out;
6320         int i, j, n, c, count;
6321
6322         in = (q3dleaf_t *)(mod_base + l->fileofs);
6323         if (l->filelen % sizeof(*in))
6324                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6325         count = l->filelen / sizeof(*in);
6326         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6327
6328         loadmodel->brush.data_leafs = out;
6329         loadmodel->brush.num_leafs = count;
6330
6331         for (i = 0;i < count;i++, in++, out++)
6332         {
6333                 out->parent = NULL;
6334                 out->plane = NULL;
6335                 out->clusterindex = LittleLong(in->clusterindex);
6336                 out->areaindex = LittleLong(in->areaindex);
6337                 for (j = 0;j < 3;j++)
6338                 {
6339                         // yes the mins/maxs are ints
6340                         out->mins[j] = LittleLong(in->mins[j]) - 1;
6341                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6342                 }
6343                 n = LittleLong(in->firstleafface);
6344                 c = LittleLong(in->numleaffaces);
6345                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6346                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6347                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6348                 out->numleafsurfaces = c;
6349                 n = LittleLong(in->firstleafbrush);
6350                 c = LittleLong(in->numleafbrushes);
6351                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6352                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6353                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6354                 out->numleafbrushes = c;
6355         }
6356 }
6357
6358 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6359 {
6360         q3dnode_t *in;
6361         mnode_t *out;
6362         int i, j, n, count;
6363
6364         in = (q3dnode_t *)(mod_base + l->fileofs);
6365         if (l->filelen % sizeof(*in))
6366                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6367         count = l->filelen / sizeof(*in);
6368         if (count == 0)
6369                 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6370         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6371
6372         loadmodel->brush.data_nodes = out;
6373         loadmodel->brush.num_nodes = count;
6374
6375         for (i = 0;i < count;i++, in++, out++)
6376         {
6377                 out->parent = NULL;
6378                 n = LittleLong(in->planeindex);
6379                 if (n < 0 || n >= loadmodel->brush.num_planes)
6380                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6381                 out->plane = loadmodel->brush.data_planes + n;
6382                 for (j = 0;j < 2;j++)
6383                 {
6384                         n = LittleLong(in->childrenindex[j]);
6385                         if (n >= 0)
6386                         {
6387                                 if (n >= loadmodel->brush.num_nodes)
6388                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6389                                 out->children[j] = loadmodel->brush.data_nodes + n;
6390                         }
6391                         else
6392                         {
6393                                 n = -1 - n;
6394                                 if (n >= loadmodel->brush.num_leafs)
6395                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6396                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6397                         }
6398                 }
6399                 for (j = 0;j < 3;j++)
6400                 {
6401                         // yes the mins/maxs are ints
6402                         out->mins[j] = LittleLong(in->mins[j]) - 1;
6403                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6404                 }
6405         }
6406
6407         // set the parent pointers
6408         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6409 }
6410
6411 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6412 {
6413         q3dlightgrid_t *in;
6414         q3dlightgrid_t *out;
6415         int count;
6416         int i;
6417         int texturesize[3];
6418         unsigned char *texturergba, *texturelayer[3], *texturepadding[2];
6419         double lightgridmatrix[4][4];
6420
6421         in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6422         if (l->filelen % sizeof(*in))
6423                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6424         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6425         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6426         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6427         loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6428         loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6429         loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6430         loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6431         loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6432         loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6433         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6434         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6435         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6436         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6437         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]);
6438         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]);
6439
6440         // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6441         if (l->filelen)
6442         {
6443                 if (l->filelen < count * (int)sizeof(*in))
6444                 {
6445                         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]);
6446                         return; // ignore the grid if we cannot understand it
6447                 }
6448                 if (l->filelen != count * (int)sizeof(*in))
6449                         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);
6450                 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6451                 loadmodel->brushq3.data_lightgrid = out;
6452                 loadmodel->brushq3.num_lightgrid = count;
6453                 // no swapping or validation necessary
6454                 memcpy(out, in, count * (int)sizeof(*out));
6455
6456                 if(mod_q3bsp_sRGBlightmaps.integer)
6457                 {
6458                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6459                         {
6460                                 // we fix the brightness consistently via lightmapscale
6461                         }
6462                         else
6463                         {
6464                                 for(i = 0; i < count; ++i)
6465                                 {
6466                                         out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6467                                         out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6468                                         out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6469                                         out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6470                                         out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6471                                         out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6472                                 }
6473                         }
6474                 }
6475                 else
6476                 {
6477                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6478                         {
6479                                 for(i = 0; i < count; ++i)
6480                                 {
6481                                         out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6482                                         out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6483                                         out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6484                                         out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6485                                         out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6486                                         out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6487                                 }
6488                         }
6489                         else
6490                         {
6491                                 // all is good
6492                         }
6493                 }
6494
6495                 if (mod_q3bsp_lightgrid_texture.integer)
6496                 {
6497                         // build a texture to hold the data for per-pixel sampling
6498                         // this has 3 different kinds of data stacked in it:
6499                         // ambient color
6500                         // bent-normal light color
6501                         // bent-normal light dir
6502
6503                         texturesize[0] = loadmodel->brushq3.num_lightgrid_isize[0];
6504                         texturesize[1] = loadmodel->brushq3.num_lightgrid_isize[1];
6505                         texturesize[2] = (loadmodel->brushq3.num_lightgrid_isize[2] + 2) * 3;
6506                         texturergba = (unsigned char*)Mem_Alloc(loadmodel->mempool, texturesize[0] * texturesize[1] * texturesize[2] * sizeof(char[4]));
6507                         texturelayer[0] = texturergba + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6508                         texturelayer[1] = texturelayer[0] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6509                         texturelayer[2] = texturelayer[1] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6510                         // the light dir layer needs padding above/below it that is a neutral unsigned normal (127,127,127,255)
6511                         texturepadding[0] = texturelayer[2] - loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6512                         texturepadding[1] = texturelayer[2] + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2] * 4;
6513                         for (i = 0; i < texturesize[0] * texturesize[1]; i++)
6514                         {
6515                                 texturepadding[0][i * 4] = texturepadding[1][i * 4] = 127;
6516                                 texturepadding[0][i * 4 + 1] = texturepadding[1][i * 4 + 1] = 127;
6517                                 texturepadding[0][i * 4 + 2] = texturepadding[1][i * 4 + 2] = 127;
6518                                 texturepadding[0][i * 4 + 3] = texturepadding[1][i * 4 + 3] = 255;
6519                         }
6520                         for (i = 0; i < count; i++)
6521                         {
6522                                 texturelayer[0][i * 4 + 0] = out[i].ambientrgb[0];
6523                                 texturelayer[0][i * 4 + 1] = out[i].ambientrgb[1];
6524                                 texturelayer[0][i * 4 + 2] = out[i].ambientrgb[2];
6525                                 texturelayer[0][i * 4 + 3] = 255;
6526                                 texturelayer[1][i * 4 + 0] = out[i].diffusergb[0];
6527                                 texturelayer[1][i * 4 + 1] = out[i].diffusergb[1];
6528                                 texturelayer[1][i * 4 + 2] = out[i].diffusergb[2];
6529                                 texturelayer[1][i * 4 + 3] = 255;
6530                                 // this uses the mod_md3_sin table because the values are
6531                                 // already in the 0-255 range, the 64+ bias fetches a cosine
6532                                 // instead of a sine value
6533                                 texturelayer[2][i * 4 + 0] = (char)((mod_md3_sin[64 + out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6534                                 texturelayer[2][i * 4 + 1] = (char)((mod_md3_sin[out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6535                                 texturelayer[2][i * 4 + 2] = (char)((mod_md3_sin[64 + out[i].diffusepitch]) * 127 + 127);
6536                                 texturelayer[2][i * 4 + 3] = 255;
6537                         }
6538 #if 0
6539                         // debugging hack
6540                         int x, y, z;
6541                         for (z = 0; z < loadmodel->brushq3.num_lightgrid_isize[2]; z++)
6542                         {
6543                                 for (y = 0; y < loadmodel->brushq3.num_lightgrid_isize[1]; y++)
6544                                 {
6545                                         for (x = 0; x < loadmodel->brushq3.num_lightgrid_isize[0]; x++)
6546                                         {
6547                                                 i = (z * texturesize[1] + y) * texturesize[0] + x;
6548                                                 texturelayer[0][i * 4 + 0] = x * 256 / loadmodel->brushq3.num_lightgrid_isize[0];
6549                                                 texturelayer[0][i * 4 + 1] = y * 256 / loadmodel->brushq3.num_lightgrid_isize[1];
6550                                                 texturelayer[0][i * 4 + 2] = z * 256 / loadmodel->brushq3.num_lightgrid_isize[2];
6551                                         }
6552                                 }
6553                         }
6554 #endif
6555                         loadmodel->brushq3.lightgridtexturesize[0] = texturesize[0];
6556                         loadmodel->brushq3.lightgridtexturesize[1] = texturesize[1];
6557                         loadmodel->brushq3.lightgridtexturesize[2] = texturesize[2];
6558                         memset(lightgridmatrix[0], 0, sizeof(lightgridmatrix));
6559                         lightgridmatrix[0][0] = loadmodel->brushq3.num_lightgrid_scale[0] / texturesize[0];
6560                         lightgridmatrix[1][1] = loadmodel->brushq3.num_lightgrid_scale[1] / texturesize[1];
6561                         lightgridmatrix[2][2] = loadmodel->brushq3.num_lightgrid_scale[2] / texturesize[2];
6562                         lightgridmatrix[0][3] = -(loadmodel->brushq3.num_lightgrid_imins[0] - 0.5f) / texturesize[0];
6563                         lightgridmatrix[1][3] = -(loadmodel->brushq3.num_lightgrid_imins[1] - 0.5f) / texturesize[1];
6564                         lightgridmatrix[2][3] = -(loadmodel->brushq3.num_lightgrid_imins[2] - 1.5f) / texturesize[2];
6565                         lightgridmatrix[3][3] = 1;
6566                         Matrix4x4_FromArrayDoubleD3D(&loadmodel->brushq3.lightgridworldtotexturematrix, lightgridmatrix[0]);
6567                         loadmodel->brushq3.lightgridtexture = R_LoadTexture3D(loadmodel->texturepool, "lightgrid", texturesize[0], texturesize[1], texturesize[2], texturergba, TEXTYPE_RGBA, TEXF_CLAMP, 0, NULL);
6568                         Mem_Free(texturergba);
6569                 }
6570         }
6571 }
6572
6573 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6574 {
6575         q3dpvs_t *in;
6576         int totalchains;
6577
6578         if (l->filelen == 0)
6579         {
6580                 int i;
6581                 // unvised maps often have cluster indices even without pvs, so check
6582                 // leafs to find real number of clusters
6583                 loadmodel->brush.num_pvsclusters = 1;
6584                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6585                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6586
6587                 // create clusters
6588                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6589                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6590                 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6591                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6592                 return;
6593         }
6594
6595         in = (q3dpvs_t *)(mod_base + l->fileofs);
6596         if (l->filelen < 9)
6597                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6598
6599         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6600         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6601         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6602                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6603         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6604         if (l->filelen < totalchains + (int)sizeof(*in))
6605                 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);
6606
6607         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6608         memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6609 }
6610
6611 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6612 {
6613         int i, j, k, index[3];
6614         float transformed[3], blend1, blend2, blend, stylescale = 1;
6615         q3dlightgrid_t *a, *s;
6616
6617         // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6618         // LadyHavoc: FIXME: is this true?
6619         stylescale = 1; // added while render
6620         //stylescale = r_refdef.scene.rtlightstylevalue[0];
6621
6622         if (!model->brushq3.num_lightgrid)
6623         {
6624                 ambientcolor[0] = stylescale;
6625                 ambientcolor[1] = stylescale;
6626                 ambientcolor[2] = stylescale;
6627                 return;
6628         }
6629
6630         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6631         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6632         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6633         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6634         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6635         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6636         index[0] = (int)floor(transformed[0]);
6637         index[1] = (int)floor(transformed[1]);
6638         index[2] = (int)floor(transformed[2]);
6639         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6640
6641         // now lerp the values
6642         VectorClear(diffusenormal);
6643         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6644         for (k = 0;k < 2;k++)
6645         {
6646                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6647                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6648                         continue;
6649                 for (j = 0;j < 2;j++)
6650                 {
6651                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6652                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6653                                 continue;
6654                         for (i = 0;i < 2;i++)
6655                         {
6656                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6657                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6658                                         continue;
6659                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6660                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6661                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6662                                 // this uses the mod_md3_sin table because the values are
6663                                 // already in the 0-255 range, the 64+ bias fetches a cosine
6664                                 // instead of a sine value
6665                                 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6666                                 diffusenormal[1] += blend * (mod_md3_sin[     s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6667                                 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6668                                 //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)));
6669                         }
6670                 }
6671         }
6672
6673         // normalize the light direction before turning
6674         VectorNormalize(diffusenormal);
6675         //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]);
6676 }
6677
6678 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3], double endpos[3])
6679 {
6680         double t1, t2;
6681         double midf, mid[3];
6682         int ret, side;
6683
6684         // check for empty
6685         while (node->plane)
6686         {
6687                 // find the point distances
6688                 mplane_t *plane = node->plane;
6689                 if (plane->type < 3)
6690                 {
6691                         t1 = p1[plane->type] - plane->dist;
6692                         t2 = p2[plane->type] - plane->dist;
6693                 }
6694                 else
6695                 {
6696                         t1 = DotProduct (plane->normal, p1) - plane->dist;
6697                         t2 = DotProduct (plane->normal, p2) - plane->dist;
6698                 }
6699
6700                 if (t1 < 0)
6701                 {
6702                         if (t2 < 0)
6703                         {
6704                                 node = node->children[1];
6705                                 continue;
6706                         }
6707                         side = 1;
6708                 }
6709                 else
6710                 {
6711                         if (t2 >= 0)
6712                         {
6713                                 node = node->children[0];
6714                                 continue;
6715                         }
6716                         side = 0;
6717                 }
6718
6719                 midf = t1 / (t1 - t2);
6720                 VectorLerp(p1, midf, p2, mid);
6721
6722                 // recurse both sides, front side first
6723                 // return 2 if empty is followed by solid (hit something)
6724                 // do not return 2 if both are solid or both empty,
6725                 // or if start is solid and end is empty
6726                 // as these degenerate cases usually indicate the eye is in solid and
6727                 // should see the target point anyway
6728                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side    ], p1, mid, endpos);
6729                 if (ret != 0)
6730                         return ret;
6731                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2, endpos);
6732                 if (ret != 1)
6733                         return ret;
6734                 VectorCopy(mid, endpos);
6735                 return 2;
6736         }
6737         return ((mleaf_t *)node)->clusterindex < 0;
6738 }
6739
6740 static qbool Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
6741 {
6742         if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6743         {
6744                 trace_t trace;
6745                 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
6746                 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
6747         }
6748         else
6749         {
6750                 double tracestart[3], traceend[3], traceendpos[3];
6751                 VectorCopy(start, tracestart);
6752                 VectorCopy(end, traceend);
6753                 VectorCopy(end, traceendpos);
6754                 Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend, traceendpos);
6755                 return BoxesOverlap(traceendpos, traceendpos, acceptmins, acceptmaxs);
6756         }
6757 }
6758
6759 void Mod_CollisionBIH_TracePoint(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
6760 {
6761         const bih_t *bih;
6762         const bih_leaf_t *leaf;
6763         const bih_node_t *node;
6764         const colbrushf_t *brush;
6765         int axis;
6766         int nodenum;
6767         int nodestackpos = 0;
6768         int nodestack[1024];
6769
6770         memset(trace, 0, sizeof(*trace));
6771         trace->fraction = 1;
6772         trace->hitsupercontentsmask = hitsupercontentsmask;
6773         trace->skipsupercontentsmask = skipsupercontentsmask;
6774         trace->skipmaterialflagsmask = skipmaterialflagsmask;
6775
6776         bih = &model->collision_bih;
6777         if(!bih->nodes)
6778                 return;
6779
6780         nodenum = bih->rootnode;
6781         nodestack[nodestackpos++] = nodenum;
6782         while (nodestackpos)
6783         {
6784                 nodenum = nodestack[--nodestackpos];
6785                 node = bih->nodes + nodenum;
6786 #if 1
6787                 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6788                         continue;
6789 #endif
6790                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6791                 {
6792                         axis = node->type - BIH_SPLITX;
6793                         if (start[axis] >= node->frontmin)
6794                                 nodestack[nodestackpos++] = node->front;
6795                         if (start[axis] <= node->backmax)
6796                                 nodestack[nodestackpos++] = node->back;
6797                 }
6798                 else if (node->type == BIH_UNORDERED)
6799                 {
6800                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6801                         {
6802                                 leaf = bih->leafs + node->children[axis];
6803 #if 1
6804                                 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6805                                         continue;
6806 #endif
6807                                 switch(leaf->type)
6808                                 {
6809                                 case BIH_BRUSH:
6810                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6811                                         Collision_TracePointBrushFloat(trace, start, brush);
6812                                         break;
6813                                 case BIH_COLLISIONTRIANGLE:
6814                                         // collision triangle - skipped because they have no volume
6815                                         break;
6816                                 case BIH_RENDERTRIANGLE:
6817                                         // render triangle - skipped because they have no volume
6818                                         break;
6819                                 }
6820                         }
6821                 }
6822         }
6823 }
6824
6825 static void Mod_CollisionBIH_TraceLineShared(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)
6826 {
6827         const bih_leaf_t *leaf;
6828         const bih_node_t *node;
6829         const colbrushf_t *brush;
6830         const int *e;
6831         const texture_t *texture;
6832         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6833         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6834         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6835
6836         if(!bih->nodes)
6837                 return;
6838
6839         if (VectorCompare(start, end))
6840         {
6841                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6842                 return;
6843         }
6844
6845         nodenum = bih->rootnode;
6846
6847         memset(trace, 0, sizeof(*trace));
6848         trace->fraction = 1;
6849         trace->hitsupercontentsmask = hitsupercontentsmask;
6850         trace->skipsupercontentsmask = skipsupercontentsmask;
6851         trace->skipmaterialflagsmask = skipmaterialflagsmask;
6852
6853         // push first node
6854         nodestackline[nodestackpos][0] = start[0];
6855         nodestackline[nodestackpos][1] = start[1];
6856         nodestackline[nodestackpos][2] = start[2];
6857         nodestackline[nodestackpos][3] = end[0];
6858         nodestackline[nodestackpos][4] = end[1];
6859         nodestackline[nodestackpos][5] = end[2];
6860         nodestack[nodestackpos++] = nodenum;
6861         while (nodestackpos)
6862         {
6863                 nodenum = nodestack[--nodestackpos];
6864                 node = bih->nodes + nodenum;
6865                 VectorCopy(nodestackline[nodestackpos], nodestart);
6866                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6867                 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6868                 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6869                 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6870                 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6871                 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6872                 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6873                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs) && !collision_bih_fullrecursion.integer)
6874                         continue;
6875                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6876                 {
6877                         // recurse children of the split
6878                         axis = node->type - BIH_SPLITX;
6879                         d1 = node->backmax - nodestart[axis];
6880                         d2 = node->backmax - nodeend[axis];
6881                         d3 = nodestart[axis] - node->frontmin;
6882                         d4 = nodeend[axis] - node->frontmin;
6883                         if (collision_bih_fullrecursion.integer)
6884                                 d1 = d2 = d3 = d4 = 1; // force full recursion
6885                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6886                         {
6887                         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;
6888                         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;
6889                         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;
6890                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6891                         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;
6892                         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;
6893                         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;
6894                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6895                         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;
6896                         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;
6897                         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;
6898                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6899                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6900                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6901                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6902                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
6903                         }
6904                 }
6905                 else if (node->type == BIH_UNORDERED)
6906                 {
6907                         // calculate sweep bounds for this node
6908                         // copy node bounds into local variables
6909                         VectorCopy(node->mins, nodebigmins);
6910                         VectorCopy(node->maxs, nodebigmaxs);
6911                         // clip line to this node bounds
6912                         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); }
6913                         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); }
6914                         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); }
6915                         // some of the line intersected the enlarged node box
6916                         // calculate sweep bounds for this node
6917                         sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6918                         sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6919                         sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6920                         sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6921                         sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6922                         sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6923                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6924                         {
6925                                 leaf = bih->leafs + node->children[axis];
6926                                 // TODO: This is very expensive in Steel Storm. Framerate halved during even light combat.
6927                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6928                                         continue;
6929                                 switch(leaf->type)
6930                                 {
6931                                 case BIH_BRUSH:
6932                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6933                                         Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6934                                         break;
6935                                 case BIH_COLLISIONTRIANGLE:
6936                                         if (!mod_q3bsp_curves_collisions.integer)
6937                                                 continue;
6938                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6939                                         texture = model->data_textures + leaf->textureindex;
6940                                         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);
6941                                         break;
6942                                 case BIH_RENDERTRIANGLE:
6943                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6944                                         texture = model->data_textures + leaf->textureindex;
6945                                         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);
6946                                         break;
6947                                 }
6948                         }
6949                 }
6950         }
6951 }
6952
6953 void Mod_CollisionBIH_TraceLine(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)
6954 {
6955         if (VectorCompare(start, end))
6956         {
6957                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6958                 return;
6959         }
6960         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->collision_bih);
6961 }
6962
6963 void Mod_CollisionBIH_TraceBrush(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)
6964 {
6965         const bih_t *bih;
6966         const bih_leaf_t *leaf;
6967         const bih_node_t *node;
6968         const colbrushf_t *brush;
6969         const int *e;
6970         const texture_t *texture;
6971         vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6972         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6973         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6974         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6975
6976         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6977         {
6978                 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6979                         Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6980                 else
6981                         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6982                 return;
6983         }
6984
6985         bih = &model->collision_bih;
6986         if(!bih->nodes)
6987                 return;
6988         nodenum = bih->rootnode;
6989
6990         // box trace, performed as brush trace
6991         memset(trace, 0, sizeof(*trace));
6992         trace->fraction = 1;
6993         trace->hitsupercontentsmask = hitsupercontentsmask;
6994         trace->skipsupercontentsmask = skipsupercontentsmask;
6995         trace->skipmaterialflagsmask = skipmaterialflagsmask;
6996
6997         // calculate tracebox-like parameters for efficient culling
6998         VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6999         VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7000         VectorSubtract(thisbrush_start->mins, start, startmins);
7001         VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7002         VectorSubtract(thisbrush_end->mins, end, endmins);
7003         VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7004         mins[0] = min(startmins[0], endmins[0]);
7005         mins[1] = min(startmins[1], endmins[1]);
7006         mins[2] = min(startmins[2], endmins[2]);
7007         maxs[0] = max(startmaxs[0], endmaxs[0]);
7008         maxs[1] = max(startmaxs[1], endmaxs[1]);
7009         maxs[2] = max(startmaxs[2], endmaxs[2]);
7010
7011         // push first node
7012         nodestackline[nodestackpos][0] = start[0];
7013         nodestackline[nodestackpos][1] = start[1];
7014         nodestackline[nodestackpos][2] = start[2];
7015         nodestackline[nodestackpos][3] = end[0];
7016         nodestackline[nodestackpos][4] = end[1];
7017         nodestackline[nodestackpos][5] = end[2];
7018         nodestack[nodestackpos++] = nodenum;
7019         while (nodestackpos)
7020         {
7021                 nodenum = nodestack[--nodestackpos];
7022                 node = bih->nodes + nodenum;
7023                 VectorCopy(nodestackline[nodestackpos], nodestart);
7024                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7025                 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7026                 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7027                 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7028                 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7029                 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7030                 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7031                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7032                         continue;
7033                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7034                 {
7035                         // recurse children of the split
7036                         axis = node->type - BIH_SPLITX;
7037                         d1 = node->backmax - nodestart[axis] - mins[axis];
7038                         d2 = node->backmax - nodeend[axis] - mins[axis];
7039                         d3 = nodestart[axis] - node->frontmin + maxs[axis];
7040                         d4 = nodeend[axis] - node->frontmin + maxs[axis];
7041                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7042                         {
7043                         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;
7044                         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;
7045                         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;
7046                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7047                         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;
7048                         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;
7049                         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;
7050                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7051                         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;
7052                         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;
7053                         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;
7054                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7055                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7056                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7057                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7058                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
7059                         }
7060                 }
7061                 else if (node->type == BIH_UNORDERED)
7062                 {
7063                         // calculate sweep bounds for this node
7064                         // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7065                         VectorSubtract(node->mins, maxs, nodebigmins);
7066                         VectorSubtract(node->maxs, mins, nodebigmaxs);
7067                         // clip line to this node bounds
7068                         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); }
7069                         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); }
7070                         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); }
7071                         // some of the line intersected the enlarged node box
7072                         // calculate sweep bounds for this node
7073                         sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7074                         sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7075                         sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7076                         sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7077                         sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7078                         sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7079                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7080                         {
7081                                 leaf = bih->leafs + node->children[axis];
7082                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7083                                         continue;
7084                                 switch(leaf->type)
7085                                 {
7086                                 case BIH_BRUSH:
7087                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7088                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7089                                         break;
7090                                 case BIH_COLLISIONTRIANGLE:
7091                                         if (!mod_q3bsp_curves_collisions.integer)
7092                                                 continue;
7093                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7094                                         texture = model->data_textures + leaf->textureindex;
7095                                         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);
7096                                         break;
7097                                 case BIH_RENDERTRIANGLE:
7098                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7099                                         texture = model->data_textures + leaf->textureindex;
7100                                         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);
7101                                         break;
7102                                 }
7103                         }
7104                 }
7105         }
7106 }
7107
7108 void Mod_CollisionBIH_TraceBox(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)
7109 {
7110         colboxbrushf_t thisbrush_start, thisbrush_end;
7111         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7112
7113         // box trace, performed as brush trace
7114         VectorAdd(start, boxmins, boxstartmins);
7115         VectorAdd(start, boxmaxs, boxstartmaxs);
7116         VectorAdd(end, boxmins, boxendmins);
7117         VectorAdd(end, boxmaxs, boxendmaxs);
7118         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7119         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7120         Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7121 }
7122
7123
7124 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7125 {
7126         trace_t trace;
7127         Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0, 0);
7128         return trace.startsupercontents;
7129 }
7130
7131 qbool Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
7132 {
7133         trace_t trace;
7134         Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
7135         return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
7136 }
7137
7138 void Mod_CollisionBIH_TracePoint_Mesh(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7139 {
7140 #if 0
7141         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7142         vec3_t end;
7143         int hitsupercontents;
7144         VectorSet(end, start[0], start[1], model->normalmins[2]);
7145 #endif
7146         memset(trace, 0, sizeof(*trace));
7147         trace->fraction = 1;
7148         trace->hitsupercontentsmask = hitsupercontentsmask;
7149         trace->skipsupercontentsmask = skipsupercontentsmask;
7150         trace->skipmaterialflagsmask = skipmaterialflagsmask;
7151 #if 0
7152         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7153         hitsupercontents = trace->hitsupercontents;
7154         memset(trace, 0, sizeof(*trace));
7155         trace->fraction = 1;
7156         trace->hitsupercontentsmask = hitsupercontentsmask;
7157         trace->skipsupercontentsmask = skipsupercontentsmask;
7158         trace->skipmaterialflagsmask = skipmaterialflagsmask;
7159         trace->startsupercontents = hitsupercontents;
7160 #endif
7161 }
7162
7163 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7164 {
7165 #if 0
7166         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7167         trace_t trace;
7168         vec3_t end;
7169         VectorSet(end, start[0], start[1], model->normalmins[2]);
7170         memset(&trace, 0, sizeof(trace));
7171         trace.fraction = 1;
7172         trace.hitsupercontentsmask = hitsupercontentsmask;
7173         trace.skipsupercontentsmask = skipsupercontentsmask;
7174         trace.skipmaterialflagsmask = skipmaterialflagsmask;
7175         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7176         return trace.hitsupercontents;
7177 #else
7178         return 0;
7179 #endif
7180 }
7181
7182 void Mod_CollisionBIH_TraceLineAgainstSurfaces(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)
7183 {
7184         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->render_bih);
7185 }
7186
7187
7188 bih_t *Mod_MakeCollisionBIH(model_t *model, qbool userendersurfaces, bih_t *out)
7189 {
7190         int j;
7191         int bihnumleafs;
7192         int bihmaxnodes;
7193         int brushindex;
7194         int triangleindex;
7195         int bihleafindex;
7196         int nummodelbrushes = model->nummodelbrushes;
7197         const int *e;
7198         const int *collisionelement3i;
7199         const float *collisionvertex3f;
7200         const int *renderelement3i;
7201         const float *rendervertex3f;
7202         bih_leaf_t *bihleafs;
7203         bih_node_t *bihnodes;
7204         int *temp_leafsort;
7205         int *temp_leafsortscratch;
7206         const msurface_t *surface;
7207         const q3mbrush_t *brush;
7208
7209         // find out how many BIH leaf nodes we need
7210         bihnumleafs = 0;
7211         if (userendersurfaces)
7212         {
7213                 for (j = model->submodelsurfaces_start;j < model->submodelsurfaces_end;j++)
7214                         bihnumleafs += model->data_surfaces[j].num_triangles;
7215         }
7216         else
7217         {
7218                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7219                         if (brush->colbrushf)
7220                                 bihnumleafs++;
7221                 for (j = model->submodelsurfaces_start;j < model->submodelsurfaces_end;j++)
7222                 {
7223                         if (model->data_surfaces[j].texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7224                                 bihnumleafs += model->data_surfaces[j].num_triangles + model->data_surfaces[j].num_collisiontriangles;
7225                         else
7226                                 bihnumleafs += model->data_surfaces[j].num_collisiontriangles;
7227                 }
7228         }
7229
7230         if (!bihnumleafs)
7231                 return NULL;
7232
7233         // allocate the memory for the BIH leaf nodes
7234         bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7235
7236         // now populate the BIH leaf nodes
7237         bihleafindex = 0;
7238
7239         // add render surfaces
7240         renderelement3i = model->surfmesh.data_element3i;
7241         rendervertex3f = model->surfmesh.data_vertex3f;
7242         for (j = model->submodelsurfaces_start; j < model->submodelsurfaces_end; j++)
7243         {
7244                 surface = model->data_surfaces + j;
7245                 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7246                 {
7247                         if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7248                                 continue;
7249                         bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7250                         bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7251                         bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7252                         bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7253                         bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7254                         bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7255                         bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7256                         bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7257                         bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7258                         bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7259                         bihleafindex++;
7260                 }
7261         }
7262
7263         if (!userendersurfaces)
7264         {
7265                 // add collision brushes
7266                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7267                 {
7268                         if (!brush->colbrushf)
7269                                 continue;
7270                         bihleafs[bihleafindex].type = BIH_BRUSH;
7271                         bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7272                         bihleafs[bihleafindex].surfaceindex = -1;
7273                         bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7274                         VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7275                         VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7276                         bihleafindex++;
7277                 }
7278
7279                 // add collision surfaces
7280                 collisionelement3i = model->brush.data_collisionelement3i;
7281                 collisionvertex3f = model->brush.data_collisionvertex3f;
7282                 for (j = model->submodelsurfaces_start; j < model->submodelsurfaces_end; j++)
7283                 {
7284                         surface = model->data_surfaces + j;
7285                         for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7286                         {
7287                                 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7288                                 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7289                                 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7290                                 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7291                                 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7292                                 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7293                                 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7294                                 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7295                                 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7296                                 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7297                                 bihleafindex++;
7298                         }
7299                 }
7300         }
7301
7302         // allocate buffers for the produced and temporary data
7303         bihmaxnodes = bihnumleafs + 1;
7304         bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7305         temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7306         temp_leafsortscratch = temp_leafsort + bihnumleafs;
7307
7308         // now build it
7309         BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7310
7311         // we're done with the temporary data
7312         Mem_Free(temp_leafsort);
7313
7314         // resize the BIH nodes array if it over-allocated
7315         if (out->maxnodes > out->numnodes)
7316         {
7317                 out->maxnodes = out->numnodes;
7318                 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7319         }
7320
7321         return out;
7322 }
7323
7324 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents)
7325 {
7326         int supercontents = 0;
7327         if (nativecontents & CONTENTSQ3_SOLID)
7328                 supercontents |= SUPERCONTENTS_SOLID;
7329         if (nativecontents & CONTENTSQ3_WATER)
7330                 supercontents |= SUPERCONTENTS_WATER;
7331         if (nativecontents & CONTENTSQ3_SLIME)
7332                 supercontents |= SUPERCONTENTS_SLIME;
7333         if (nativecontents & CONTENTSQ3_LAVA)
7334                 supercontents |= SUPERCONTENTS_LAVA;
7335         if (nativecontents & CONTENTSQ3_BODY)
7336                 supercontents |= SUPERCONTENTS_BODY;
7337         if (nativecontents & CONTENTSQ3_CORPSE)
7338                 supercontents |= SUPERCONTENTS_CORPSE;
7339         if (nativecontents & CONTENTSQ3_NODROP)
7340                 supercontents |= SUPERCONTENTS_NODROP;
7341         if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7342                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7343         if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7344                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7345         if (nativecontents & CONTENTSQ3_DONOTENTER)
7346                 supercontents |= SUPERCONTENTS_DONOTENTER;
7347         if (nativecontents & CONTENTSQ3_BOTCLIP)
7348                 supercontents |= SUPERCONTENTS_BOTCLIP;
7349         if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7350                 supercontents |= SUPERCONTENTS_OPAQUE;
7351         return supercontents;
7352 }
7353
7354 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents)
7355 {
7356         int nativecontents = 0;
7357         if (supercontents & SUPERCONTENTS_SOLID)
7358                 nativecontents |= CONTENTSQ3_SOLID;
7359         if (supercontents & SUPERCONTENTS_WATER)
7360                 nativecontents |= CONTENTSQ3_WATER;
7361         if (supercontents & SUPERCONTENTS_SLIME)
7362                 nativecontents |= CONTENTSQ3_SLIME;
7363         if (supercontents & SUPERCONTENTS_LAVA)
7364                 nativecontents |= CONTENTSQ3_LAVA;
7365         if (supercontents & SUPERCONTENTS_BODY)
7366                 nativecontents |= CONTENTSQ3_BODY;
7367         if (supercontents & SUPERCONTENTS_CORPSE)
7368                 nativecontents |= CONTENTSQ3_CORPSE;
7369         if (supercontents & SUPERCONTENTS_NODROP)
7370                 nativecontents |= CONTENTSQ3_NODROP;
7371         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7372                 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7373         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7374                 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7375         if (supercontents & SUPERCONTENTS_DONOTENTER)
7376                 nativecontents |= CONTENTSQ3_DONOTENTER;
7377         if (supercontents & SUPERCONTENTS_BOTCLIP)
7378                 nativecontents |= CONTENTSQ3_BOTCLIP;
7379         if (!(supercontents & SUPERCONTENTS_OPAQUE))
7380                 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7381         return nativecontents;
7382 }
7383
7384 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7385 {
7386         int numleafs;
7387         while (node->plane)
7388         {
7389                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7390                 node = node->children[1];
7391         }
7392         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7393         if (loadmodel->brush.num_leafs < numleafs)
7394                 loadmodel->brush.num_leafs = numleafs;
7395 }
7396
7397 static void Mod_Q3BSP_Load(model_t *mod, void *buffer, void *bufferend)
7398 {
7399         int i, j, lumps;
7400         q3dheader_t *header;
7401         float corner[3], yawradius, modelradius;
7402
7403         mod->modeldatatypestring = "Q3BSP";
7404
7405         mod->type = mod_brushq3;
7406         mod->brush.ishlbsp = false;
7407         mod->brush.isbsp2rmqe = false;
7408         mod->brush.isbsp2 = false;
7409         mod->brush.isq2bsp = false;
7410         mod->brush.isq3bsp = true;
7411         mod->brush.skymasking = true;
7412         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7413         mod->numskins = 1;
7414
7415         header = (q3dheader_t *)buffer;
7416         if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7417                 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7418
7419         i = LittleLong(header->version);
7420         if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7421                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7422
7423         mod->soundfromcenter = true;
7424         mod->TraceBox = Mod_CollisionBIH_TraceBox;
7425         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
7426         mod->TraceLine = Mod_CollisionBIH_TraceLine;
7427         mod->TracePoint = Mod_CollisionBIH_TracePoint;
7428         mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
7429         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7430         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7431         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7432         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7433         mod->brush.GetPVS = Mod_BSP_GetPVS;
7434         mod->brush.FatPVS = Mod_BSP_FatPVS;
7435         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
7436         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
7437         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
7438         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
7439         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7440         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
7441         mod->brush.AmbientSoundLevelsForPoint = NULL;
7442         mod->brush.RoundUpToHullSize = NULL;
7443         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
7444         mod->Draw = R_Mod_Draw;
7445         mod->DrawDepth = R_Mod_DrawDepth;
7446         mod->DrawDebug = R_Mod_DrawDebug;
7447         mod->DrawPrepass = R_Mod_DrawPrepass;
7448         mod->GetLightInfo = R_Mod_GetLightInfo;
7449         mod->CompileShadowMap = R_Mod_CompileShadowMap;
7450         mod->DrawShadowMap = R_Mod_DrawShadowMap;
7451         mod->DrawLight = R_Mod_DrawLight;
7452
7453         mod_base = (unsigned char *)header;
7454
7455         // swap all the lumps
7456         header->ident = LittleLong(header->ident);
7457         header->version = LittleLong(header->version);
7458         lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7459         for (i = 0;i < lumps;i++)
7460         {
7461                 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7462                 if((char *) bufferend < (char *) buffer + j)
7463                         Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7464                 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7465                 if((char *) bufferend < (char *) buffer + j)
7466                         Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7467         }
7468         /*
7469          * NO, do NOT clear them!
7470          * they contain actual data referenced by other stuff.
7471          * Instead, before using the advertisements lump, check header->versio
7472          * again!
7473          * Sorry, but otherwise it breaks memory of the first lump.
7474         for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7475         {
7476                 header->lumps[i].fileofs = 0;
7477                 header->lumps[i].filelen = 0;
7478         }
7479         */
7480
7481         mod->brush.qw_md4sum = 0;
7482         mod->brush.qw_md4sum2 = 0;
7483         for (i = 0;i < lumps;i++)
7484         {
7485                 if (i == Q3LUMP_ENTITIES)
7486                         continue;
7487                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7488                 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7489                         continue;
7490                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7491
7492                 // all this checksumming can take a while, so let's send keepalives here too
7493                 CL_KeepaliveMessage(false);
7494         }
7495
7496         // allocate a texture pool if we need it
7497         if (mod->texturepool == NULL)
7498                 mod->texturepool = R_AllocTexturePool();
7499
7500         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7501         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7502         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7503         if (header->version == Q3BSPVERSION_IG)
7504                 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7505         else
7506                 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7507         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7508         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7509         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7510         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7511         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7512         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7513         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7514         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7515         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7516         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7517         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7518         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7519         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7520         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7521
7522         // the MakePortals code works fine on the q3bsp data as well
7523         if (mod_bsp_portalize.integer)
7524                 Mod_BSP_MakePortals();
7525
7526         // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7527         loadmodel->brush.supportwateralpha = true;
7528
7529         loadmodel->brush.num_leafs = 0;
7530         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7531
7532         if (loadmodel->brush.numsubmodels)
7533                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
7534
7535         mod = loadmodel;
7536         mod->modelsurfaces_sorted = (int*)Mem_Alloc(loadmodel->mempool, mod->num_surfaces * sizeof(*mod->modelsurfaces_sorted));
7537         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7538         {
7539                 if (i > 0)
7540                 {
7541                         char name[10];
7542                         // duplicate the basic information
7543                         dpsnprintf(name, sizeof(name), "*%i", i);
7544                         mod = Mod_FindName(name, loadmodel->name);
7545                         // copy the base model to this one
7546                         *mod = *loadmodel;
7547                         // rename the clone back to its proper name
7548                         strlcpy(mod->name, name, sizeof(mod->name));
7549                         mod->brush.parentmodel = loadmodel;
7550                         // textures and memory belong to the main model
7551                         mod->texturepool = NULL;
7552                         mod->mempool = NULL;
7553                         mod->brush.GetPVS = NULL;
7554                         mod->brush.FatPVS = NULL;
7555                         mod->brush.BoxTouchingPVS = NULL;
7556                         mod->brush.BoxTouchingLeafPVS = NULL;
7557                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7558                         mod->brush.FindBoxClusters = NULL;
7559                         mod->brush.LightPoint = NULL;
7560                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7561                 }
7562                 mod->brush.submodel = i;
7563                 if (loadmodel->brush.submodels)
7564                         loadmodel->brush.submodels[i] = mod;
7565
7566                 // make the model surface list (used by shadowing/lighting)
7567                 mod->submodelsurfaces_start = mod->brushq3.data_models[i].firstface;
7568                 mod->submodelsurfaces_end = mod->brushq3.data_models[i].firstface + mod->brushq3.data_models[i].numfaces;
7569                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7570                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7571
7572                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7573                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7574                 // enlarge the bounding box to enclose all geometry of this model,
7575                 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7576                 // which can in turn mess up the farclip (as well as culling when
7577                 // outside the level - an unimportant concern)
7578
7579                 //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]);
7580                 for (j = mod->submodelsurfaces_start;j < mod->submodelsurfaces_end;j++)
7581                 {
7582                         const msurface_t *surface = mod->data_surfaces + j;
7583                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7584                         int k;
7585                         if (!surface->num_vertices)
7586                                 continue;
7587                         for (k = 0;k < surface->num_vertices;k++, v += 3)
7588                         {
7589                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7590                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7591                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7592                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7593                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7594                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7595                         }
7596                 }
7597                 //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]);
7598                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7599                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7600                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7601                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7602                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7603                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7604                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7605                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7606                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7607                 mod->yawmins[2] = mod->normalmins[2];
7608                 mod->yawmaxs[2] = mod->normalmaxs[2];
7609                 mod->radius = modelradius;
7610                 mod->radius2 = modelradius * modelradius;
7611
7612                 Mod_SetDrawSkyAndWater(mod);
7613                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7614                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7615
7616                 // generate VBOs and other shared data before cloning submodels
7617                 if (i == 0)
7618                         Mod_BuildVBOs();
7619         }
7620         mod = loadmodel;
7621
7622         // make the model surface list (used by shadowing/lighting)
7623         Mod_MakeSortedSurfaces(loadmodel);
7624
7625         if (mod_q3bsp_sRGBlightmaps.integer)
7626         {
7627                 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7628                 {
7629                         // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7630                         // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7631                         // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7632                         // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7633                         //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7634                 }
7635                 else // if this is NOT set, regular rendering looks right by this requirement anyway
7636                 {
7637                         /*
7638                         // we want color 1 to do the same as without sRGB
7639                         // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7640                         loadmodel->lightmapscale *= 2.476923f; // fixes max level
7641                         */
7642
7643                         // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7644                         // we need to undo that
7645                         loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7646                 }
7647         }
7648
7649         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);
7650 }
7651
7652 void Mod_IBSP_Load(model_t *mod, void *buffer, void *bufferend)
7653 {
7654         int i = LittleLong(((int *)buffer)[1]);
7655         if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7656                 Mod_Q3BSP_Load(mod,buffer, bufferend);
7657         else if (i == Q2BSPVERSION)
7658                 Mod_Q2BSP_Load(mod,buffer, bufferend);
7659         else
7660                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7661 }
7662
7663 static void Mod_VBSP_LoadEntities(sizebuf_t *sb)
7664 {
7665         loadmodel->brush.entities = NULL;
7666         if (!sb->cursize)
7667                 return;
7668         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
7669         MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
7670         loadmodel->brush.entities[sb->cursize] = 0;
7671 }
7672
7673 static void Mod_VBSP_LoadVertexes(sizebuf_t *sb)
7674 {
7675         mvertex_t       *out;
7676         int                     i, count;
7677         int                     structsize = 12;
7678
7679         if (sb->cursize % structsize)
7680                 Host_Error("Mod_VBSP_LoadVertexes: funny lump size in %s",loadmodel->name);
7681         count = sb->cursize / structsize;
7682         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
7683
7684         loadmodel->brushq1.vertexes = out;
7685         loadmodel->brushq1.numvertexes = count;
7686
7687         for ( i=0 ; i<count ; i++, out++)
7688         {
7689                 out->position[0] = MSG_ReadLittleFloat(sb);
7690                 out->position[1] = MSG_ReadLittleFloat(sb);
7691                 out->position[2] = MSG_ReadLittleFloat(sb);
7692         }
7693 }
7694
7695 static void Mod_VBSP_LoadEdges(sizebuf_t *sb)
7696 {
7697         medge_t *out;
7698         int     i, count;
7699         int             structsize = 4;
7700
7701         if (sb->cursize % structsize)
7702                 Host_Error("Mod_VBSP_LoadEdges: funny lump size in %s",loadmodel->name);
7703         count = sb->cursize / structsize;
7704         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
7705
7706         loadmodel->brushq1.edges = out;
7707         loadmodel->brushq1.numedges = count;
7708
7709         for ( i=0 ; i<count ; i++, out++)
7710         {
7711                 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
7712                 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
7713                 
7714                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
7715                 {
7716                         Con_Printf("Mod_VBSP_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);
7717                         if(!loadmodel->brushq1.numvertexes)
7718                                 Host_Error("Mod_VBSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
7719                                 
7720                         out->v[0] = 0;
7721                         out->v[1] = 0;
7722                 }
7723         }
7724 }
7725
7726 static void Mod_VBSP_LoadSurfedges(sizebuf_t *sb)
7727 {
7728         int             i;
7729         int structsize = 4;
7730
7731         if (sb->cursize % structsize)
7732                 Host_Error("Mod_VBSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
7733         loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
7734         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
7735
7736         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
7737                 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
7738 }
7739
7740 static void Mod_VBSP_LoadTextures(sizebuf_t *sb)
7741 {
7742         Con_Printf(CON_WARN "Mod_VBSP_LoadTextures: Don't know how to do this yet\n");
7743 }
7744
7745 static void Mod_VBSP_LoadPlanes(sizebuf_t *sb)
7746 {
7747         int                     i;
7748         mplane_t        *out;
7749         int structsize = 20;
7750
7751         if (sb->cursize % structsize)
7752                 Host_Error("Mod_VBSP_LoadPlanes: funny lump size in %s", loadmodel->name);
7753         loadmodel->brush.num_planes = sb->cursize / structsize;
7754         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
7755
7756         for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
7757         {
7758                 out->normal[0] = MSG_ReadLittleFloat(sb);
7759                 out->normal[1] = MSG_ReadLittleFloat(sb);
7760                 out->normal[2] = MSG_ReadLittleFloat(sb);
7761                 out->dist = MSG_ReadLittleFloat(sb);
7762                 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
7763                 PlaneClassify(out);
7764         }
7765 }
7766
7767 static void Mod_VBSP_LoadTexinfo(sizebuf_t *sb)
7768 {
7769         mtexinfo_t *out;
7770         int i, j, k, count, miptex;
7771         int structsize = 72;
7772
7773         if (sb->cursize % structsize)
7774                 Host_Error("Mod_VBSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
7775         count = sb->cursize / structsize;
7776         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
7777
7778         loadmodel->brushq1.texinfo = out;
7779         loadmodel->brushq1.numtexinfo = count;
7780
7781         for (i = 0;i < count;i++, out++)
7782         {
7783                 for (k = 0;k < 2;k++)
7784                         for (j = 0;j < 4;j++)
7785                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
7786
7787                 for (k = 0;k < 2;k++)
7788                         for (j = 0;j < 4;j++)
7789                                 MSG_ReadLittleFloat(sb); // TODO lightmapVecs
7790
7791                 out->q1flags = MSG_ReadLittleLong(sb);
7792                 miptex = MSG_ReadLittleLong(sb);
7793
7794                 if (out->q1flags & TEX_SPECIAL)
7795                 {
7796                         // if texture chosen is NULL or the shader needs a lightmap,
7797                         // force to notexture water shader
7798                         out->textureindex = loadmodel->num_textures - 1;
7799                 }
7800                 else
7801                 {
7802                         // if texture chosen is NULL, force to notexture
7803                         out->textureindex = loadmodel->num_textures - 2;
7804                 }
7805                 // see if the specified miptex is valid and try to use it instead
7806                 if (loadmodel->data_textures)
7807                 {
7808                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
7809                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
7810                         else
7811                                 out->textureindex = miptex;
7812                 }
7813         }
7814 }
7815
7816 static void Mod_VBSP_LoadFaces(sizebuf_t *sb)
7817 {
7818         msurface_t *surface;
7819         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
7820         float texmins[2], texmaxs[2], val;
7821         rtexture_t *lightmaptexture, *deluxemaptexture;
7822         char vabuf[1024];
7823         int structsize =  56;
7824
7825         if (sb->cursize % structsize)
7826                 Host_Error("Mod_VBSP_LoadFaces: funny lump size in %s",loadmodel->name);
7827         count = sb->cursize / structsize;
7828         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
7829         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
7830
7831         loadmodel->num_surfaces = count;
7832
7833         loadmodel->brushq1.firstrender = true;
7834         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
7835
7836         totalverts = 0;
7837         totaltris = 0;
7838         for (surfacenum = 0;surfacenum < count;surfacenum++)
7839         {
7840                 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
7841                 totalverts += numedges;
7842                 totaltris += numedges - 2;
7843         }
7844
7845         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
7846
7847         lightmaptexture = NULL;
7848         deluxemaptexture = r_texture_blanknormalmap;
7849         lightmapnumber = 0;
7850         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
7851         totallightmapsamples = 0;
7852
7853         totalverts = 0;
7854         totaltris = 0;
7855         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
7856         {
7857                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
7858                 planenum = (unsigned short)MSG_ReadLittleShort(sb);
7859                 /*side = */MSG_ReadLittleShort(sb); // TODO support onNode?
7860                 firstedge = MSG_ReadLittleLong(sb);
7861                 numedges = (unsigned short)MSG_ReadLittleShort(sb);
7862                 texinfoindex = (unsigned short)MSG_ReadLittleShort(sb);
7863                 MSG_ReadLittleLong(sb); // skipping over dispinfo and surfaceFogVolumeID, both short
7864                 for (i = 0;i < MAXLIGHTMAPS;i++)
7865                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
7866                 lightmapoffset = MSG_ReadLittleLong(sb);
7867
7868                 // FIXME: validate edges, texinfo, etc?
7869                 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)
7870                         Host_Error("Mod_VBSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
7871                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
7872                         Host_Error("Mod_VBSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
7873                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
7874                         Host_Error("Mod_VBSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
7875
7876                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
7877                 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
7878
7879                 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
7880                 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
7881                         lightmapoffset = -1;
7882
7883                 //surface->flags = surface->texture->flags;
7884                 //if (LittleShort(in->side))
7885                 //      surface->flags |= SURF_PLANEBACK;
7886                 //surface->plane = loadmodel->brush.data_planes + planenum;
7887
7888                 surface->num_firstvertex = totalverts;
7889                 surface->num_vertices = numedges;
7890                 surface->num_firsttriangle = totaltris;
7891                 surface->num_triangles = numedges - 2;
7892                 totalverts += numedges;
7893                 totaltris += numedges - 2;
7894
7895                 // convert edges back to a normal polygon
7896                 for (i = 0;i < surface->num_vertices;i++)
7897                 {
7898                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
7899                         float s, t;
7900                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
7901                         if (lindex >= 0)
7902                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
7903                         else
7904                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
7905                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
7906                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
7907                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
7908                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
7909                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
7910                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
7911                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
7912                 }
7913
7914                 for (i = 0;i < surface->num_triangles;i++)
7915                 {
7916                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
7917                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
7918                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
7919                 }
7920
7921                 // compile additional data about the surface geometry
7922                 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);
7923                 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);
7924                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
7925
7926                 // generate surface extents information
7927                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
7928                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
7929                 for (i = 1;i < surface->num_vertices;i++)
7930                 {
7931                         for (j = 0;j < 2;j++)
7932                         {
7933                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
7934                                 texmins[j] = min(texmins[j], val);
7935                                 texmaxs[j] = max(texmaxs[j], val);
7936                         }
7937                 }
7938                 for (i = 0;i < 2;i++)
7939                 {
7940                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
7941                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
7942                 }
7943
7944                 smax = surface->lightmapinfo->extents[0] >> 4;
7945                 tmax = surface->lightmapinfo->extents[1] >> 4;
7946                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
7947                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
7948
7949                 // lighting info
7950                 surface->lightmaptexture = NULL;
7951                 surface->deluxemaptexture = r_texture_blanknormalmap;
7952                 if (lightmapoffset == -1)
7953                 {
7954                         surface->lightmapinfo->samples = NULL;
7955 #if 1
7956                         // give non-lightmapped water a 1x white lightmap
7957                         if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
7958                         {
7959                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
7960                                 surface->lightmapinfo->styles[0] = 0;
7961                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
7962                         }
7963 #endif
7964                 }
7965                 else
7966                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
7967
7968                 // check if we should apply a lightmap to this
7969                 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
7970                 {
7971                         if (ssize > 256 || tsize > 256)
7972                                 Host_Error("Bad surface extents");
7973
7974                         if (lightmapsize < ssize)
7975                                 lightmapsize = ssize;
7976                         if (lightmapsize < tsize)
7977                                 lightmapsize = tsize;
7978
7979                         totallightmapsamples += ssize*tsize;
7980
7981                         // force lightmap upload on first time seeing the surface
7982                         //
7983                         // additionally this is used by the later code to see if a
7984                         // lightmap is needed on this surface (rather than duplicating the
7985                         // logic above)
7986                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
7987                         loadmodel->lit = true;
7988                 }
7989         }
7990
7991         // small maps (such as ammo boxes especially) don't need big lightmap
7992         // textures, so this code tries to guess a good size based on
7993         // totallightmapsamples (size of the lightmaps lump basically), as well as
7994         // trying to max out the size if there is a lot of lightmap data to store
7995         // additionally, never choose a lightmapsize that is smaller than the
7996         // largest surface encountered (as it would fail)
7997         i = lightmapsize;
7998         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
7999                 ;
8000
8001         // now that we've decided the lightmap texture size, we can do the rest
8002         if (cls.state != ca_dedicated)
8003         {
8004                 int stainmapsize = 0;
8005                 mod_alloclightmap_state_t allocState;
8006
8007                 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
8008                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
8009                 {
8010                         int iu, iv, lightmapx = 0, lightmapy = 0;
8011                         float u, v, ubase, vbase, uscale, vscale;
8012
8013                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
8014                                 continue;
8015
8016                         smax = surface->lightmapinfo->extents[0] >> 4;
8017                         tmax = surface->lightmapinfo->extents[1] >> 4;
8018                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
8019                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
8020                         stainmapsize += ssize * tsize * 3;
8021
8022                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
8023                         {
8024                                 // allocate a texture pool if we need it
8025                                 if (loadmodel->texturepool == NULL)
8026                                         loadmodel->texturepool = R_AllocTexturePool();
8027                                 // could not find room, make a new lightmap
8028                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
8029                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
8030                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
8031                                 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);
8032                                 if (loadmodel->brushq1.nmaplightdata)
8033                                         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);
8034                                 lightmapnumber++;
8035                                 Mod_AllocLightmap_Reset(&allocState);
8036                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
8037                         }
8038                         surface->lightmaptexture = lightmaptexture;
8039                         surface->deluxemaptexture = deluxemaptexture;
8040                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
8041                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
8042
8043                         uscale = 1.0f / (float)lightmapsize;
8044                         vscale = 1.0f / (float)lightmapsize;
8045                         ubase = lightmapx * uscale;
8046                         vbase = lightmapy * vscale;
8047
8048                         for (i = 0;i < surface->num_vertices;i++)
8049                         {
8050                                 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);
8051                                 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);
8052                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
8053                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
8054                                 // LadyHavoc: calc lightmap data offset for vertex lighting to use
8055                                 iu = (int) u;
8056                                 iv = (int) v;
8057                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
8058                         }
8059                 }
8060
8061                 if (cl_stainmaps.integer)
8062                 {
8063                         // allocate stainmaps for permanent marks on walls and clear white
8064                         unsigned char *stainsamples = NULL;
8065                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
8066                         memset(stainsamples, 255, stainmapsize);
8067                         // assign pointers
8068                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
8069                         {
8070                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
8071                                         continue;
8072                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
8073                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
8074                                 surface->lightmapinfo->stainsamples = stainsamples;
8075                                 stainsamples += ssize * tsize * 3;
8076                         }
8077                 }
8078         }
8079
8080         // generate ushort elements array if possible
8081         if (loadmodel->surfmesh.data_element3s)
8082                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8083                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8084 }
8085
8086 // Valve BSP loader
8087 // Cloudwalk: Wasn't sober when I wrote this. I screamed and ran away at the face loader
8088 void Mod_VBSP_Load(model_t *mod, void *buffer, void *bufferend)
8089 {
8090         static cvar_t *testing = NULL; // TEMPORARY
8091         int i;
8092         sizebuf_t sb;
8093         sizebuf_t lumpsb[HL2HEADER_LUMPS];
8094
8095         if(!testing || !testing->integer)
8096         {
8097                 if(!testing)
8098                         testing = Cvar_Get(&cvars_all, "mod_bsp_vbsptest", "0", CF_CLIENT | CF_SERVER, "uhhh");
8099                 Host_Error("Mod_VBSP_Load: not yet fully implemented. Change the now-generated \"mod_bsp_vbsptest\" to 1 if you wish to test this");
8100         }
8101         else
8102         {
8103
8104                 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
8105
8106                 mod->type = mod_brushhl2;
8107
8108                 MSG_ReadLittleLong(&sb);
8109                 MSG_ReadLittleLong(&sb); // TODO version check
8110
8111                 mod->modeldatatypestring = "VBSP";
8112
8113                 // read lumps
8114                 for (i = 0; i < HL2HEADER_LUMPS; i++)
8115                 {
8116                         int offset = MSG_ReadLittleLong(&sb);
8117                         int size = MSG_ReadLittleLong(&sb);
8118                         MSG_ReadLittleLong(&sb); // TODO support version
8119                         MSG_ReadLittleLong(&sb); // TODO support ident
8120                         if (offset < 0 || offset + size > sb.cursize)
8121                                 Host_Error("Mod_VBSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
8122                         MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
8123                 }
8124
8125                 MSG_ReadLittleLong(&sb); // TODO support revision field
8126
8127                 mod->soundfromcenter = true;
8128                 mod->TraceBox = Mod_CollisionBIH_TraceBox;
8129                 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
8130                 mod->TraceLine = Mod_CollisionBIH_TraceLine;
8131                 mod->TracePoint = Mod_CollisionBIH_TracePoint;
8132                 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
8133                 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8134                 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight; // probably not correct
8135                 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents; // probably not correct
8136                 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents; // probably not correct
8137                 mod->brush.GetPVS = Mod_BSP_GetPVS;
8138                 mod->brush.FatPVS = Mod_BSP_FatPVS;
8139                 mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
8140                 mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
8141                 mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
8142                 mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
8143                 mod->brush.LightPoint = Mod_Q3BSP_LightPoint; // probably not correct
8144                 mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
8145                 mod->brush.AmbientSoundLevelsForPoint = NULL;
8146                 mod->brush.RoundUpToHullSize = NULL;
8147                 mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
8148                 mod->Draw = R_Mod_Draw;
8149                 mod->DrawDepth = R_Mod_DrawDepth;
8150                 mod->DrawDebug = R_Mod_DrawDebug;
8151                 mod->DrawPrepass = R_Mod_DrawPrepass;
8152                 mod->GetLightInfo = R_Mod_GetLightInfo;
8153                 mod->CompileShadowMap = R_Mod_CompileShadowMap;
8154                 mod->DrawShadowMap = R_Mod_DrawShadowMap;
8155                 mod->DrawLight = R_Mod_DrawLight;
8156
8157                 // allocate a texture pool if we need it
8158                 if (mod->texturepool == NULL)
8159                         mod->texturepool = R_AllocTexturePool();
8160
8161                 Mod_VBSP_LoadEntities(&lumpsb[HL2LUMP_ENTITIES]);
8162                 Mod_VBSP_LoadVertexes(&lumpsb[HL2LUMP_VERTEXES]);
8163                 Mod_VBSP_LoadEdges(&lumpsb[HL2LUMP_EDGES]);
8164                 Mod_VBSP_LoadSurfedges(&lumpsb[HL2LUMP_SURFEDGES]);
8165                 Mod_VBSP_LoadTextures(&lumpsb[HL2LUMP_TEXDATA/*?*/]);
8166                 //Mod_VBSP_LoadLighting(&lumpsb[HL2LUMP_LIGHTING]);
8167                 Mod_VBSP_LoadPlanes(&lumpsb[HL2LUMP_PLANES]);
8168                 Mod_VBSP_LoadTexinfo(&lumpsb[HL2LUMP_TEXINFO]);
8169
8170                 // AHHHHHHH
8171                 Mod_VBSP_LoadFaces(&lumpsb[HL2LUMP_FACES]);
8172         }
8173 }
8174
8175 void Mod_MAP_Load(model_t *mod, void *buffer, void *bufferend)
8176 {
8177         Host_Error("Mod_MAP_Load: not yet implemented");
8178 }
8179
8180 typedef struct objvertex_s
8181 {
8182         int nextindex;
8183         int submodelindex;
8184         int textureindex;
8185         float v[3];
8186         float vt[2];
8187         float vn[3];
8188 }
8189 objvertex_t;
8190
8191 static unsigned char nobsp_pvs[1] = {1};
8192
8193 void Mod_OBJ_Load(model_t *mod, void *buffer, void *bufferend)
8194 {
8195         const char *textbase = (char *)buffer, *text = textbase;
8196         char *s;
8197         char *argv[512];
8198         char line[1024];
8199         char materialname[MAX_QPATH];
8200         int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8201         int index1, index2, index3;
8202         objvertex_t vfirst, vprev, vcurrent;
8203         int argc;
8204         int linelen;
8205         int numtriangles = 0;
8206         int maxtriangles = 0;
8207         objvertex_t *vertices = NULL;
8208         int linenumber = 0;
8209         int maxtextures = 0, numtextures = 0, textureindex = 0;
8210         int maxv = 0, numv = 1;
8211         int maxvt = 0, numvt = 1;
8212         int maxvn = 0, numvn = 1;
8213         char *texturenames = NULL;
8214         float dist, modelradius, modelyawradius, yawradius;
8215         float *obj_v = NULL;
8216         float *obj_vt = NULL;
8217         float *obj_vn = NULL;
8218         float mins[3];
8219         float maxs[3];
8220         float corner[3];
8221         objvertex_t *thisvertex = NULL;
8222         int vertexhashindex;
8223         int *vertexhashtable = NULL;
8224         objvertex_t *vertexhashdata = NULL;
8225         objvertex_t *vdata = NULL;
8226         int vertexhashsize = 0;
8227         int vertexhashcount = 0;
8228         skinfile_t *skinfiles = NULL;
8229         unsigned char *data = NULL;
8230         int *submodelfirstsurface;
8231         msurface_t *tempsurface;
8232         msurface_t *tempsurfaces;
8233
8234         memset(&vfirst, 0, sizeof(vfirst));
8235         memset(&vprev, 0, sizeof(vprev));
8236         memset(&vcurrent, 0, sizeof(vcurrent));
8237
8238         dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8239
8240         loadmodel->modeldatatypestring = "OBJ";
8241
8242         loadmodel->type = mod_obj;
8243         loadmodel->soundfromcenter = true;
8244         loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8245         loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8246         loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8247         loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8248         loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8249         loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8250         loadmodel->brush.TraceLineOfSight = NULL;
8251         loadmodel->brush.SuperContentsFromNativeContents = NULL;
8252         loadmodel->brush.NativeContentsFromSuperContents = NULL;
8253         loadmodel->brush.GetPVS = NULL;
8254         loadmodel->brush.FatPVS = NULL;
8255         loadmodel->brush.BoxTouchingPVS = NULL;
8256         loadmodel->brush.BoxTouchingLeafPVS = NULL;
8257         loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8258         loadmodel->brush.FindBoxClusters = NULL;
8259         loadmodel->brush.LightPoint = NULL;
8260         loadmodel->brush.FindNonSolidLocation = NULL;
8261         loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8262         loadmodel->brush.RoundUpToHullSize = NULL;
8263         loadmodel->brush.PointInLeaf = NULL;
8264         loadmodel->Draw = R_Mod_Draw;
8265         loadmodel->DrawDepth = R_Mod_DrawDepth;
8266         loadmodel->DrawDebug = R_Mod_DrawDebug;
8267         loadmodel->DrawPrepass = R_Mod_DrawPrepass;
8268         loadmodel->GetLightInfo = R_Mod_GetLightInfo;
8269         loadmodel->CompileShadowMap = R_Mod_CompileShadowMap;
8270         loadmodel->DrawShadowMap = R_Mod_DrawShadowMap;
8271         loadmodel->DrawLight = R_Mod_DrawLight;
8272
8273         skinfiles = Mod_LoadSkinFiles();
8274         if (loadmodel->numskins < 1)
8275                 loadmodel->numskins = 1;
8276
8277         // make skinscenes for the skins (no groups)
8278         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8279         for (i = 0;i < loadmodel->numskins;i++)
8280         {
8281                 loadmodel->skinscenes[i].firstframe = i;
8282                 loadmodel->skinscenes[i].framecount = 1;
8283                 loadmodel->skinscenes[i].loop = true;
8284                 loadmodel->skinscenes[i].framerate = 10;
8285         }
8286
8287         VectorClear(mins);
8288         VectorClear(maxs);
8289
8290         // we always have model 0, i.e. the first "submodel"
8291         loadmodel->brush.numsubmodels = 1;
8292
8293         // parse the OBJ text now
8294         for(;;)
8295         {
8296                 static char emptyarg[1] = "";
8297                 if (!*text)
8298                         break;
8299                 linenumber++;
8300                 linelen = 0;
8301                 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8302                         line[linelen] = text[linelen];
8303                 line[linelen] = 0;
8304                 for (argc = 0;argc < 4;argc++)
8305                         argv[argc] = emptyarg;
8306                 argc = 0;
8307                 s = line;
8308                 while (*s == ' ' || *s == '\t')
8309                         s++;
8310                 while (*s)
8311                 {
8312                         argv[argc++] = s;
8313                         while (*s > ' ')
8314                                 s++;
8315                         if (!*s)
8316                                 break;
8317                         *s++ = 0;
8318                         while (*s == ' ' || *s == '\t')
8319                                 s++;
8320                 }
8321                 text += linelen;
8322                 if (*text == '\r')
8323                         text++;
8324                 if (*text == '\n')
8325                         text++;
8326                 if (!argc)
8327                         continue;
8328                 if (argv[0][0] == '#')
8329                         continue;
8330                 if (!strcmp(argv[0], "v"))
8331                 {
8332                         if (maxv <= numv)
8333                         {
8334                                 maxv = max(maxv * 2, 1024);
8335                                 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8336                         }
8337                         if(mod_obj_orientation.integer)
8338                         {
8339                                 obj_v[numv*3+0] = atof(argv[1]);
8340                                 obj_v[numv*3+2] = atof(argv[2]);
8341                                 obj_v[numv*3+1] = atof(argv[3]);
8342                         }
8343                         else
8344                         {
8345                                 obj_v[numv*3+0] = atof(argv[1]);
8346                                 obj_v[numv*3+1] = atof(argv[2]);
8347                                 obj_v[numv*3+2] = atof(argv[3]);
8348                         }
8349                         numv++;
8350                 }
8351                 else if (!strcmp(argv[0], "vt"))
8352                 {
8353                         if (maxvt <= numvt)
8354                         {
8355                                 maxvt = max(maxvt * 2, 1024);
8356                                 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8357                         }
8358                         obj_vt[numvt*2+0] = atof(argv[1]);
8359                         obj_vt[numvt*2+1] = 1-atof(argv[2]);
8360                         numvt++;
8361                 }
8362                 else if (!strcmp(argv[0], "vn"))
8363                 {
8364                         if (maxvn <= numvn)
8365                         {
8366                                 maxvn = max(maxvn * 2, 1024);
8367                                 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8368                         }
8369                         if(mod_obj_orientation.integer)
8370                         {
8371                                 obj_vn[numvn*3+0] = atof(argv[1]);
8372                                 obj_vn[numvn*3+2] = atof(argv[2]);
8373                                 obj_vn[numvn*3+1] = atof(argv[3]);
8374                         }
8375                         else
8376                         {
8377                                 obj_vn[numvn*3+0] = atof(argv[1]);
8378                                 obj_vn[numvn*3+1] = atof(argv[2]);
8379                                 obj_vn[numvn*3+2] = atof(argv[3]);
8380                         }
8381                         numvn++;
8382                 }
8383                 else if (!strcmp(argv[0], "f"))
8384                 {
8385                         if (!numtextures)
8386                         {
8387                                 if (maxtextures <= numtextures)
8388                                 {
8389                                         maxtextures = max(maxtextures * 2, 256);
8390                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8391                                 }
8392                                 textureindex = numtextures++;
8393                                 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8394                         }
8395                         for (j = 1;j < argc;j++)
8396                         {
8397                                 index1 = atoi(argv[j]);
8398                                 while(argv[j][0] && argv[j][0] != '/')
8399                                         argv[j]++;
8400                                 if (argv[j][0])
8401                                         argv[j]++;
8402                                 index2 = atoi(argv[j]);
8403                                 while(argv[j][0] && argv[j][0] != '/')
8404                                         argv[j]++;
8405                                 if (argv[j][0])
8406                                         argv[j]++;
8407                                 index3 = atoi(argv[j]);
8408                                 // negative refers to a recent vertex
8409                                 // zero means not specified
8410                                 // positive means an absolute vertex index
8411                                 if (index1 < 0)
8412                                         index1 = numv - index1;
8413                                 if (index2 < 0)
8414                                         index2 = numvt - index2;
8415                                 if (index3 < 0)
8416                                         index3 = numvn - index3;
8417                                 vcurrent.nextindex = -1;
8418                                 vcurrent.textureindex = textureindex;
8419                                 vcurrent.submodelindex = submodelindex;
8420                                 if (obj_v && index1 >= 0 && index1 < numv)
8421                                         VectorCopy(obj_v + 3*index1, vcurrent.v);
8422                                 if (obj_vt && index2 >= 0 && index2 < numvt)
8423                                         Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8424                                 if (obj_vn && index3 >= 0 && index3 < numvn)
8425                                         VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8426                                 if (numtriangles == 0)
8427                                 {
8428                                         VectorCopy(vcurrent.v, mins);
8429                                         VectorCopy(vcurrent.v, maxs);
8430                                 }
8431                                 else
8432                                 {
8433                                         mins[0] = min(mins[0], vcurrent.v[0]);
8434                                         mins[1] = min(mins[1], vcurrent.v[1]);
8435                                         mins[2] = min(mins[2], vcurrent.v[2]);
8436                                         maxs[0] = max(maxs[0], vcurrent.v[0]);
8437                                         maxs[1] = max(maxs[1], vcurrent.v[1]);
8438                                         maxs[2] = max(maxs[2], vcurrent.v[2]);
8439                                 }
8440                                 if (j == 1)
8441                                         vfirst = vcurrent;
8442                                 else if (j >= 3)
8443                                 {
8444                                         if (maxtriangles <= numtriangles)
8445                                         {
8446                                                 maxtriangles = max(maxtriangles * 2, 32768);
8447                                                 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8448                                         }
8449                                         if(mod_obj_orientation.integer)
8450                                         {
8451                                                 vertices[numtriangles*3+0] = vfirst;
8452                                                 vertices[numtriangles*3+1] = vprev;
8453                                                 vertices[numtriangles*3+2] = vcurrent;
8454                                         }
8455                                         else
8456                                         {
8457                                                 vertices[numtriangles*3+0] = vfirst;
8458                                                 vertices[numtriangles*3+2] = vprev;
8459                                                 vertices[numtriangles*3+1] = vcurrent;
8460                                         }
8461                                         numtriangles++;
8462                                 }
8463                                 vprev = vcurrent;
8464                         }
8465                 }
8466                 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8467                 {
8468                         submodelindex = atof(argv[1]);
8469                         loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8470                 }
8471                 else if (!strcmp(argv[0], "usemtl"))
8472                 {
8473                         for (i = 0;i < numtextures;i++)
8474                                 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8475                                         break;
8476                         if (i < numtextures)
8477                                 textureindex = i;
8478                         else
8479                         {
8480                                 if (maxtextures <= numtextures)
8481                                 {
8482                                         maxtextures = max(maxtextures * 2, 256);
8483                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8484                                 }
8485                                 textureindex = numtextures++;
8486                                 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8487                         }
8488                 }
8489         }
8490
8491         // now that we have the OBJ data loaded as-is, we can convert it
8492
8493         // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8494         VectorCopy(mins, loadmodel->normalmins);
8495         VectorCopy(maxs, loadmodel->normalmaxs);
8496         dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8497         modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8498         modelyawradius = dist*dist+modelyawradius*modelyawradius;
8499         modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8500         modelradius = modelyawradius + modelradius * modelradius;
8501         modelyawradius = sqrt(modelyawradius);
8502         modelradius = sqrt(modelradius);
8503         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8504         loadmodel->yawmins[2] = loadmodel->normalmins[2];
8505         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] =  modelyawradius;
8506         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8507         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8508         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] =  modelradius;
8509         loadmodel->radius = modelradius;
8510         loadmodel->radius2 = modelradius * modelradius;
8511
8512         // allocate storage for triangles
8513         loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8514         // allocate vertex hash structures to build an optimal vertex subset
8515         vertexhashsize = numtriangles*2;
8516         vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8517         memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8518         vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8519         vertexhashcount = 0;
8520
8521         // gather surface stats for assigning vertex/triangle ranges
8522         firstvertex = 0;
8523         firsttriangle = 0;
8524         elementindex = 0;
8525         loadmodel->num_surfaces = 0;
8526         // allocate storage for the worst case number of surfaces, later we resize
8527         tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8528         submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8529         tempsurface = tempsurfaces;
8530         for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8531         {
8532                 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8533                 for (textureindex = 0;textureindex < numtextures;textureindex++)
8534                 {
8535                         for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8536                         {
8537                                 thisvertex = vertices + vertexindex;
8538                                 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8539                                         break;
8540                         }
8541                         // skip the surface creation if there are no triangles for it
8542                         if (vertexindex == numtriangles*3)
8543                                 continue;
8544                         // create a surface for these vertices
8545                         surfacevertices = 0;
8546                         surfaceelements = 0;
8547                         // we hack in a texture index in the surface to be fixed up later...
8548                         tempsurface->texture = (texture_t *)((size_t)textureindex);
8549                         // calculate bounds as we go
8550                         VectorCopy(thisvertex->v, tempsurface->mins);
8551                         VectorCopy(thisvertex->v, tempsurface->maxs);
8552                         for (;vertexindex < numtriangles*3;vertexindex++)
8553                         {
8554                                 thisvertex = vertices + vertexindex;
8555                                 if (thisvertex->submodelindex != submodelindex)
8556                                         continue;
8557                                 if (thisvertex->textureindex != textureindex)
8558                                         continue;
8559                                 // add vertex to surface bounds
8560                                 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8561                                 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8562                                 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8563                                 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8564                                 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8565                                 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8566                                 // add the vertex if it is not found in the merged set, and
8567                                 // get its index (triangle element) for the surface
8568                                 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8569                                 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8570                                 {
8571                                         vdata = vertexhashdata + i;
8572                                         if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8573                                                 break;
8574                                 }
8575                                 if (i < 0)
8576                                 {
8577                                         i = vertexhashcount++;
8578                                         vdata = vertexhashdata + i;
8579                                         *vdata = *thisvertex;
8580                                         vdata->nextindex = vertexhashtable[vertexhashindex];
8581                                         vertexhashtable[vertexhashindex] = i;
8582                                         surfacevertices++;
8583                                 }
8584                                 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8585                                 surfaceelements++;
8586                         }
8587                         surfacetriangles = surfaceelements / 3;
8588                         tempsurface->num_vertices = surfacevertices;
8589                         tempsurface->num_triangles = surfacetriangles;
8590                         tempsurface->num_firstvertex = firstvertex;
8591                         tempsurface->num_firsttriangle = firsttriangle;
8592                         firstvertex += tempsurface->num_vertices;
8593                         firsttriangle += tempsurface->num_triangles;
8594                         tempsurface++;
8595                         loadmodel->num_surfaces++;
8596                 }
8597         }
8598         submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8599         numvertices = firstvertex;
8600         loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8601         tempsurfaces = NULL;
8602
8603         // allocate storage for final mesh data
8604         loadmodel->num_textures = numtextures * loadmodel->numskins;
8605         loadmodel->num_texturesperskin = numtextures;
8606         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(model_t *));
8607         loadmodel->brush.submodels = (model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(model_t *);
8608         loadmodel->modelsurfaces_sorted = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8609         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8610         loadmodel->surfmesh.num_vertices = numvertices;
8611         loadmodel->surfmesh.num_triangles = numtriangles;
8612         loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8613         loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8614         loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8615         loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8616         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8617
8618         if (loadmodel->surfmesh.num_vertices <= 65536) {
8619                 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8620         }
8621
8622         for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8623         {
8624                 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8625                 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8626                 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8627         }
8628
8629         // load the textures
8630         for (textureindex = 0;textureindex < numtextures;textureindex++)
8631                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8632         Mod_FreeSkinFiles(skinfiles);
8633
8634         // set the surface textures to their real values now that we loaded them...
8635         for (i = 0;i < loadmodel->num_surfaces;i++)
8636                 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8637
8638         // free data
8639         Mem_Free(vertices);
8640         Mem_Free(texturenames);
8641         Mem_Free(obj_v);
8642         Mem_Free(obj_vt);
8643         Mem_Free(obj_vn);
8644         Mem_Free(vertexhashtable);
8645         Mem_Free(vertexhashdata);
8646
8647         // compute all the mesh information that was not loaded from the file
8648         if (loadmodel->surfmesh.data_element3s)
8649                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8650                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8651         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8652         // generate normals if the file did not have them
8653         if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8654                 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);
8655         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);
8656
8657         // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8658         loadmodel->brush.num_visleafs = 1;
8659         loadmodel->brush.num_leafs = 1;
8660         loadmodel->brush.num_nodes = 0;
8661         loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8662         loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8663         loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8664         loadmodel->brush.num_pvsclusters = 1;
8665         loadmodel->brush.num_pvsclusterbytes = 1;
8666         loadmodel->brush.data_pvsclusters = nobsp_pvs;
8667         //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8668         //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8669         loadmodel->brush.data_leafsurfaces = loadmodel->modelsurfaces_sorted;
8670         VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8671         VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8672         loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8673         loadmodel->brush.data_leafs->clusterindex = 0;
8674         loadmodel->brush.data_leafs->areaindex = 0;
8675         loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8676         loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8677         loadmodel->brush.data_leafs->numleafbrushes = 0;
8678         loadmodel->brush.data_leafs->firstleafbrush = NULL;
8679         loadmodel->brush.supportwateralpha = true;
8680
8681         if (loadmodel->brush.numsubmodels)
8682                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
8683
8684         mod = loadmodel;
8685         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8686         {
8687                 if (i > 0)
8688                 {
8689                         char name[10];
8690                         // duplicate the basic information
8691                         dpsnprintf(name, sizeof(name), "*%i", i);
8692                         mod = Mod_FindName(name, loadmodel->name);
8693                         // copy the base model to this one
8694                         *mod = *loadmodel;
8695                         // rename the clone back to its proper name
8696                         strlcpy(mod->name, name, sizeof(mod->name));
8697                         mod->brush.parentmodel = loadmodel;
8698                         // textures and memory belong to the main model
8699                         mod->texturepool = NULL;
8700                         mod->mempool = NULL;
8701                         mod->brush.GetPVS = NULL;
8702                         mod->brush.FatPVS = NULL;
8703                         mod->brush.BoxTouchingPVS = NULL;
8704                         mod->brush.BoxTouchingLeafPVS = NULL;
8705                         mod->brush.BoxTouchingVisibleLeafs = NULL;
8706                         mod->brush.FindBoxClusters = NULL;
8707                         mod->brush.LightPoint = NULL;
8708                         mod->brush.AmbientSoundLevelsForPoint = NULL;
8709                 }
8710                 mod->brush.submodel = i;
8711                 if (loadmodel->brush.submodels)
8712                         loadmodel->brush.submodels[i] = mod;
8713
8714                 // make the model surface list (used by shadowing/lighting)
8715                 mod->submodelsurfaces_start = submodelfirstsurface[i];
8716                 mod->submodelsurfaces_end = submodelfirstsurface[i+1];
8717                 mod->firstmodelbrush = 0;
8718                 mod->nummodelbrushes = 0;
8719
8720                 VectorClear(mod->normalmins);
8721                 VectorClear(mod->normalmaxs);
8722                 l = false;
8723                 for (j = mod->submodelsurfaces_start;j < mod->submodelsurfaces_end;j++)
8724                 {
8725                         const msurface_t *surface = mod->data_surfaces + j;
8726                         const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8727                         int k;
8728                         if (!surface->num_vertices)
8729                                 continue;
8730                         if (!l)
8731                         {
8732                                 l = true;
8733                                 VectorCopy(v3f, mod->normalmins);
8734                                 VectorCopy(v3f, mod->normalmaxs);
8735                         }
8736                         for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8737                         {
8738                                 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8739                                 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8740                                 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8741                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8742                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8743                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8744                         }
8745                 }
8746                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8747                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8748                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8749                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8750                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8751                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8752                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8753                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8754                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8755                 mod->yawmins[2] = mod->normalmins[2];
8756                 mod->yawmaxs[2] = mod->normalmaxs[2];
8757                 mod->radius = modelradius;
8758                 mod->radius2 = modelradius * modelradius;
8759
8760                 Mod_SetDrawSkyAndWater(mod);
8761
8762                 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8763                 mod->render_bih = mod->collision_bih;
8764
8765                 // generate VBOs and other shared data before cloning submodels
8766                 if (i == 0)
8767                         Mod_BuildVBOs();
8768         }
8769         mod = loadmodel;
8770         Mem_Free(submodelfirstsurface);
8771
8772         // make the model surface list (used by shadowing/lighting)
8773         Mod_MakeSortedSurfaces(loadmodel);
8774
8775         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);
8776 }