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