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