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