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