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