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