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