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