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