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