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