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