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