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