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