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