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