]> icculus.org git repositories - divverent/darkplaces.git/blob - model_brush.c
optimize prologic inversion, it was really showing up in profiles
[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, true);
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, true);
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                 if (mod_q1bsp_polygoncollisions.integer)
3759                 {
3760                         Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
3761                         // point traces and contents checks still use the bsp tree
3762                         mod->TraceLine = Mod_CollisionBIH_TraceLine;
3763                         mod->TraceBox = Mod_CollisionBIH_TraceBox;
3764                         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
3765                 }
3766                 else
3767                         Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
3768
3769                 // generate VBOs and other shared data before cloning submodels
3770                 if (i == 0)
3771                 {
3772                         Mod_BuildVBOs();
3773                         Mod_Q1BSP_LoadMapBrushes();
3774                         //Mod_Q1BSP_ProcessLightList();
3775                 }
3776         }
3777
3778         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);
3779 }
3780
3781 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3782 {
3783 }
3784
3785 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3786 {
3787 /*
3788         d_t *in;
3789         m_t *out;
3790         int i, count;
3791
3792         in = (void *)(mod_base + l->fileofs);
3793         if (l->filelen % sizeof(*in))
3794                 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3795         count = l->filelen / sizeof(*in);
3796         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3797
3798         loadmodel-> = out;
3799         loadmodel->num = count;
3800
3801         for (i = 0;i < count;i++, in++, out++)
3802         {
3803         }
3804 */
3805 }
3806
3807 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3808 {
3809 /*
3810         d_t *in;
3811         m_t *out;
3812         int i, count;
3813
3814         in = (void *)(mod_base + l->fileofs);
3815         if (l->filelen % sizeof(*in))
3816                 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3817         count = l->filelen / sizeof(*in);
3818         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3819
3820         loadmodel-> = out;
3821         loadmodel->num = count;
3822
3823         for (i = 0;i < count;i++, in++, out++)
3824         {
3825         }
3826 */
3827 }
3828
3829 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3830 {
3831 /*
3832         d_t *in;
3833         m_t *out;
3834         int i, count;
3835
3836         in = (void *)(mod_base + l->fileofs);
3837         if (l->filelen % sizeof(*in))
3838                 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3839         count = l->filelen / sizeof(*in);
3840         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3841
3842         loadmodel-> = out;
3843         loadmodel->num = count;
3844
3845         for (i = 0;i < count;i++, in++, out++)
3846         {
3847         }
3848 */
3849 }
3850
3851 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3852 {
3853 /*
3854         d_t *in;
3855         m_t *out;
3856         int i, count;
3857
3858         in = (void *)(mod_base + l->fileofs);
3859         if (l->filelen % sizeof(*in))
3860                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3861         count = l->filelen / sizeof(*in);
3862         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3863
3864         loadmodel-> = out;
3865         loadmodel->num = count;
3866
3867         for (i = 0;i < count;i++, in++, out++)
3868         {
3869         }
3870 */
3871 }
3872
3873 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3874 {
3875 /*
3876         d_t *in;
3877         m_t *out;
3878         int i, count;
3879
3880         in = (void *)(mod_base + l->fileofs);
3881         if (l->filelen % sizeof(*in))
3882                 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3883         count = l->filelen / sizeof(*in);
3884         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3885
3886         loadmodel-> = out;
3887         loadmodel->num = count;
3888
3889         for (i = 0;i < count;i++, in++, out++)
3890         {
3891         }
3892 */
3893 }
3894
3895 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3896 {
3897 /*
3898         d_t *in;
3899         m_t *out;
3900         int i, count;
3901
3902         in = (void *)(mod_base + l->fileofs);
3903         if (l->filelen % sizeof(*in))
3904                 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3905         count = l->filelen / sizeof(*in);
3906         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3907
3908         loadmodel-> = out;
3909         loadmodel->num = count;
3910
3911         for (i = 0;i < count;i++, in++, out++)
3912         {
3913         }
3914 */
3915 }
3916
3917 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3918 {
3919 /*
3920         d_t *in;
3921         m_t *out;
3922         int i, count;
3923
3924         in = (void *)(mod_base + l->fileofs);
3925         if (l->filelen % sizeof(*in))
3926                 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3927         count = l->filelen / sizeof(*in);
3928         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3929
3930         loadmodel-> = out;
3931         loadmodel->num = count;
3932
3933         for (i = 0;i < count;i++, in++, out++)
3934         {
3935         }
3936 */
3937 }
3938
3939 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3940 {
3941 /*
3942         d_t *in;
3943         m_t *out;
3944         int i, count;
3945
3946         in = (void *)(mod_base + l->fileofs);
3947         if (l->filelen % sizeof(*in))
3948                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3949         count = l->filelen / sizeof(*in);
3950         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3951
3952         loadmodel-> = out;
3953         loadmodel->num = count;
3954
3955         for (i = 0;i < count;i++, in++, out++)
3956         {
3957         }
3958 */
3959 }
3960
3961 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3962 {
3963 /*
3964         d_t *in;
3965         m_t *out;
3966         int i, count;
3967
3968         in = (void *)(mod_base + l->fileofs);
3969         if (l->filelen % sizeof(*in))
3970                 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3971         count = l->filelen / sizeof(*in);
3972         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3973
3974         loadmodel-> = out;
3975         loadmodel->num = count;
3976
3977         for (i = 0;i < count;i++, in++, out++)
3978         {
3979         }
3980 */
3981 }
3982
3983 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3984 {
3985 /*
3986         d_t *in;
3987         m_t *out;
3988         int i, count;
3989
3990         in = (void *)(mod_base + l->fileofs);
3991         if (l->filelen % sizeof(*in))
3992                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3993         count = l->filelen / sizeof(*in);
3994         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3995
3996         loadmodel-> = out;
3997         loadmodel->num = count;
3998
3999         for (i = 0;i < count;i++, in++, out++)
4000         {
4001         }
4002 */
4003 }
4004
4005 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4006 {
4007 /*
4008         d_t *in;
4009         m_t *out;
4010         int i, count;
4011
4012         in = (void *)(mod_base + l->fileofs);
4013         if (l->filelen % sizeof(*in))
4014                 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4015         count = l->filelen / sizeof(*in);
4016         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4017
4018         loadmodel-> = out;
4019         loadmodel->num = count;
4020
4021         for (i = 0;i < count;i++, in++, out++)
4022         {
4023         }
4024 */
4025 }
4026
4027 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4028 {
4029 /*
4030         d_t *in;
4031         m_t *out;
4032         int i, count;
4033
4034         in = (void *)(mod_base + l->fileofs);
4035         if (l->filelen % sizeof(*in))
4036                 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4037         count = l->filelen / sizeof(*in);
4038         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4039
4040         loadmodel-> = out;
4041         loadmodel->num = count;
4042
4043         for (i = 0;i < count;i++, in++, out++)
4044         {
4045         }
4046 */
4047 }
4048
4049 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4050 {
4051 /*
4052         d_t *in;
4053         m_t *out;
4054         int i, count;
4055
4056         in = (void *)(mod_base + l->fileofs);
4057         if (l->filelen % sizeof(*in))
4058                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4059         count = l->filelen / sizeof(*in);
4060         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4061
4062         loadmodel-> = out;
4063         loadmodel->num = count;
4064
4065         for (i = 0;i < count;i++, in++, out++)
4066         {
4067         }
4068 */
4069 }
4070
4071 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4072 {
4073 /*
4074         d_t *in;
4075         m_t *out;
4076         int i, count;
4077
4078         in = (void *)(mod_base + l->fileofs);
4079         if (l->filelen % sizeof(*in))
4080                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4081         count = l->filelen / sizeof(*in);
4082         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4083
4084         loadmodel-> = out;
4085         loadmodel->num = count;
4086
4087         for (i = 0;i < count;i++, in++, out++)
4088         {
4089         }
4090 */
4091 }
4092
4093 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4094 {
4095 /*
4096         d_t *in;
4097         m_t *out;
4098         int i, count;
4099
4100         in = (void *)(mod_base + l->fileofs);
4101         if (l->filelen % sizeof(*in))
4102                 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4103         count = l->filelen / sizeof(*in);
4104         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4105
4106         loadmodel-> = out;
4107         loadmodel->num = count;
4108
4109         for (i = 0;i < count;i++, in++, out++)
4110         {
4111         }
4112 */
4113 }
4114
4115 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4116 {
4117 /*
4118         d_t *in;
4119         m_t *out;
4120         int i, count;
4121
4122         in = (void *)(mod_base + l->fileofs);
4123         if (l->filelen % sizeof(*in))
4124                 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4125         count = l->filelen / sizeof(*in);
4126         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4127
4128         loadmodel-> = out;
4129         loadmodel->num = count;
4130
4131         for (i = 0;i < count;i++, in++, out++)
4132         {
4133         }
4134 */
4135 }
4136
4137 static void Mod_Q2BSP_LoadModels(lump_t *l)
4138 {
4139 /*
4140         d_t *in;
4141         m_t *out;
4142         int i, count;
4143
4144         in = (void *)(mod_base + l->fileofs);
4145         if (l->filelen % sizeof(*in))
4146                 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4147         count = l->filelen / sizeof(*in);
4148         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4149
4150         loadmodel-> = out;
4151         loadmodel->num = count;
4152
4153         for (i = 0;i < count;i++, in++, out++)
4154         {
4155         }
4156 */
4157 }
4158
4159 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4160 {
4161         int i;
4162         q2dheader_t *header;
4163
4164         Host_Error("Mod_Q2BSP_Load: not yet implemented");
4165
4166         mod->modeldatatypestring = "Q2BSP";
4167
4168         mod->type = mod_brushq2;
4169
4170         header = (q2dheader_t *)buffer;
4171
4172         i = LittleLong(header->version);
4173         if (i != Q2BSPVERSION)
4174                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4175
4176         mod_base = (unsigned char *)header;
4177
4178         // swap all the lumps
4179         for (i = 0;i < (int) sizeof(*header) / 4;i++)
4180                 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4181
4182         mod->brush.qw_md4sum = 0;
4183         mod->brush.qw_md4sum2 = 0;
4184         for (i = 0;i < Q2HEADER_LUMPS;i++)
4185         {
4186                 if (i == Q2LUMP_ENTITIES)
4187                         continue;
4188                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4189                 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4190                         continue;
4191                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4192         }
4193
4194         Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4195         Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4196         Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4197         Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4198         Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4199         Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4200         Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4201         Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4202         Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4203         Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4204         Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4205         Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4206         Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4207         Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4208         Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4209         Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4210         Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4211         // LordHavoc: must go last because this makes the submodels
4212         Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4213 }
4214
4215 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4216 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4217
4218 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4219 {
4220         const char *data;
4221         char key[128], value[MAX_INPUTLINE];
4222         float v[3];
4223         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4224         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4225         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4226         if (!l->filelen)
4227                 return;
4228         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4229         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4230         loadmodel->brush.entities[l->filelen] = 0;
4231         data = loadmodel->brush.entities;
4232         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4233         // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4234         loadmodel->brushq3.deluxemapping = false;
4235         if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4236         {
4237                 while (1)
4238                 {
4239                         if (!COM_ParseToken_Simple(&data, false, false))
4240                                 break; // error
4241                         if (com_token[0] == '}')
4242                                 break; // end of worldspawn
4243                         if (com_token[0] == '_')
4244                                 strlcpy(key, com_token + 1, sizeof(key));
4245                         else
4246                                 strlcpy(key, com_token, sizeof(key));
4247                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
4248                                 key[strlen(key)-1] = 0;
4249                         if (!COM_ParseToken_Simple(&data, false, false))
4250                                 break; // error
4251                         strlcpy(value, com_token, sizeof(value));
4252                         if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4253                         {
4254 #if _MSC_VER >= 1400
4255 #define sscanf sscanf_s
4256 #endif
4257 #if 0
4258                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4259                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4260 #else
4261                                 VectorSet(v, 64, 64, 128);
4262                                 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4263                                         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]);
4264                                 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4265                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4266 #endif
4267                         }
4268                         else if (!strcmp("deluxeMaps", key))
4269                         {
4270                                 if (!strcmp(com_token, "1"))
4271                                 {
4272                                         loadmodel->brushq3.deluxemapping = true;
4273                                         loadmodel->brushq3.deluxemapping_modelspace = true;
4274                                 }
4275                                 else if (!strcmp(com_token, "2"))
4276                                 {
4277                                         loadmodel->brushq3.deluxemapping = true;
4278                                         loadmodel->brushq3.deluxemapping_modelspace = false;
4279                                 }
4280                         }
4281                 }
4282         }
4283 }
4284
4285 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4286 {
4287         q3dtexture_t *in;
4288         texture_t *out;
4289         int i, count;
4290
4291         in = (q3dtexture_t *)(mod_base + l->fileofs);
4292         if (l->filelen % sizeof(*in))
4293                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4294         count = l->filelen / sizeof(*in);
4295         out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4296
4297         loadmodel->data_textures = out;
4298         loadmodel->num_textures = count;
4299         loadmodel->num_texturesperskin = loadmodel->num_textures;
4300
4301         for (i = 0;i < count;i++)
4302         {
4303                 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4304                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4305                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4306                 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4307                 // restore the surfaceflags and supercontents
4308                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4309                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4310         }
4311 }
4312
4313 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4314 {
4315         q3dplane_t *in;
4316         mplane_t *out;
4317         int i, count;
4318
4319         in = (q3dplane_t *)(mod_base + l->fileofs);
4320         if (l->filelen % sizeof(*in))
4321                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4322         count = l->filelen / sizeof(*in);
4323         out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4324
4325         loadmodel->brush.data_planes = out;
4326         loadmodel->brush.num_planes = count;
4327
4328         for (i = 0;i < count;i++, in++, out++)
4329         {
4330                 out->normal[0] = LittleFloat(in->normal[0]);
4331                 out->normal[1] = LittleFloat(in->normal[1]);
4332                 out->normal[2] = LittleFloat(in->normal[2]);
4333                 out->dist = LittleFloat(in->dist);
4334                 PlaneClassify(out);
4335         }
4336 }
4337
4338 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4339 {
4340         q3dbrushside_t *in;
4341         q3mbrushside_t *out;
4342         int i, n, count;
4343
4344         in = (q3dbrushside_t *)(mod_base + l->fileofs);
4345         if (l->filelen % sizeof(*in))
4346                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4347         count = l->filelen / sizeof(*in);
4348         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4349
4350         loadmodel->brush.data_brushsides = out;
4351         loadmodel->brush.num_brushsides = count;
4352
4353         for (i = 0;i < count;i++, in++, out++)
4354         {
4355                 n = LittleLong(in->planeindex);
4356                 if (n < 0 || n >= loadmodel->brush.num_planes)
4357                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4358                 out->plane = loadmodel->brush.data_planes + n;
4359                 n = LittleLong(in->textureindex);
4360                 if (n < 0 || n >= loadmodel->num_textures)
4361                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4362                 out->texture = loadmodel->data_textures + n;
4363         }
4364 }
4365
4366 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4367 {
4368         q3dbrushside_ig_t *in;
4369         q3mbrushside_t *out;
4370         int i, n, count;
4371
4372         in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4373         if (l->filelen % sizeof(*in))
4374                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4375         count = l->filelen / sizeof(*in);
4376         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4377
4378         loadmodel->brush.data_brushsides = out;
4379         loadmodel->brush.num_brushsides = count;
4380
4381         for (i = 0;i < count;i++, in++, out++)
4382         {
4383                 n = LittleLong(in->planeindex);
4384                 if (n < 0 || n >= loadmodel->brush.num_planes)
4385                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4386                 out->plane = loadmodel->brush.data_planes + n;
4387                 n = LittleLong(in->textureindex);
4388                 if (n < 0 || n >= loadmodel->num_textures)
4389                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4390                 out->texture = loadmodel->data_textures + n;
4391         }
4392 }
4393
4394 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4395 {
4396         q3dbrush_t *in;
4397         q3mbrush_t *out;
4398         int i, j, n, c, count, maxplanes, q3surfaceflags;
4399         colplanef_t *planes;
4400
4401         in = (q3dbrush_t *)(mod_base + l->fileofs);
4402         if (l->filelen % sizeof(*in))
4403                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4404         count = l->filelen / sizeof(*in);
4405         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4406
4407         loadmodel->brush.data_brushes = out;
4408         loadmodel->brush.num_brushes = count;
4409
4410         maxplanes = 0;
4411         planes = NULL;
4412
4413         for (i = 0;i < count;i++, in++, out++)
4414         {
4415                 n = LittleLong(in->firstbrushside);
4416                 c = LittleLong(in->numbrushsides);
4417                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4418                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4419                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4420                 out->numbrushsides = c;
4421                 n = LittleLong(in->textureindex);
4422                 if (n < 0 || n >= loadmodel->num_textures)
4423                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4424                 out->texture = loadmodel->data_textures + n;
4425
4426                 // make a list of mplane_t structs to construct a colbrush from
4427                 if (maxplanes < out->numbrushsides)
4428                 {
4429                         maxplanes = out->numbrushsides;
4430                         if (planes)
4431                                 Mem_Free(planes);
4432                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4433                 }
4434                 q3surfaceflags = 0;
4435                 for (j = 0;j < out->numbrushsides;j++)
4436                 {
4437                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4438                         planes[j].dist = out->firstbrushside[j].plane->dist;
4439                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4440                         planes[j].texture = out->firstbrushside[j].texture;
4441                         q3surfaceflags |= planes[j].q3surfaceflags;
4442                 }
4443                 // make the colbrush from the planes
4444                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4445
4446                 // this whole loop can take a while (e.g. on redstarrepublic4)
4447                 CL_KeepaliveMessage(false);
4448         }
4449         if (planes)
4450                 Mem_Free(planes);
4451 }
4452
4453 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4454 {
4455         q3deffect_t *in;
4456         q3deffect_t *out;
4457         int i, n, count;
4458
4459         in = (q3deffect_t *)(mod_base + l->fileofs);
4460         if (l->filelen % sizeof(*in))
4461                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4462         count = l->filelen / sizeof(*in);
4463         out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4464
4465         loadmodel->brushq3.data_effects = out;
4466         loadmodel->brushq3.num_effects = count;
4467
4468         for (i = 0;i < count;i++, in++, out++)
4469         {
4470                 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4471                 n = LittleLong(in->brushindex);
4472                 if (n >= loadmodel->brush.num_brushes)
4473                 {
4474                         Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4475                         n = -1;
4476                 }
4477                 out->brushindex = n;
4478                 out->unknown = LittleLong(in->unknown);
4479         }
4480 }
4481
4482 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4483 {
4484         q3dvertex_t *in;
4485         int i, count;
4486
4487         in = (q3dvertex_t *)(mod_base + l->fileofs);
4488         if (l->filelen % sizeof(*in))
4489                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4490         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4491         loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4492         loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4493         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4494         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4495         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4496
4497         for (i = 0;i < count;i++, in++)
4498         {
4499                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4500                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4501                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4502                 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4503                 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4504                 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4505                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4506                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4507                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4508                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4509                 // svector/tvector are calculated later in face loading
4510                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4511                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4512                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4513                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4514                 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4515                         loadmodel->lit = true;
4516         }
4517 }
4518
4519 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4520 {
4521         int *in;
4522         int *out;
4523         int i, count;
4524
4525         in = (int *)(mod_base + l->fileofs);
4526         if (l->filelen % sizeof(int[3]))
4527                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4528         count = l->filelen / sizeof(*in);
4529
4530         if(!loadmodel->brushq3.num_vertices)
4531         {
4532                 if (count)
4533                         Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4534                 loadmodel->brushq3.num_triangles = 0;
4535                 return;
4536         }
4537
4538         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4539         loadmodel->brushq3.num_triangles = count / 3;
4540         loadmodel->brushq3.data_element3i = out;
4541
4542         for (i = 0;i < count;i++, in++, out++)
4543         {
4544                 *out = LittleLong(*in);
4545                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4546                 {
4547                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4548                         *out = 0;
4549                 }
4550         }
4551 }
4552
4553 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4554 {
4555         q3dlightmap_t *input_pointer;
4556         int i;
4557         int j;
4558         int k;
4559         int count;
4560         int powerx;
4561         int powery;
4562         int powerxy;
4563         int powerdxy;
4564         int endlightmap;
4565         int mergegoal;
4566         int lightmapindex;
4567         int realcount;
4568         int realindex;
4569         int mergedwidth;
4570         int mergedheight;
4571         int mergedcolumns;
4572         int mergedrows;
4573         int mergedrowsxcolumns;
4574         int size;
4575         int bytesperpixel;
4576         int rgbmap[3];
4577         unsigned char *c;
4578         unsigned char *mergedpixels;
4579         unsigned char *mergeddeluxepixels;
4580         unsigned char *mergebuf;
4581         char mapname[MAX_QPATH];
4582         qboolean external;
4583         unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4584
4585         // defaults for q3bsp
4586         size = 128;
4587         bytesperpixel = 3;
4588         rgbmap[0] = 2;
4589         rgbmap[1] = 1;
4590         rgbmap[2] = 0;
4591         external = false;
4592         loadmodel->brushq3.lightmapsize = 128;
4593
4594         if (cls.state == ca_dedicated)
4595                 return;
4596
4597         if(mod_q3bsp_nolightmaps.integer)
4598         {
4599                 return;
4600         }
4601         else if(l->filelen)
4602         {
4603                 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4604                 if (developer_loading.integer)
4605                         Con_Printf("Using internal lightmaps\n");
4606                 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4607                 if (l->filelen % sizeof(*input_pointer))
4608                         Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4609                 count = l->filelen / sizeof(*input_pointer);
4610                 for(i = 0; i < count; ++i)
4611                         inpixels[i] = input_pointer[i].rgb;
4612         }
4613         else
4614         {
4615                 // no internal lightmaps
4616                 // try external lightmaps
4617                 if (developer_loading.integer)
4618                         Con_Printf("Using external lightmaps\n");
4619                 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4620                 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false, NULL);
4621                 if(!inpixels[0])
4622                         return;
4623
4624                 // using EXTERNAL lightmaps instead
4625                 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4626                 {
4627                         Mem_Free(inpixels[0]);
4628                         Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4629                 }
4630
4631                 size = image_width;
4632                 bytesperpixel = 4;
4633                 rgbmap[0] = 0;
4634                 rgbmap[1] = 1;
4635                 rgbmap[2] = 2;
4636                 external = true;
4637
4638                 for(count = 1; ; ++count)
4639                 {
4640                         inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false, NULL);
4641                         if(!inpixels[count])
4642                                 break; // we got all of them
4643                         if(image_width != size || image_height != size)
4644                         {
4645                                 Mem_Free(inpixels[count]);
4646                                 inpixels[count] = NULL;
4647                                 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);
4648                                 break;
4649                         }
4650                 }
4651         }
4652
4653         loadmodel->brushq3.lightmapsize = size;
4654         loadmodel->brushq3.num_originallightmaps = count;
4655
4656         // now check the surfaces to see if any of them index an odd numbered
4657         // lightmap, if so this is not a deluxemapped bsp file
4658         //
4659         // also check what lightmaps are actually used, because q3map2 sometimes
4660         // (always?) makes an unused one at the end, which
4661         // q3map2 sometimes (or always?) makes a second blank lightmap for no
4662         // reason when only one lightmap is used, which can throw off the
4663         // deluxemapping detection method, so check 2-lightmap bsp's specifically
4664         // to see if the second lightmap is blank, if so it is not deluxemapped.
4665         // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4666         // in Mod_Q3BSP_LoadEntities was failed
4667         if (!loadmodel->brushq3.deluxemapping)
4668         {
4669                 loadmodel->brushq3.deluxemapping = !(count & 1);
4670                 loadmodel->brushq3.deluxemapping_modelspace = true;
4671                 endlightmap = 0;
4672                 if (loadmodel->brushq3.deluxemapping)
4673                 {
4674                         int facecount = faceslump->filelen / sizeof(q3dface_t);
4675                         q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4676                         for (i = 0;i < facecount;i++)
4677                         {
4678                                 j = LittleLong(faces[i].lightmapindex);
4679                                 if (j >= 0)
4680                                 {
4681                                         endlightmap = max(endlightmap, j + 1);
4682                                         if ((j & 1) || j + 1 >= count)
4683                                         {
4684                                                 loadmodel->brushq3.deluxemapping = false;
4685                                                 break;
4686                                         }
4687                                 }
4688                         }
4689                 }
4690
4691                 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4692                 // reason when only one lightmap is used, which can throw off the
4693                 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4694                 // to see if the second lightmap is blank, if so it is not deluxemapped.
4695                 //
4696                 // further research has shown q3map2 sometimes creates a deluxemap and two
4697                 // blank lightmaps, which must be handled properly as well
4698                 if (endlightmap == 1 && count > 1)
4699                 {
4700                         c = inpixels[1];
4701                         for (i = 0;i < size*size;i++)
4702                         {
4703                                 if (c[bytesperpixel*i + rgbmap[0]])
4704                                         break;
4705                                 if (c[bytesperpixel*i + rgbmap[1]])
4706                                         break;
4707                                 if (c[bytesperpixel*i + rgbmap[2]])
4708                                         break;
4709                         }
4710                         if (i == size*size)
4711                         {
4712                                 // all pixels in the unused lightmap were black...
4713                                 loadmodel->brushq3.deluxemapping = false;
4714                         }
4715                 }
4716         }
4717
4718         Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4719
4720         // figure out what the most reasonable merge power is within limits
4721
4722         // find the appropriate NxN dimensions to merge to, to avoid wasted space
4723         realcount = count >> (int)loadmodel->brushq3.deluxemapping;
4724
4725         // figure out how big the merged texture has to be
4726         mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
4727         mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
4728         while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
4729                 mergegoal /= 2;
4730         mergedwidth = mergegoal;
4731         mergedheight = mergegoal;
4732         // choose non-square size (2x1 aspect) if only half the space is used;
4733         // this really only happens when the entire set fits in one texture, if
4734         // there are multiple textures, we don't worry about shrinking the last
4735         // one to fit, because the driver prefers the same texture size on
4736         // consecutive draw calls...
4737         if (mergedwidth * mergedheight / 2 >= size*size*realcount)
4738                 mergedheight /= 2;
4739
4740         loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
4741         loadmodel->brushq3.num_lightmapmergedheightpower = 0;
4742         while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
4743                 loadmodel->brushq3.num_lightmapmergedwidthpower++;
4744         while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
4745                 loadmodel->brushq3.num_lightmapmergedheightpower++;
4746         loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
4747
4748         powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
4749         powery = loadmodel->brushq3.num_lightmapmergedheightpower;
4750         powerxy = powerx+powery;
4751         powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
4752
4753         mergedcolumns = 1 << powerx;
4754         mergedrows = 1 << powery;
4755         mergedrowsxcolumns = 1 << powerxy;
4756
4757         loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
4758         loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4759         if (loadmodel->brushq3.deluxemapping)
4760                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4761
4762         // allocate a texture pool if we need it
4763         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4764                 loadmodel->texturepool = R_AllocTexturePool();
4765
4766         mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
4767         mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
4768         for (i = 0;i < count;i++)
4769         {
4770                 // figure out which merged lightmap texture this fits into
4771                 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
4772                 lightmapindex = i >> powerdxy;
4773
4774                 // choose the destination address
4775                 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
4776                 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
4777                 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
4778                         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);
4779
4780                 // convert pixels from RGB or BGRA while copying them into the destination rectangle
4781                 for (j = 0;j < size;j++)
4782                 for (k = 0;k < size;k++)
4783                 {
4784                         mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
4785                         mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
4786                         mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
4787                         mergebuf[(j*mergedwidth+k)*4+3] = 255;
4788                 }
4789
4790                 // upload texture if this was the last tile being written to the texture
4791                 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
4792                 {
4793                         if (loadmodel->brushq3.deluxemapping && (i & 1))
4794                                 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);
4795                         else
4796                                 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);
4797                 }
4798         }
4799
4800         if (mergeddeluxepixels)
4801                 Mem_Free(mergeddeluxepixels);
4802         Mem_Free(mergedpixels);
4803         if(external)
4804         {
4805                 for(i = 0; i < count; ++i)
4806                         Mem_Free(inpixels[i]);
4807         }
4808 }
4809
4810 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
4811 {
4812         int j, k, cnt, tri;
4813         float *mins, *maxs;
4814         const float *vert;
4815         *collisionstride = stride;
4816         if(stride > 0)
4817         {
4818                 cnt = (num_triangles + stride - 1) / stride;
4819                 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
4820                 for(j = 0; j < cnt; ++j)
4821                 {
4822                         mins = &((*collisionbbox6f)[6 * j + 0]);
4823                         maxs = &((*collisionbbox6f)[6 * j + 3]);
4824                         for(k = 0; k < stride; ++k)
4825                         {
4826                                 tri = j * stride + k;
4827                                 if(tri >= num_triangles)
4828                                         break;
4829                                 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
4830                                 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
4831                                 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
4832                                 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
4833                                 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
4834                                 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
4835                                 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
4836                                 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
4837                                 if(vert[0] < mins[0]) mins[0] = vert[0];
4838                                 if(vert[1] < mins[1]) mins[1] = vert[1];
4839                                 if(vert[2] < mins[2]) mins[2] = vert[2];
4840                                 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4841                                 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4842                                 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4843                                 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
4844                                 if(vert[0] < mins[0]) mins[0] = vert[0];
4845                                 if(vert[1] < mins[1]) mins[1] = vert[1];
4846                                 if(vert[2] < mins[2]) mins[2] = vert[2];
4847                                 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4848                                 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4849                                 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4850                         }
4851                 }
4852         }
4853         else
4854                 *collisionbbox6f = NULL;
4855 }
4856
4857 typedef struct patchtess_s
4858 {
4859         patchinfo_t info;
4860
4861         // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
4862         int surface_id;
4863         float lodgroup[6];
4864         float *originalvertex3f;
4865 } patchtess_t;
4866
4867 #define PATCHTESS_SAME_LODGROUP(a,b) \
4868         ( \
4869                 (a).lodgroup[0] == (b).lodgroup[0] && \
4870                 (a).lodgroup[1] == (b).lodgroup[1] && \
4871                 (a).lodgroup[2] == (b).lodgroup[2] && \
4872                 (a).lodgroup[3] == (b).lodgroup[3] && \
4873                 (a).lodgroup[4] == (b).lodgroup[4] && \
4874                 (a).lodgroup[5] == (b).lodgroup[5] \
4875         )
4876
4877 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4878 {
4879         q3dface_t *in, *oldin;
4880         msurface_t *out, *oldout;
4881         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;
4882         float lightmaptcbase[2], lightmaptcscale[2];
4883         //int *originalelement3i;
4884         //int *originalneighbor3i;
4885         float *originalvertex3f;
4886         //float *originalsvector3f;
4887         //float *originaltvector3f;
4888         float *originalnormal3f;
4889         float *originalcolor4f;
4890         float *originaltexcoordtexture2f;
4891         float *originaltexcoordlightmap2f;
4892         float *surfacecollisionvertex3f;
4893         int *surfacecollisionelement3i;
4894         float *v;
4895         patchtess_t *patchtess = NULL;
4896         int patchtesscount = 0;
4897         qboolean again;
4898
4899         in = (q3dface_t *)(mod_base + l->fileofs);
4900         if (l->filelen % sizeof(*in))
4901                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4902         count = l->filelen / sizeof(*in);
4903         out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4904
4905         loadmodel->data_surfaces = out;
4906         loadmodel->num_surfaces = count;
4907
4908         if(count > 0)
4909                 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
4910
4911         i = 0;
4912         oldi = i;
4913         oldin = in;
4914         oldout = out;
4915         meshvertices = 0;
4916         meshtriangles = 0;
4917         for (;i < count;i++, in++, out++)
4918         {
4919                 // check face type first
4920                 type = LittleLong(in->type);
4921                 if (type != Q3FACETYPE_FLAT
4922                  && type != Q3FACETYPE_PATCH
4923                  && type != Q3FACETYPE_MESH
4924                  && type != Q3FACETYPE_FLARE)
4925                 {
4926                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4927                         continue;
4928                 }
4929
4930                 n = LittleLong(in->textureindex);
4931                 if (n < 0 || n >= loadmodel->num_textures)
4932                 {
4933                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4934                         continue;
4935                 }
4936                 out->texture = loadmodel->data_textures + n;
4937                 n = LittleLong(in->effectindex);
4938                 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4939                 {
4940                         if (developer_extra.integer)
4941                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4942                         n = -1;
4943                 }
4944                 if (n == -1)
4945                         out->effect = NULL;
4946                 else
4947                         out->effect = loadmodel->brushq3.data_effects + n;
4948
4949                 if (cls.state != ca_dedicated)
4950                 {
4951                         out->lightmaptexture = NULL;
4952                         out->deluxemaptexture = r_texture_blanknormalmap;
4953                         n = LittleLong(in->lightmapindex);
4954                         if (n < 0)
4955                                 n = -1;
4956                         else if (n >= loadmodel->brushq3.num_originallightmaps)
4957                         {
4958                                 if(loadmodel->brushq3.num_originallightmaps != 0)
4959                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
4960                                 n = -1;
4961                         }
4962                         else
4963                         {
4964                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
4965                                 if (loadmodel->brushq3.deluxemapping)
4966                                         out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
4967                                 loadmodel->lit = true;
4968                         }
4969                 }
4970
4971                 firstvertex = LittleLong(in->firstvertex);
4972                 numvertices = LittleLong(in->numvertices);
4973                 firstelement = LittleLong(in->firstelement);
4974                 numtriangles = LittleLong(in->numelements) / 3;
4975                 if (numtriangles * 3 != LittleLong(in->numelements))
4976                 {
4977                         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));
4978                         continue;
4979                 }
4980                 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4981                 {
4982                         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);
4983                         continue;
4984                 }
4985                 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4986                 {
4987                         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);
4988                         continue;
4989                 }
4990                 switch(type)
4991                 {
4992                 case Q3FACETYPE_FLAT:
4993                 case Q3FACETYPE_MESH:
4994                         // no processing necessary
4995                         break;
4996                 case Q3FACETYPE_PATCH:
4997                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4998                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4999                         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))
5000                         {
5001                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5002                                 continue;
5003                         }
5004                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5005
5006                         // convert patch to Q3FACETYPE_MESH
5007                         xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5008                         ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5009                         // bound to user settings
5010                         xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5011                         ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5012                         // bound to sanity settings
5013                         xtess = bound(0, xtess, 1024);
5014                         ytess = bound(0, ytess, 1024);
5015
5016                         // lower quality collision patches! Same procedure as before, but different cvars
5017                         // convert patch to Q3FACETYPE_MESH
5018                         cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5019                         cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5020                         // bound to user settings
5021                         cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5022                         cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5023                         // bound to sanity settings
5024                         cxtess = bound(0, cxtess, 1024);
5025                         cytess = bound(0, cytess, 1024);
5026
5027                         // store it for the LOD grouping step
5028                         patchtess[patchtesscount].info.xsize = patchsize[0];
5029                         patchtess[patchtesscount].info.ysize = patchsize[1];
5030                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5031                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5032                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5033                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5034         
5035                         patchtess[patchtesscount].surface_id = i;
5036                         patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5037                         patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5038                         patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5039                         patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5040                         patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5041                         patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5042                         patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5043                         ++patchtesscount;
5044                         break;
5045                 case Q3FACETYPE_FLARE:
5046                         if (developer_extra.integer)
5047                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5048                         // don't render it
5049                         continue;
5050                 }
5051                 out->num_vertices = numvertices;
5052                 out->num_triangles = numtriangles;
5053                 meshvertices += out->num_vertices;
5054                 meshtriangles += out->num_triangles;
5055         }
5056
5057         // Fix patches tesselations so that they make no seams
5058         do
5059         {
5060                 again = false;
5061                 for(i = 0; i < patchtesscount; ++i)
5062                 {
5063                         for(j = i+1; j < patchtesscount; ++j)
5064                         {
5065                                 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5066                                         continue;
5067
5068                                 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5069                                         again = true;
5070                         }
5071                 }
5072         }
5073         while (again);
5074
5075         // Calculate resulting number of triangles
5076         collisionvertices = 0;
5077         collisiontriangles = 0;
5078         for(i = 0; i < patchtesscount; ++i)
5079         {
5080                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5081                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5082                 numvertices = finalwidth * finalheight;
5083                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5084
5085                 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5086                 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5087                 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5088                 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5089
5090                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5091                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5092                 numvertices = finalwidth * finalheight;
5093                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5094
5095                 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5096                 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5097                 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5098                 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5099         }
5100
5101         i = oldi;
5102         in = oldin;
5103         out = oldout;
5104         Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5105         if (collisiontriangles)
5106         {
5107                 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5108                 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5109         }
5110         meshvertices = 0;
5111         meshtriangles = 0;
5112         collisionvertices = 0;
5113         collisiontriangles = 0;
5114         for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5115         {
5116                 if (out->num_vertices < 3 || out->num_triangles < 1)
5117                         continue;
5118
5119                 type = LittleLong(in->type);
5120                 firstvertex = LittleLong(in->firstvertex);
5121                 firstelement = LittleLong(in->firstelement);
5122                 out->num_firstvertex = meshvertices;
5123                 out->num_firsttriangle = meshtriangles;
5124                 out->num_firstcollisiontriangle = collisiontriangles;
5125                 switch(type)
5126                 {
5127                 case Q3FACETYPE_FLAT:
5128                 case Q3FACETYPE_MESH:
5129                         // no processing necessary, except for lightmap merging
5130                         for (j = 0;j < out->num_vertices;j++)
5131                         {
5132                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5133                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5134                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5135                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5136                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5137                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5138                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5139                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5140                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5141                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5142                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5143                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5144                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5145                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5146                         }
5147                         for (j = 0;j < out->num_triangles*3;j++)
5148                                 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5149                         break;
5150                 case Q3FACETYPE_PATCH:
5151                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5152                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5153                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5154                         originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5155                         originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5156                         originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5157                         originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5158
5159                         xtess = ytess = cxtess = cytess = -1;
5160                         for(j = 0; j < patchtesscount; ++j)
5161                                 if(patchtess[j].surface_id == i)
5162                                 {
5163                                         xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5164                                         ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5165                                         cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5166                                         cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5167                                         break;
5168                                 }
5169                         if(xtess == -1)
5170                         {
5171                                 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5172                                 xtess = ytess = cxtess = cytess = 0;
5173                         }
5174
5175                         finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5176                         finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5177                         finalvertices = finalwidth * finalheight;
5178                         oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5179                         type = Q3FACETYPE_MESH;
5180                         // generate geometry
5181                         // (note: normals are skipped because they get recalculated)
5182                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5183                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5184                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5185                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5186                         Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5187                         Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5188
5189                         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);
5190
5191                         if (developer_extra.integer)
5192                         {
5193                                 if (out->num_triangles < finaltriangles)
5194                                         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);
5195                                 else
5196                                         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);
5197                         }
5198                         // q3map does not put in collision brushes for curves... ugh
5199                         // build the lower quality collision geometry
5200                         finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5201                         finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5202                         finalvertices = finalwidth * finalheight;
5203                         oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5204
5205                         // legacy collision geometry implementation
5206                         out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5207                         out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5208                         out->num_collisionvertices = finalvertices;
5209                         out->num_collisiontriangles = finaltriangles;
5210                         Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5211                         Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5212
5213                         //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5214                         Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5215
5216                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5217
5218                         // now optimize the collision mesh by finding triangle bboxes...
5219                         Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5220                         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);
5221
5222                         // store collision geometry for BIH collision tree
5223                         surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5224                         surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5225                         Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5226                         Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5227                         Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5228 #if 1
5229                         // remove this once the legacy code is removed
5230                         {
5231                                 int nc = out->num_collisiontriangles;
5232 #endif
5233                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5234 #if 1
5235                                 if(nc != out->num_collisiontriangles)
5236                                 {
5237                                         Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5238                                 }
5239                         }
5240 #endif
5241
5242                         if (developer_extra.integer)
5243                                 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);
5244
5245                         collisionvertices += finalvertices;
5246                         collisiontriangles += out->num_collisiontriangles;
5247                         break;
5248                 default:
5249                         break;
5250                 }
5251                 meshvertices += out->num_vertices;
5252                 meshtriangles += out->num_triangles;
5253                 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5254                         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)
5255                                 invalidelements++;
5256                 if (invalidelements)
5257                 {
5258                         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);
5259                         for (j = 0;j < out->num_triangles * 3;j++)
5260                         {
5261                                 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5262                                 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)
5263                                         (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5264                         }
5265                         Con_Print("\n");
5266                 }
5267                 // calculate a bounding box
5268                 VectorClear(out->mins);
5269                 VectorClear(out->maxs);
5270                 if (out->num_vertices)
5271                 {
5272                         if (cls.state != ca_dedicated && out->lightmaptexture)
5273                         {
5274                                 // figure out which part of the merged lightmap this fits into
5275                                 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5276                                 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5277                                 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5278                                 lightmapindex &= mergewidth * mergeheight - 1;
5279                                 lightmaptcscale[0] = 1.0f / mergewidth;
5280                                 lightmaptcscale[1] = 1.0f / mergeheight;
5281                                 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5282                                 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5283                                 // modify the lightmap texcoords to match this region of the merged lightmap
5284                                 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5285                                 {
5286                                         v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5287                                         v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5288                                 }
5289                         }
5290                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5291                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5292                         for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5293                         {
5294                                 out->mins[0] = min(out->mins[0], v[0]);
5295                                 out->maxs[0] = max(out->maxs[0], v[0]);
5296                                 out->mins[1] = min(out->mins[1], v[1]);
5297                                 out->maxs[1] = max(out->maxs[1], v[1]);
5298                                 out->mins[2] = min(out->mins[2], v[2]);
5299                                 out->maxs[2] = max(out->maxs[2], v[2]);
5300                         }
5301                         out->mins[0] -= 1.0f;
5302                         out->mins[1] -= 1.0f;
5303                         out->mins[2] -= 1.0f;
5304                         out->maxs[0] += 1.0f;
5305                         out->maxs[1] += 1.0f;
5306                         out->maxs[2] += 1.0f;
5307                 }
5308                 // set lightmap styles for consistency with q1bsp
5309                 //out->lightmapinfo->styles[0] = 0;
5310                 //out->lightmapinfo->styles[1] = 255;
5311                 //out->lightmapinfo->styles[2] = 255;
5312                 //out->lightmapinfo->styles[3] = 255;
5313         }
5314
5315         i = oldi;
5316         out = oldout;
5317         for (;i < count;i++, out++)
5318         {
5319                 if(out->num_vertices && out->num_triangles)
5320                         continue;
5321                 if(out->num_vertices == 0)
5322                 {
5323                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5324                         if(out->num_triangles == 0)
5325                                 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5326                 }
5327                 else if(out->num_triangles == 0)
5328                         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)",
5329                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5330                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5331                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5332         }
5333
5334         // for per pixel lighting
5335         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
5336
5337         // generate ushort elements array if possible
5338         if (loadmodel->surfmesh.data_element3s)
5339                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5340                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5341
5342         // free the no longer needed vertex data
5343         loadmodel->brushq3.num_vertices = 0;
5344         if (loadmodel->brushq3.data_vertex3f)
5345                 Mem_Free(loadmodel->brushq3.data_vertex3f);
5346         loadmodel->brushq3.data_vertex3f = NULL;
5347         loadmodel->brushq3.data_normal3f = NULL;
5348         loadmodel->brushq3.data_texcoordtexture2f = NULL;
5349         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5350         loadmodel->brushq3.data_color4f = NULL;
5351         // free the no longer needed triangle data
5352         loadmodel->brushq3.num_triangles = 0;
5353         if (loadmodel->brushq3.data_element3i)
5354                 Mem_Free(loadmodel->brushq3.data_element3i);
5355         loadmodel->brushq3.data_element3i = NULL;
5356
5357         if(patchtess)
5358                 Mem_Free(patchtess);
5359 }
5360
5361 static void Mod_Q3BSP_LoadModels(lump_t *l)
5362 {
5363         q3dmodel_t *in;
5364         q3dmodel_t *out;
5365         int i, j, n, c, count;
5366
5367         in = (q3dmodel_t *)(mod_base + l->fileofs);
5368         if (l->filelen % sizeof(*in))
5369                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5370         count = l->filelen / sizeof(*in);
5371         out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5372
5373         loadmodel->brushq3.data_models = out;
5374         loadmodel->brushq3.num_models = count;
5375
5376         for (i = 0;i < count;i++, in++, out++)
5377         {
5378                 for (j = 0;j < 3;j++)
5379                 {
5380                         out->mins[j] = LittleFloat(in->mins[j]);
5381                         out->maxs[j] = LittleFloat(in->maxs[j]);
5382                 }
5383                 n = LittleLong(in->firstface);
5384                 c = LittleLong(in->numfaces);
5385                 if (n < 0 || n + c > loadmodel->num_surfaces)
5386                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5387                 out->firstface = n;
5388                 out->numfaces = c;
5389                 n = LittleLong(in->firstbrush);
5390                 c = LittleLong(in->numbrushes);
5391                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5392                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5393                 out->firstbrush = n;
5394                 out->numbrushes = c;
5395         }
5396 }
5397
5398 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5399 {
5400         int *in;
5401         int *out;
5402         int i, n, count;
5403
5404         in = (int *)(mod_base + l->fileofs);
5405         if (l->filelen % sizeof(*in))
5406                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5407         count = l->filelen / sizeof(*in);
5408         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5409
5410         loadmodel->brush.data_leafbrushes = out;
5411         loadmodel->brush.num_leafbrushes = count;
5412
5413         for (i = 0;i < count;i++, in++, out++)
5414         {
5415                 n = LittleLong(*in);
5416                 if (n < 0 || n >= loadmodel->brush.num_brushes)
5417                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5418                 *out = n;
5419         }
5420 }
5421
5422 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5423 {
5424         int *in;
5425         int *out;
5426         int i, n, count;
5427
5428         in = (int *)(mod_base + l->fileofs);
5429         if (l->filelen % sizeof(*in))
5430                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5431         count = l->filelen / sizeof(*in);
5432         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5433
5434         loadmodel->brush.data_leafsurfaces = out;
5435         loadmodel->brush.num_leafsurfaces = count;
5436
5437         for (i = 0;i < count;i++, in++, out++)
5438         {
5439                 n = LittleLong(*in);
5440                 if (n < 0 || n >= loadmodel->num_surfaces)
5441                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5442                 *out = n;
5443         }
5444 }
5445
5446 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5447 {
5448         q3dleaf_t *in;
5449         mleaf_t *out;
5450         int i, j, n, c, count;
5451
5452         in = (q3dleaf_t *)(mod_base + l->fileofs);
5453         if (l->filelen % sizeof(*in))
5454                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5455         count = l->filelen / sizeof(*in);
5456         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5457
5458         loadmodel->brush.data_leafs = out;
5459         loadmodel->brush.num_leafs = count;
5460
5461         for (i = 0;i < count;i++, in++, out++)
5462         {
5463                 out->parent = NULL;
5464                 out->plane = NULL;
5465                 out->clusterindex = LittleLong(in->clusterindex);
5466                 out->areaindex = LittleLong(in->areaindex);
5467                 for (j = 0;j < 3;j++)
5468                 {
5469                         // yes the mins/maxs are ints
5470                         out->mins[j] = LittleLong(in->mins[j]) - 1;
5471                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5472                 }
5473                 n = LittleLong(in->firstleafface);
5474                 c = LittleLong(in->numleaffaces);
5475                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5476                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5477                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5478                 out->numleafsurfaces = c;
5479                 n = LittleLong(in->firstleafbrush);
5480                 c = LittleLong(in->numleafbrushes);
5481                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5482                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5483                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5484                 out->numleafbrushes = c;
5485         }
5486 }
5487
5488 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5489 {
5490         q3dnode_t *in;
5491         mnode_t *out;
5492         int i, j, n, count;
5493
5494         in = (q3dnode_t *)(mod_base + l->fileofs);
5495         if (l->filelen % sizeof(*in))
5496                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5497         count = l->filelen / sizeof(*in);
5498         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5499
5500         loadmodel->brush.data_nodes = out;
5501         loadmodel->brush.num_nodes = count;
5502
5503         for (i = 0;i < count;i++, in++, out++)
5504         {
5505                 out->parent = NULL;
5506                 n = LittleLong(in->planeindex);
5507                 if (n < 0 || n >= loadmodel->brush.num_planes)
5508                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5509                 out->plane = loadmodel->brush.data_planes + n;
5510                 for (j = 0;j < 2;j++)
5511                 {
5512                         n = LittleLong(in->childrenindex[j]);
5513                         if (n >= 0)
5514                         {
5515                                 if (n >= loadmodel->brush.num_nodes)
5516                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5517                                 out->children[j] = loadmodel->brush.data_nodes + n;
5518                         }
5519                         else
5520                         {
5521                                 n = -1 - n;
5522                                 if (n >= loadmodel->brush.num_leafs)
5523                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5524                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5525                         }
5526                 }
5527                 for (j = 0;j < 3;j++)
5528                 {
5529                         // yes the mins/maxs are ints
5530                         out->mins[j] = LittleLong(in->mins[j]) - 1;
5531                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5532                 }
5533         }
5534
5535         // set the parent pointers
5536         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5537 }
5538
5539 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5540 {
5541         q3dlightgrid_t *in;
5542         q3dlightgrid_t *out;
5543         int count;
5544
5545         in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5546         if (l->filelen % sizeof(*in))
5547                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5548         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5549         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5550         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5551         loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5552         loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5553         loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5554         loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5555         loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5556         loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5557         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5558         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5559         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5560         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5561         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]);
5562         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]);
5563
5564         // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5565         if (l->filelen)
5566         {
5567                 if (l->filelen < count * (int)sizeof(*in))
5568                 {
5569                         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]);
5570                         return; // ignore the grid if we cannot understand it
5571                 }
5572                 if (l->filelen != count * (int)sizeof(*in))
5573                         Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5574                 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5575                 loadmodel->brushq3.data_lightgrid = out;
5576                 loadmodel->brushq3.num_lightgrid = count;
5577                 // no swapping or validation necessary
5578                 memcpy(out, in, count * (int)sizeof(*out));
5579         }
5580 }
5581
5582 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5583 {
5584         q3dpvs_t *in;
5585         int totalchains;
5586
5587         if (l->filelen == 0)
5588         {
5589                 int i;
5590                 // unvised maps often have cluster indices even without pvs, so check
5591                 // leafs to find real number of clusters
5592                 loadmodel->brush.num_pvsclusters = 1;
5593                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5594                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5595
5596                 // create clusters
5597                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5598                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5599                 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5600                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5601                 return;
5602         }
5603
5604         in = (q3dpvs_t *)(mod_base + l->fileofs);
5605         if (l->filelen < 9)
5606                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5607
5608         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5609         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5610         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5611                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5612         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5613         if (l->filelen < totalchains + (int)sizeof(*in))
5614                 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);
5615
5616         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5617         memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5618 }
5619
5620 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5621 {
5622         int i, j, k, index[3];
5623         float transformed[3], blend1, blend2, blend, stylescale;
5624         q3dlightgrid_t *a, *s;
5625
5626         // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5627         if (vid.renderpath == RENDERPATH_GL20)
5628                 stylescale = 1; // added while render
5629         else
5630                 stylescale = r_refdef.scene.rtlightstylevalue[0];
5631
5632         if (!model->brushq3.num_lightgrid)
5633         {
5634                 ambientcolor[0] = stylescale;
5635                 ambientcolor[1] = stylescale;
5636                 ambientcolor[2] = stylescale;
5637                 return;
5638         }
5639
5640         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5641         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5642         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5643         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5644         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5645         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5646         index[0] = (int)floor(transformed[0]);
5647         index[1] = (int)floor(transformed[1]);
5648         index[2] = (int)floor(transformed[2]);
5649         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5650
5651         // now lerp the values
5652         VectorClear(diffusenormal);
5653         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5654         for (k = 0;k < 2;k++)
5655         {
5656                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5657                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5658                         continue;
5659                 for (j = 0;j < 2;j++)
5660                 {
5661                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5662                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5663                                 continue;
5664                         for (i = 0;i < 2;i++)
5665                         {
5666                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5667                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5668                                         continue;
5669                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5670                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5671                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5672                                 // this uses the mod_md3_sin table because the values are
5673                                 // already in the 0-255 range, the 64+ bias fetches a cosine
5674                                 // instead of a sine value
5675                                 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5676                                 diffusenormal[1] += blend * (mod_md3_sin[     s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5677                                 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5678                                 //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)));
5679                         }
5680                 }
5681         }
5682
5683         // normalize the light direction before turning
5684         VectorNormalize(diffusenormal);
5685         //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]);
5686 }
5687
5688 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5689 {
5690         double t1, t2;
5691         double midf, mid[3];
5692         int ret, side;
5693
5694         // check for empty
5695         while (node->plane)
5696         {
5697                 // find the point distances
5698                 mplane_t *plane = node->plane;
5699                 if (plane->type < 3)
5700                 {
5701                         t1 = p1[plane->type] - plane->dist;
5702                         t2 = p2[plane->type] - plane->dist;
5703                 }
5704                 else
5705                 {
5706                         t1 = DotProduct (plane->normal, p1) - plane->dist;
5707                         t2 = DotProduct (plane->normal, p2) - plane->dist;
5708                 }
5709
5710                 if (t1 < 0)
5711                 {
5712                         if (t2 < 0)
5713                         {
5714                                 node = node->children[1];
5715                                 continue;
5716                         }
5717                         side = 1;
5718                 }
5719                 else
5720                 {
5721                         if (t2 >= 0)
5722                         {
5723                                 node = node->children[0];
5724                                 continue;
5725                         }
5726                         side = 0;
5727                 }
5728
5729                 midf = t1 / (t1 - t2);
5730                 VectorLerp(p1, midf, p2, mid);
5731
5732                 // recurse both sides, front side first
5733                 // return 2 if empty is followed by solid (hit something)
5734                 // do not return 2 if both are solid or both empty,
5735                 // or if start is solid and end is empty
5736                 // as these degenerate cases usually indicate the eye is in solid and
5737                 // should see the target point anyway
5738                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side    ], p1, mid);
5739                 if (ret != 0)
5740                         return ret;
5741                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5742                 if (ret != 1)
5743                         return ret;
5744                 return 2;
5745         }
5746         return ((mleaf_t *)node)->clusterindex < 0;
5747 }
5748
5749 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5750 {
5751         if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5752         {
5753                 trace_t trace;
5754                 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5755                 return trace.fraction == 1;
5756         }
5757         else
5758         {
5759                 double tracestart[3], traceend[3];
5760                 VectorCopy(start, tracestart);
5761                 VectorCopy(end, traceend);
5762                 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5763         }
5764 }
5765
5766 static void Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t point)
5767 {
5768         const bih_leaf_t *leaf;
5769         const bih_node_t *node;
5770         const colbrushf_t *brush;
5771         int axis;
5772         while (nodenum >= 0)
5773         {
5774                 node = model->collision_bih.nodes + nodenum;
5775                 axis = node->type - BIH_SPLITX;
5776                 if (point[axis] <= node->backmax)
5777                 {
5778                         if (point[axis] >= node->frontmin)
5779                                 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, node->front, point);
5780                         nodenum = node->back;
5781                 }
5782                 else if (point[axis] >= node->frontmin)
5783                         nodenum = node->front;
5784                 else // no overlap with either child?  just return
5785                         return;
5786         }
5787         if (!model->collision_bih.leafs)
5788                 return;
5789         leaf = model->collision_bih.leafs + (-1-nodenum);
5790         switch(leaf->type)
5791         {
5792         case BIH_BRUSH:
5793                 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5794                 Collision_TracePointBrushFloat(trace, point, brush);
5795                 break;
5796         case BIH_COLLISIONTRIANGLE:
5797                 // collision triangle - skipped because they have no volume
5798                 break;
5799         case BIH_RENDERTRIANGLE:
5800                 // render triangle - skipped because they have no volume
5801                 break;
5802         }
5803 }
5804
5805 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)
5806 {
5807         const bih_leaf_t *leaf;
5808         const bih_node_t *node;
5809         const colbrushf_t *brush;
5810         const int *e;
5811         const texture_t *texture;
5812         int axis;
5813 #define BIHLINECLIP
5814 #ifdef BIHLINECLIP
5815         int sideflags;
5816         vec_t frontdist1;
5817         vec_t frontdist2;
5818         vec_t frontfrac;
5819         vec_t backdist1;
5820         vec_t backdist2;
5821         vec_t backfrac;
5822         vec3_t clipped, newstart, newend;
5823 #endif
5824         vec3_t segmentmins;
5825         vec3_t segmentmaxs;
5826         segmentmins[0] = min(start[0], end[0]);
5827         segmentmins[1] = min(start[1], end[1]);
5828         segmentmins[2] = min(start[2], end[2]);
5829         segmentmaxs[0] = max(start[0], end[0]);
5830         segmentmaxs[1] = max(start[1], end[1]);
5831         segmentmaxs[2] = max(start[2], end[2]);
5832         while (nodenum >= 0)
5833         {
5834                 node = model->collision_bih.nodes + nodenum;
5835 #if 0
5836                 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
5837                         return;
5838 #endif
5839                 axis = node->type - BIH_SPLITX;
5840 #if 0
5841                 if (segmentmins[axis] <= node->backmax)
5842                 {
5843                         if (segmentmaxs[axis] >= node->frontmin)
5844                                 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5845                         nodenum = node->back;
5846                 }
5847                 else if (segmentmaxs[axis] >= node->frontmin)
5848                         nodenum = node->front;
5849                 else
5850                         return; // trace falls between children
5851 #else
5852                 frontdist1 = start[axis] - node->frontmin;
5853                 frontdist2 = end[axis] - node->frontmin;
5854                 backdist1 = start[axis] - node->backmax;
5855                 backdist2 = end[axis] - node->backmax;
5856                 sideflags = 0;
5857                 if (frontdist1 < 0)
5858                         sideflags |= 1;
5859                 if (frontdist2 < 0)
5860                         sideflags |= 2;
5861                 if (backdist1 < 0)
5862                         sideflags |= 4;
5863                 if (backdist2 < 0)
5864                         sideflags |= 8;
5865 #if 0
5866                 if (sideflags & 12)
5867                 {
5868                         if ((sideflags & 3) != 3)
5869                                 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5870                         nodenum = node->back;
5871                 }
5872                 else if ((sideflags & 3) != 3)
5873                         nodenum = node->front;
5874                 else
5875                         return; // trace falls between children
5876 #else
5877                 switch(sideflags)
5878                 {
5879                 case 0:
5880                         // start end START END
5881                         nodenum = node->front;
5882                         continue;
5883                 case 1:
5884                         // START end START END
5885 #ifdef BIHLINECLIP
5886                         frontfrac = frontdist1 / (frontdist1 - frontdist2);
5887                         VectorLerp(start, frontfrac, end, newstart); start = newstart;
5888                         segmentmins[0] = min(start[0], end[0]);
5889                         segmentmins[1] = min(start[1], end[1]);
5890                         segmentmins[2] = min(start[2], end[2]);
5891                         segmentmaxs[0] = max(start[0], end[0]);
5892                         segmentmaxs[1] = max(start[1], end[1]);
5893                         segmentmaxs[2] = max(start[2], end[2]);
5894 #endif
5895                         nodenum = node->front;
5896                         break;
5897                 case 2:
5898 #ifdef BIHLINECLIP
5899                         // start END START END
5900                         frontfrac = frontdist1 / (frontdist1 - frontdist2);
5901                         VectorLerp(start, frontfrac, end, newend); end = newend;
5902                         segmentmins[0] = min(start[0], end[0]);
5903                         segmentmins[1] = min(start[1], end[1]);
5904                         segmentmins[2] = min(start[2], end[2]);
5905                         segmentmaxs[0] = max(start[0], end[0]);
5906                         segmentmaxs[1] = max(start[1], end[1]);
5907                         segmentmaxs[2] = max(start[2], end[2]);
5908 #endif
5909                         nodenum = node->front;
5910                         break;
5911                 case 3:
5912                         // START END START END
5913                         return; // line falls in gap between children
5914                 case 4:
5915                         // start end start END
5916                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5917 #ifdef BIHLINECLIP
5918                         backfrac = backdist1 / (backdist1 - backdist2);
5919                         VectorLerp(start, backfrac, end, newend); end = newend;
5920                         segmentmins[0] = min(start[0], end[0]);
5921                         segmentmins[1] = min(start[1], end[1]);
5922                         segmentmins[2] = min(start[2], end[2]);
5923                         segmentmaxs[0] = max(start[0], end[0]);
5924                         segmentmaxs[1] = max(start[1], end[1]);
5925                         segmentmaxs[2] = max(start[2], end[2]);
5926 #endif
5927                         nodenum = node->back;
5928                         break;
5929                 case 5:
5930                         // START end start END
5931 #ifdef BIHLINECLIP
5932                         frontfrac = frontdist1 / (frontdist1 - frontdist2);
5933                         VectorLerp(start, frontfrac, end, clipped);
5934                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
5935                         backfrac = backdist1 / (backdist1 - backdist2);
5936                         VectorLerp(start, backfrac, end, newend); end = newend;
5937                         segmentmins[0] = min(start[0], end[0]);
5938                         segmentmins[1] = min(start[1], end[1]);
5939                         segmentmins[2] = min(start[2], end[2]);
5940                         segmentmaxs[0] = max(start[0], end[0]);
5941                         segmentmaxs[1] = max(start[1], end[1]);
5942                         segmentmaxs[2] = max(start[2], end[2]);
5943 #else
5944                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5945 #endif
5946                         nodenum = node->back;
5947                         break;
5948                 case 6:
5949                         // start END start END
5950 #ifdef BIHLINECLIP
5951                         frontfrac = frontdist1 / (frontdist1 - frontdist2);
5952                         VectorLerp(start, frontfrac, end, clipped);
5953                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
5954                         backfrac = backdist1 / (backdist1 - backdist2);
5955                         VectorLerp(start, backfrac, end, newend); end = newend;
5956                         segmentmins[0] = min(start[0], end[0]);
5957                         segmentmins[1] = min(start[1], end[1]);
5958                         segmentmins[2] = min(start[2], end[2]);
5959                         segmentmaxs[0] = max(start[0], end[0]);
5960                         segmentmaxs[1] = max(start[1], end[1]);
5961                         segmentmaxs[2] = max(start[2], end[2]);
5962 #else
5963                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5964 #endif
5965                         nodenum = node->back;
5966                         break;
5967                 case 7:
5968                         // START END start END
5969 #ifdef BIHLINECLIP
5970                         backfrac = backdist1 / (backdist1 - backdist2);
5971                         VectorLerp(start, backfrac, end, newend); end = newend;
5972                         segmentmins[0] = min(start[0], end[0]);
5973                         segmentmins[1] = min(start[1], end[1]);
5974                         segmentmins[2] = min(start[2], end[2]);
5975                         segmentmaxs[0] = max(start[0], end[0]);
5976                         segmentmaxs[1] = max(start[1], end[1]);
5977                         segmentmaxs[2] = max(start[2], end[2]);
5978 #endif
5979                         nodenum = node->back;
5980                         break;
5981                 case 8:
5982                         // start end START end
5983                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5984 #ifdef BIHLINECLIP
5985                         backfrac = backdist1 / (backdist1 - backdist2);
5986                         VectorLerp(start, backfrac, end, newstart); start = newstart;
5987                         segmentmins[0] = min(start[0], end[0]);
5988                         segmentmins[1] = min(start[1], end[1]);
5989                         segmentmins[2] = min(start[2], end[2]);
5990                         segmentmaxs[0] = max(start[0], end[0]);
5991                         segmentmaxs[1] = max(start[1], end[1]);
5992                         segmentmaxs[2] = max(start[2], end[2]);
5993 #endif
5994                         nodenum = node->back;
5995                         break;
5996                 case 9:
5997                         // START end START end
5998 #ifdef BIHLINECLIP
5999                         frontfrac = frontdist1 / (frontdist1 - frontdist2);
6000                         VectorLerp(start, frontfrac, end, clipped);
6001                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
6002                         backfrac = backdist1 / (backdist1 - backdist2);
6003                         VectorLerp(start, backfrac, end, newstart); start = newstart;
6004                         segmentmins[0] = min(start[0], end[0]);
6005                         segmentmins[1] = min(start[1], end[1]);
6006                         segmentmins[2] = min(start[2], end[2]);
6007                         segmentmaxs[0] = max(start[0], end[0]);
6008                         segmentmaxs[1] = max(start[1], end[1]);
6009                         segmentmaxs[2] = max(start[2], end[2]);
6010 #else
6011                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6012 #endif
6013                         nodenum = node->back;
6014                         break;
6015                 case 10:
6016                         // start END START end
6017 #ifdef BIHLINECLIP
6018                         frontfrac = frontdist1 / (frontdist1 - frontdist2);
6019                         VectorLerp(start, frontfrac, end, clipped);
6020                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
6021                         backfrac = backdist1 / (backdist1 - backdist2);
6022                         VectorLerp(start, backfrac, end, newstart); start = newstart;
6023                         segmentmins[0] = min(start[0], end[0]);
6024                         segmentmins[1] = min(start[1], end[1]);
6025                         segmentmins[2] = min(start[2], end[2]);
6026                         segmentmaxs[0] = max(start[0], end[0]);
6027                         segmentmaxs[1] = max(start[1], end[1]);
6028                         segmentmaxs[2] = max(start[2], end[2]);
6029 #else
6030                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6031 #endif
6032                         nodenum = node->back;
6033                         break;
6034                 case 11:
6035                         // START END START end
6036 #ifdef BIHLINECLIP
6037                         backfrac = backdist1 / (backdist1 - backdist2);
6038                         VectorLerp(start, backfrac, end, newstart); start = newstart;
6039                         segmentmins[0] = min(start[0], end[0]);
6040                         segmentmins[1] = min(start[1], end[1]);
6041                         segmentmins[2] = min(start[2], end[2]);
6042                         segmentmaxs[0] = max(start[0], end[0]);
6043                         segmentmaxs[1] = max(start[1], end[1]);
6044                         segmentmaxs[2] = max(start[2], end[2]);
6045 #endif
6046                         nodenum = node->back;
6047                         break;
6048                 case 12:
6049                         // start end start end
6050                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6051                         nodenum = node->back;
6052                         break;
6053                 case 13:
6054                         // START end start end
6055 #ifdef BIHLINECLIP
6056                         frontfrac = frontdist1 / (frontdist1 - frontdist2);
6057                         VectorLerp(start, frontfrac, end, clipped);
6058                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
6059 #else
6060                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6061 #endif
6062                         nodenum = node->back;
6063                         break;
6064                 case 14:
6065                         // start END start end
6066 #ifdef BIHLINECLIP
6067                         frontfrac = frontdist1 / (frontdist1 - frontdist2);
6068                         VectorLerp(start, frontfrac, end, clipped);
6069                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
6070 #else
6071                         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6072 #endif
6073                         nodenum = node->back;
6074                         break;
6075                 case 15:
6076                         // START END start end
6077                         nodenum = node->back;
6078                         continue;
6079                 }
6080 #endif
6081 #endif
6082         }
6083         if (!model->collision_bih.leafs)
6084                 return;
6085         leaf = model->collision_bih.leafs + (-1-nodenum);
6086 #if 1
6087         if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6088                 return;
6089 #endif
6090         switch(leaf->type)
6091         {
6092         case BIH_BRUSH:
6093                 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6094                 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6095                 break;
6096         case BIH_COLLISIONTRIANGLE:
6097                 if (!mod_q3bsp_curves_collisions.integer)
6098                         return;
6099                 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6100                 texture = model->data_textures + leaf->textureindex;
6101                 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);
6102                 break;
6103         case BIH_RENDERTRIANGLE:
6104                 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6105                 texture = model->data_textures + leaf->textureindex;
6106                 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);
6107                 break;
6108         }
6109 }
6110
6111 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)
6112 {
6113         const bih_leaf_t *leaf;
6114         const bih_node_t *node;
6115         const colbrushf_t *brush;
6116         const int *e;
6117         const texture_t *texture;
6118         int axis;
6119         while (nodenum >= 0)
6120         {
6121                 node = model->collision_bih.nodes + nodenum;
6122                 axis = node->type - BIH_SPLITX;
6123 #if 1
6124                 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6125                         return;
6126 #endif
6127 #if 0
6128                 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6129                 nodenum = node->back;
6130                 continue;
6131 #endif
6132                 if (segmentmins[axis] <= node->backmax)
6133                 {
6134                         if (segmentmaxs[axis] >= node->frontmin)
6135                                 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6136                         nodenum = node->back;
6137                 }
6138                 else if (segmentmaxs[axis] >= node->frontmin)
6139                         nodenum = node->front;
6140                 else
6141                         return; // trace falls between children
6142         }
6143         if (!model->collision_bih.leafs)
6144                 return;
6145         leaf = model->collision_bih.leafs + (-1-nodenum);
6146 #if 1
6147         if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6148                 return;
6149 #endif
6150         switch(leaf->type)
6151         {
6152         case BIH_BRUSH:
6153                 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6154                 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6155                 break;
6156         case BIH_COLLISIONTRIANGLE:
6157                 if (!mod_q3bsp_curves_collisions.integer)
6158                         return;
6159                 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6160                 texture = model->data_textures + leaf->textureindex;
6161                 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);
6162                 break;
6163         case BIH_RENDERTRIANGLE:
6164                 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6165                 texture = model->data_textures + leaf->textureindex;
6166                 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);
6167                 break;
6168         }
6169 }
6170
6171 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)
6172 {
6173         memset(trace, 0, sizeof(*trace));
6174         trace->fraction = 1;
6175         trace->realfraction = 1;
6176         trace->hitsupercontentsmask = hitsupercontentsmask;
6177         Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6178 }
6179
6180 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)
6181 {
6182         if (VectorCompare(start, end))
6183         {
6184                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6185                 return;
6186         }
6187
6188         memset(trace, 0, sizeof(*trace));
6189         trace->fraction = 1;
6190         trace->realfraction = 1;
6191         trace->hitsupercontentsmask = hitsupercontentsmask;
6192         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6193 }
6194
6195 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)
6196 {
6197         float segmentmins[3], segmentmaxs[3];
6198         colboxbrushf_t thisbrush_start, thisbrush_end;
6199         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6200
6201         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6202         {
6203                 vec3_t shiftstart, shiftend;
6204                 VectorAdd(start, boxmins, shiftstart);
6205                 VectorAdd(end, boxmins, shiftend);
6206                 if (VectorCompare(start, end))
6207                         Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6208                 else
6209                         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6210                 return;
6211         }
6212
6213         // box trace, performed as brush trace
6214         memset(trace, 0, sizeof(*trace));
6215         trace->fraction = 1;
6216         trace->realfraction = 1;
6217         trace->hitsupercontentsmask = hitsupercontentsmask;
6218         segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6219         segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6220         segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6221         segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6222         segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6223         segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6224         VectorAdd(start, boxmins, boxstartmins);
6225         VectorAdd(start, boxmaxs, boxstartmaxs);
6226         VectorAdd(end, boxmins, boxendmins);
6227         VectorAdd(end, boxmaxs, boxendmaxs);
6228         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6229         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6230         Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6231 }
6232
6233 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)
6234 {
6235         float segmentmins[3], segmentmaxs[3];
6236
6237         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6238         {
6239                 if (VectorCompare(start->mins, end->mins))
6240                         Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6241                 else
6242                         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6243                 return;
6244         }
6245
6246         // box trace, performed as brush trace
6247         memset(trace, 0, sizeof(*trace));
6248         trace->fraction = 1;
6249         trace->realfraction = 1;
6250         trace->hitsupercontentsmask = hitsupercontentsmask;
6251         segmentmins[0] = min(start->mins[0], end->mins[0]);
6252         segmentmins[1] = min(start->mins[1], end->mins[1]);
6253         segmentmins[2] = min(start->mins[2], end->mins[2]);
6254         segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6255         segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6256         segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6257         Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, segmentmins, segmentmaxs);
6258 }
6259
6260 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6261 {
6262         trace_t trace;
6263         Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6264         return trace.startsupercontents;
6265 }
6266
6267 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)
6268 {
6269 #if 0
6270         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6271         vec3_t end;
6272         int hitsupercontents;
6273         VectorSet(end, start[0], start[1], model->normalmins[2]);
6274 #endif
6275         memset(trace, 0, sizeof(*trace));
6276         trace->fraction = 1;
6277         trace->realfraction = 1;
6278         trace->hitsupercontentsmask = hitsupercontentsmask;
6279 #if 0
6280         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6281         hitsupercontents = trace->hitsupercontents;
6282         memset(trace, 0, sizeof(*trace));
6283         trace->fraction = 1;
6284         trace->realfraction = 1;
6285         trace->hitsupercontentsmask = hitsupercontentsmask;
6286         trace->startsupercontents = hitsupercontents;
6287 #endif
6288 }
6289
6290 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6291 {
6292 #if 0
6293         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6294         trace_t trace;
6295         vec3_t end;
6296         VectorSet(end, start[0], start[1], model->normalmins[2]);
6297         memset(&trace, 0, sizeof(trace));
6298         trace.fraction = 1;
6299         trace.realfraction = 1;
6300         trace.hitsupercontentsmask = 0;
6301         Mod_CollisionBIH_TraceLine_RecursiveBIHNode(&trace, model, model->collision_bih.rootnode, start, end, start, end);
6302         return trace.hitsupercontents;
6303 #else
6304         return 0;
6305 #endif
6306 }
6307
6308 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6309 {
6310         int i;
6311         mleaf_t *leaf;
6312         colbrushf_t *brush;
6313         // find which leaf the point is in
6314         while (node->plane)
6315                 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6316         // point trace the brushes
6317         leaf = (mleaf_t *)node;
6318         for (i = 0;i < leaf->numleafbrushes;i++)
6319         {
6320                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6321                 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6322                 {
6323                         brush->markframe = markframe;
6324                         Collision_TracePointBrushFloat(trace, point, brush);
6325                 }
6326         }
6327         // can't do point traces on curves (they have no thickness)
6328 }
6329
6330 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)
6331 {
6332         int i, startside, endside;
6333         float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6334         mleaf_t *leaf;
6335         msurface_t *surface;
6336         mplane_t *plane;
6337         colbrushf_t *brush;
6338         // walk the tree until we hit a leaf, recursing for any split cases
6339         while (node->plane)
6340         {
6341 #if 0
6342                 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6343                         return;
6344                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6345                 node = node->children[1];
6346 #else
6347                 // abort if this part of the bsp tree can not be hit by this trace
6348 //              if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6349 //                      return;
6350                 plane = node->plane;
6351                 // axial planes are much more common than non-axial, so an optimized
6352                 // axial case pays off here
6353                 if (plane->type < 3)
6354                 {
6355                         dist1 = start[plane->type] - plane->dist;
6356                         dist2 = end[plane->type] - plane->dist;
6357                 }
6358                 else
6359                 {
6360                         dist1 = DotProduct(start, plane->normal) - plane->dist;
6361                         dist2 = DotProduct(end, plane->normal) - plane->dist;
6362                 }
6363                 startside = dist1 < 0;
6364                 endside = dist2 < 0;
6365                 if (startside == endside)
6366                 {
6367                         // most of the time the line fragment is on one side of the plane
6368                         node = node->children[startside];
6369                 }
6370                 else
6371                 {
6372                         // line crosses node plane, split the line
6373                         dist1 = PlaneDiff(linestart, plane);
6374                         dist2 = PlaneDiff(lineend, plane);
6375                         midfrac = dist1 / (dist1 - dist2);
6376                         VectorLerp(linestart, midfrac, lineend, mid);
6377                         // take the near side first
6378                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6379                         // if we found an impact on the front side, don't waste time
6380                         // exploring the far side
6381                         if (midfrac <= trace->realfraction)
6382                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6383                         return;
6384                 }
6385 #endif
6386         }
6387         // abort if this part of the bsp tree can not be hit by this trace
6388 //      if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6389 //              return;
6390         // hit a leaf
6391         nodesegmentmins[0] = min(start[0], end[0]) - 1;
6392         nodesegmentmins[1] = min(start[1], end[1]) - 1;
6393         nodesegmentmins[2] = min(start[2], end[2]) - 1;
6394         nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6395         nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6396         nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6397         // line trace the brushes
6398         leaf = (mleaf_t *)node;
6399 #if 0
6400         if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6401                 return;
6402 #endif
6403         for (i = 0;i < leaf->numleafbrushes;i++)
6404         {
6405                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6406                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6407                 {
6408                         brush->markframe = markframe;
6409                         Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6410                 }
6411         }
6412         // can't do point traces on curves (they have no thickness)
6413         if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6414         {
6415                 // line trace the curves
6416                 for (i = 0;i < leaf->numleafsurfaces;i++)
6417                 {
6418                         surface = model->data_surfaces + leaf->firstleafsurface[i];
6419                         if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6420                         {
6421                                 surface->deprecatedq3collisionmarkframe = markframe;
6422                                 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);
6423                         }
6424                 }
6425         }
6426 }
6427
6428 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)
6429 {
6430         int i;
6431         int sides;
6432         mleaf_t *leaf;
6433         colbrushf_t *brush;
6434         msurface_t *surface;
6435         mplane_t *plane;
6436         float nodesegmentmins[3], nodesegmentmaxs[3];
6437         // walk the tree until we hit a leaf, recursing for any split cases
6438         while (node->plane)
6439         {
6440 #if 0
6441                 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6442                         return;
6443                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6444                 node = node->children[1];
6445 #else
6446                 // abort if this part of the bsp tree can not be hit by this trace
6447 //              if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6448 //                      return;
6449                 plane = node->plane;
6450                 // axial planes are much more common than non-axial, so an optimized
6451                 // axial case pays off here
6452                 if (plane->type < 3)
6453                 {
6454                         // this is an axial plane, compare bounding box directly to it and
6455                         // recurse sides accordingly
6456                         // recurse down node sides
6457                         // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6458                         //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6459                         //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6460                         sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6461                 }
6462                 else
6463                 {
6464                         // this is a non-axial plane, so check if the start and end boxes
6465                         // are both on one side of the plane to handle 'diagonal' cases
6466                         sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6467                 }
6468                 if (sides == 3)
6469                 {
6470                         // segment crosses plane
6471                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6472                         sides = 2;
6473                 }
6474                 // if sides == 0 then the trace itself is bogus (Not A Number values),
6475                 // in this case we simply pretend the trace hit nothing
6476                 if (sides == 0)
6477                         return; // ERROR: NAN bounding box!
6478                 // take whichever side the segment box is on
6479                 node = node->children[sides - 1];
6480 #endif
6481         }
6482         // abort if this part of the bsp tree can not be hit by this trace
6483 //      if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6484 //              return;
6485         nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6486         nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6487         nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6488         nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6489         nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6490         nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6491         // hit a leaf
6492         leaf = (mleaf_t *)node;
6493 #if 0
6494         if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6495                 return;
6496 #endif
6497         for (i = 0;i < leaf->numleafbrushes;i++)
6498         {
6499                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6500                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6501                 {
6502                         brush->markframe = markframe;
6503                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6504                 }
6505         }
6506         if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6507         {
6508                 for (i = 0;i < leaf->numleafsurfaces;i++)
6509                 {
6510                         surface = model->data_surfaces + leaf->firstleafsurface[i];
6511                         if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6512                         {
6513                                 surface->deprecatedq3collisionmarkframe = markframe;
6514                                 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);
6515                         }
6516                 }
6517         }
6518 }
6519
6520
6521 static int markframe = 0;
6522
6523 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)
6524 {
6525         int i;
6526         q3mbrush_t *brush;
6527         memset(trace, 0, sizeof(*trace));
6528         trace->fraction = 1;
6529         trace->realfraction = 1;
6530         trace->hitsupercontentsmask = hitsupercontentsmask;
6531         if (mod_collision_bih.integer)
6532                 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6533         else if (model->brush.submodel)
6534         {
6535                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6536                         if (brush->colbrushf)
6537                                 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6538         }
6539         else
6540                 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6541 }
6542
6543 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)
6544 {
6545         int i;
6546         float segmentmins[3], segmentmaxs[3];
6547         msurface_t *surface;
6548         q3mbrush_t *brush;
6549
6550         if (VectorCompare(start, end))
6551         {
6552                 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6553                 return;
6554         }
6555
6556         memset(trace, 0, sizeof(*trace));
6557         trace->fraction = 1;
6558         trace->realfraction = 1;
6559         trace->hitsupercontentsmask = hitsupercontentsmask;
6560         segmentmins[0] = min(start[0], end[0]) - 1;
6561         segmentmins[1] = min(start[1], end[1]) - 1;
6562         segmentmins[2] = min(start[2], end[2]) - 1;
6563         segmentmaxs[0] = max(start[0], end[0]) + 1;
6564         segmentmaxs[1] = max(start[1], end[1]) + 1;
6565         segmentmaxs[2] = max(start[2], end[2]) + 1;
6566         if (mod_collision_bih.integer)
6567                 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6568         else if (model->brush.submodel)
6569         {
6570                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6571                         if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6572                                 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6573                 if (mod_q3bsp_curves_collisions.integer)
6574                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6575                                 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6576                                         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);
6577         }
6578         else
6579                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6580 }
6581
6582 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)
6583 {
6584         int i;
6585         float segmentmins[3], segmentmaxs[3];
6586         msurface_t *surface;
6587         q3mbrush_t *brush;
6588         colboxbrushf_t thisbrush_start, thisbrush_end;
6589         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6590
6591         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6592         {
6593                 vec3_t shiftstart, shiftend;
6594                 VectorAdd(start, boxmins, shiftstart);
6595                 VectorAdd(end, boxmins, shiftend);
6596                 if (VectorCompare(start, end))
6597                         Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6598                 else
6599                         Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6600                 return;
6601         }
6602
6603         // box trace, performed as brush trace
6604         memset(trace, 0, sizeof(*trace));
6605         trace->fraction = 1;
6606         trace->realfraction = 1;
6607         trace->hitsupercontentsmask = hitsupercontentsmask;
6608         segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6609         segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6610         segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6611         segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6612         segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6613         segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6614         VectorAdd(start, boxmins, boxstartmins);
6615         VectorAdd(start, boxmaxs, boxstartmaxs);
6616         VectorAdd(end, boxmins, boxendmins);
6617         VectorAdd(end, boxmaxs, boxendmaxs);
6618         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6619         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6620         if (mod_collision_bih.integer)
6621                 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6622         else if (model->brush.submodel)
6623         {
6624                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6625                         if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6626                                 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, brush->colbrushf, brush->colbrushf);
6627                 if (mod_q3bsp_curves_collisions.integer)
6628                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6629                                 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6630                                         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);
6631         }
6632         else
6633                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, &thisbrush_start.brush, &thisbrush_end.brush, ++markframe, segmentmins, segmentmaxs);
6634 }
6635
6636 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)
6637 {
6638         float segmentmins[3], segmentmaxs[3];
6639         int i;
6640         msurface_t *surface;
6641         q3mbrush_t *brush;
6642
6643         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6644         {
6645                 if (VectorCompare(start->mins, end->mins))
6646                         Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6647                 else
6648                         Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6649                 return;
6650         }
6651
6652         // box trace, performed as brush trace
6653         memset(trace, 0, sizeof(*trace));
6654         trace->fraction = 1;
6655         trace->realfraction = 1;
6656         trace->hitsupercontentsmask = hitsupercontentsmask;
6657         segmentmins[0] = min(start->mins[0], end->mins[0]);
6658         segmentmins[1] = min(start->mins[1], end->mins[1]);
6659         segmentmins[2] = min(start->mins[2], end->mins[2]);
6660         segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6661         segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6662         segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6663         if (mod_collision_bih.integer)
6664                 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, segmentmins, segmentmaxs);
6665         else if (model->brush.submodel)
6666         {
6667                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6668                         if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6669                                 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6670                 if (mod_q3bsp_curves_collisions.integer)
6671                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6672                                 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6673                                         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);
6674         }
6675         else
6676                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6677 }
6678
6679 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6680 {
6681         int i;
6682         int supercontents = 0;
6683         q3mbrush_t *brush;
6684         if (mod_collision_bih.integer)
6685         {
6686                 trace_t trace;
6687                 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6688                 supercontents = trace.startsupercontents;
6689         }
6690         // test if the point is inside each brush
6691         else if (model->brush.submodel)
6692         {
6693                 // submodels are effectively one leaf
6694                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6695                         if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6696                                 supercontents |= brush->colbrushf->supercontents;
6697         }
6698         else
6699         {
6700                 mnode_t *node = model->brush.data_nodes;
6701                 mleaf_t *leaf;
6702                 // find which leaf the point is in
6703                 while (node->plane)
6704                         node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6705                 leaf = (mleaf_t *)node;
6706                 // now check the brushes in the leaf
6707                 for (i = 0;i < leaf->numleafbrushes;i++)
6708                 {
6709                         brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6710                         if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6711                                 supercontents |= brush->colbrushf->supercontents;
6712                 }
6713         }
6714         return supercontents;
6715 }
6716
6717 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6718 {
6719         int j;
6720         int bihnumleafs;
6721         int bihmaxnodes;
6722         int brushindex;
6723         int triangleindex;
6724         int bihleafindex;
6725         int nummodelbrushes = model->nummodelbrushes;
6726         int nummodelsurfaces = model->nummodelsurfaces;
6727         const int *e;
6728         const int *collisionelement3i;
6729         const float *collisionvertex3f;
6730         const int *renderelement3i;
6731         const float *rendervertex3f;
6732         bih_leaf_t *bihleafs;
6733         bih_node_t *bihnodes;
6734         int *temp_leafsort;
6735         int *temp_leafsortscratch;
6736         const msurface_t *surface;
6737         const q3mbrush_t *brush;
6738
6739         // find out how many BIH leaf nodes we need
6740         bihnumleafs = 0;
6741         if (userendersurfaces)
6742         {
6743                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6744                         bihnumleafs += surface->num_triangles;
6745         }
6746         else
6747         {
6748                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6749                         if (brush->colbrushf)
6750                                 bihnumleafs++;
6751                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6752                 {
6753                         if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6754                                 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6755                         else
6756                                 bihnumleafs += surface->num_collisiontriangles;
6757                 }
6758         }
6759
6760         if (!bihnumleafs)
6761                 return NULL;
6762
6763         // allocate the memory for the BIH leaf nodes
6764         bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6765
6766         // now populate the BIH leaf nodes
6767         bihleafindex = 0;
6768
6769         // add render surfaces
6770         renderelement3i = model->surfmesh.data_element3i;
6771         rendervertex3f = model->surfmesh.data_vertex3f;
6772         for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6773         {
6774                 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6775                 {
6776                         if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6777                                 continue;
6778                         bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6779                         bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6780                         bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6781                         bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6782                         bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6783                         bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6784                         bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6785                         bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6786                         bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6787                         bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6788                         bihleafindex++;
6789                 }
6790         }
6791
6792         if (!userendersurfaces)
6793         {
6794                 // add collision brushes
6795                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6796                 {
6797                         if (!brush->colbrushf)
6798                                 continue;
6799                         bihleafs[bihleafindex].type = BIH_BRUSH;
6800                         bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6801                         bihleafs[bihleafindex].surfaceindex = -1;
6802                         bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6803                         VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6804                         VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6805                         bihleafindex++;
6806                 }
6807
6808                 // add collision surfaces
6809                 collisionelement3i = model->brush.data_collisionelement3i;
6810                 collisionvertex3f = model->brush.data_collisionvertex3f;
6811                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6812                 {
6813                         for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6814                         {
6815                                 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6816                                 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6817                                 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6818                                 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6819                                 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6820                                 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6821                                 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6822                                 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6823                                 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6824                                 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6825                                 bihleafindex++;
6826                         }
6827                 }
6828         }
6829
6830         // allocate buffers for the produced and temporary data
6831         bihmaxnodes = bihnumleafs - 1;
6832         bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6833         temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6834         temp_leafsortscratch = temp_leafsort + bihnumleafs;
6835
6836         // now build it
6837         BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6838
6839         // we're done with the temporary data
6840         Mem_Free(temp_leafsort);
6841
6842         // resize the BIH nodes array if it over-allocated
6843         if (out->maxnodes > out->numnodes)
6844         {
6845                 out->maxnodes = out->numnodes;
6846                 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
6847         }
6848
6849         return out;
6850 }
6851
6852 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6853 {
6854         int supercontents = 0;
6855         if (nativecontents & CONTENTSQ3_SOLID)
6856                 supercontents |= SUPERCONTENTS_SOLID;
6857         if (nativecontents & CONTENTSQ3_WATER)
6858                 supercontents |= SUPERCONTENTS_WATER;
6859         if (nativecontents & CONTENTSQ3_SLIME)
6860                 supercontents |= SUPERCONTENTS_SLIME;
6861         if (nativecontents & CONTENTSQ3_LAVA)
6862                 supercontents |= SUPERCONTENTS_LAVA;
6863         if (nativecontents & CONTENTSQ3_BODY)
6864                 supercontents |= SUPERCONTENTS_BODY;
6865         if (nativecontents & CONTENTSQ3_CORPSE)
6866                 supercontents |= SUPERCONTENTS_CORPSE;
6867         if (nativecontents & CONTENTSQ3_NODROP)
6868                 supercontents |= SUPERCONTENTS_NODROP;
6869         if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6870                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6871         if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6872                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6873         if (nativecontents & CONTENTSQ3_DONOTENTER)
6874                 supercontents |= SUPERCONTENTS_DONOTENTER;
6875         if (nativecontents & CONTENTSQ3_BOTCLIP)
6876                 supercontents |= SUPERCONTENTS_BOTCLIP;
6877         if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6878                 supercontents |= SUPERCONTENTS_OPAQUE;
6879         return supercontents;
6880 }
6881
6882 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6883 {
6884         int nativecontents = 0;
6885         if (supercontents & SUPERCONTENTS_SOLID)
6886                 nativecontents |= CONTENTSQ3_SOLID;
6887         if (supercontents & SUPERCONTENTS_WATER)
6888                 nativecontents |= CONTENTSQ3_WATER;
6889         if (supercontents & SUPERCONTENTS_SLIME)
6890                 nativecontents |= CONTENTSQ3_SLIME;
6891         if (supercontents & SUPERCONTENTS_LAVA)
6892                 nativecontents |= CONTENTSQ3_LAVA;
6893         if (supercontents & SUPERCONTENTS_BODY)
6894                 nativecontents |= CONTENTSQ3_BODY;
6895         if (supercontents & SUPERCONTENTS_CORPSE)
6896                 nativecontents |= CONTENTSQ3_CORPSE;
6897         if (supercontents & SUPERCONTENTS_NODROP)
6898                 nativecontents |= CONTENTSQ3_NODROP;
6899         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6900                 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6901         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6902                 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6903         if (supercontents & SUPERCONTENTS_DONOTENTER)
6904                 nativecontents |= CONTENTSQ3_DONOTENTER;
6905         if (supercontents & SUPERCONTENTS_BOTCLIP)
6906                 nativecontents |= CONTENTSQ3_BOTCLIP;
6907         if (!(supercontents & SUPERCONTENTS_OPAQUE))
6908                 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6909         return nativecontents;
6910 }
6911
6912 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6913 {
6914         int numleafs;
6915         while (node->plane)
6916         {
6917                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6918                 node = node->children[1];
6919         }
6920         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6921         if (loadmodel->brush.num_leafs < numleafs)
6922                 loadmodel->brush.num_leafs = numleafs;
6923 }
6924
6925 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6926 {
6927         int i, j, lumps;
6928         q3dheader_t *header;
6929         float corner[3], yawradius, modelradius;
6930
6931         mod->modeldatatypestring = "Q3BSP";
6932
6933         mod->type = mod_brushq3;
6934         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6935         mod->numskins = 1;
6936
6937         header = (q3dheader_t *)buffer;
6938         if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6939                 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6940
6941         i = LittleLong(header->version);
6942         if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6943                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6944
6945         mod->soundfromcenter = true;
6946         mod->TraceBox = Mod_Q3BSP_TraceBox;
6947         mod->TraceBrush = Mod_Q3BSP_TraceBrush;
6948         mod->TraceLine = Mod_Q3BSP_TraceLine;
6949         mod->TracePoint = Mod_Q3BSP_TracePoint;
6950         mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6951         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6952         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6953         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6954         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6955         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6956         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6957         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6958         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6959         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6960         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6961         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6962         mod->brush.AmbientSoundLevelsForPoint = NULL;
6963         mod->brush.RoundUpToHullSize = NULL;
6964         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6965         mod->Draw = R_Q1BSP_Draw;
6966         mod->DrawDepth = R_Q1BSP_DrawDepth;
6967         mod->DrawDebug = R_Q1BSP_DrawDebug;
6968         mod->DrawPrepass = R_Q1BSP_DrawPrepass;
6969         mod->GetLightInfo = R_Q1BSP_GetLightInfo;
6970         mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
6971         mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
6972         mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
6973         mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
6974         mod->DrawLight = R_Q1BSP_DrawLight;
6975
6976         mod_base = (unsigned char *)header;
6977
6978         // swap all the lumps
6979         header->ident = LittleLong(header->ident);
6980         header->version = LittleLong(header->version);
6981         lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
6982         for (i = 0;i < lumps;i++)
6983         {
6984                 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
6985                 if((char *) bufferend < (char *) buffer + j)
6986                         Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
6987                 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
6988                 if((char *) bufferend < (char *) buffer + j)
6989                         Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
6990         }
6991         /*
6992          * NO, do NOT clear them!
6993          * they contain actual data referenced by other stuff.
6994          * Instead, before using the advertisements lump, check header->versio
6995          * again!
6996          * Sorry, but otherwise it breaks memory of the first lump.
6997         for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
6998         {
6999                 header->lumps[i].fileofs = 0;
7000                 header->lumps[i].filelen = 0;
7001         }
7002         */
7003
7004         mod->brush.qw_md4sum = 0;
7005         mod->brush.qw_md4sum2 = 0;
7006         for (i = 0;i < lumps;i++)
7007         {
7008                 if (i == Q3LUMP_ENTITIES)
7009                         continue;
7010                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7011                 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7012                         continue;
7013                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7014
7015                 // all this checksumming can take a while, so let's send keepalives here too
7016                 CL_KeepaliveMessage(false);
7017         }
7018
7019         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7020         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7021         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7022         if (header->version == Q3BSPVERSION_IG)
7023                 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7024         else
7025                 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7026         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7027         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7028         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7029         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7030         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7031         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7032         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7033         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7034         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7035         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7036         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7037         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7038         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7039         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7040
7041         // the MakePortals code works fine on the q3bsp data as well
7042         Mod_Q1BSP_MakePortals();
7043
7044         // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7045         loadmodel->brush.supportwateralpha = true;
7046
7047         // make a single combined shadow mesh to allow optimized shadow volume creation
7048         Mod_Q1BSP_CreateShadowMesh(loadmodel);
7049
7050         loadmodel->brush.num_leafs = 0;
7051         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7052
7053         if (loadmodel->brush.numsubmodels)
7054                 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7055
7056         mod = loadmodel;
7057         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7058         {
7059                 if (i > 0)
7060                 {
7061                         char name[10];
7062                         // duplicate the basic information
7063                         dpsnprintf(name, sizeof(name), "*%i", i);
7064                         mod = Mod_FindName(name, loadmodel->name);
7065                         // copy the base model to this one
7066                         *mod = *loadmodel;
7067                         // rename the clone back to its proper name
7068                         strlcpy(mod->name, name, sizeof(mod->name));
7069                         mod->brush.parentmodel = loadmodel;
7070                         // textures and memory belong to the main model
7071                         mod->texturepool = NULL;
7072                         mod->mempool = NULL;
7073                         mod->brush.GetPVS = NULL;
7074                         mod->brush.FatPVS = NULL;
7075                         mod->brush.BoxTouchingPVS = NULL;
7076                         mod->brush.BoxTouchingLeafPVS = NULL;
7077                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7078                         mod->brush.FindBoxClusters = NULL;
7079                         mod->brush.LightPoint = NULL;
7080                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7081                 }
7082                 mod->brush.submodel = i;
7083                 if (loadmodel->brush.submodels)
7084                         loadmodel->brush.submodels[i] = mod;
7085
7086                 // make the model surface list (used by shadowing/lighting)
7087                 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7088                 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7089                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7090                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7091                 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7092                 Mod_MakeSortedSurfaces(mod);
7093
7094                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7095                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7096                 // enlarge the bounding box to enclose all geometry of this model,
7097                 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7098                 // which can in turn mess up the farclip (as well as culling when
7099                 // outside the level - an unimportant concern)
7100
7101                 //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]);
7102                 for (j = 0;j < mod->nummodelsurfaces;j++)
7103                 {
7104                         const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7105                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7106                         int k;
7107                         if (!surface->num_vertices)
7108                                 continue;
7109                         for (k = 0;k < surface->num_vertices;k++, v += 3)
7110                         {
7111                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7112                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7113                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7114                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7115                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7116                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7117                         }
7118                 }
7119                 //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]);
7120                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7121                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7122                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7123                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7124                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7125                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7126                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7127                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7128                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7129                 mod->yawmins[2] = mod->normalmins[2];
7130                 mod->yawmaxs[2] = mod->normalmaxs[2];
7131                 mod->radius = modelradius;
7132                 mod->radius2 = modelradius * modelradius;
7133
7134                 // this gets altered below if sky or water is used
7135                 mod->DrawSky = NULL;
7136                 mod->DrawAddWaterPlanes = NULL;
7137
7138                 for (j = 0;j < mod->nummodelsurfaces;j++)
7139                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7140                                 break;
7141                 if (j < mod->nummodelsurfaces)
7142                         mod->DrawSky = R_Q1BSP_DrawSky;
7143
7144                 for (j = 0;j < mod->nummodelsurfaces;j++)
7145                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7146                                 break;
7147                 if (j < mod->nummodelsurfaces)
7148                         mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7149
7150                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7151                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7152
7153                 // generate VBOs and other shared data before cloning submodels
7154                 if (i == 0)
7155                         Mod_BuildVBOs();
7156         }
7157
7158         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);
7159 }
7160
7161 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7162 {
7163         int i = LittleLong(((int *)buffer)[1]);
7164         if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7165                 Mod_Q3BSP_Load(mod,buffer, bufferend);
7166         else if (i == Q2BSPVERSION)
7167                 Mod_Q2BSP_Load(mod,buffer, bufferend);
7168         else
7169                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7170 }
7171
7172 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7173 {
7174         Host_Error("Mod_MAP_Load: not yet implemented");
7175 }
7176
7177 #define OBJASMODEL
7178
7179 #ifdef OBJASMODEL
7180 typedef struct objvertex_s
7181 {
7182         int nextindex;
7183         int submodelindex;
7184         int textureindex;
7185         float v[3];
7186         float vt[2];
7187         float vn[3];
7188 }
7189 objvertex_t;
7190
7191 static unsigned char nobsp_pvs[1] = {1};
7192
7193 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7194 {
7195         const char *textbase = (char *)buffer, *text = textbase;
7196         char *s;
7197         char *argv[512];
7198         char line[1024];
7199         char materialname[MAX_QPATH];
7200         int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7201         int index1, index2, index3;
7202         objvertex_t vfirst, vprev, vcurrent;
7203         int argc;
7204         int linelen;
7205         int numtriangles = 0;
7206         int maxtriangles = 0;
7207         objvertex_t *vertices = NULL;
7208         int linenumber = 0;
7209         int maxtextures = 0, numtextures = 0, textureindex = 0;
7210         int maxv = 0, numv = 1;
7211         int maxvt = 0, numvt = 1;
7212         int maxvn = 0, numvn = 1;
7213         char *texturenames = NULL;
7214         float dist, modelradius, modelyawradius, yawradius;
7215         float *v = NULL;
7216         float *vt = NULL;
7217         float *vn = NULL;
7218         float mins[3];
7219         float maxs[3];
7220         float corner[3];
7221         objvertex_t *thisvertex = NULL;
7222         int vertexhashindex;
7223         int *vertexhashtable = NULL;
7224         objvertex_t *vertexhashdata = NULL;
7225         objvertex_t *vdata = NULL;
7226         int vertexhashsize = 0;
7227         int vertexhashcount = 0;
7228         skinfile_t *skinfiles = NULL;
7229         unsigned char *data = NULL;
7230         int *submodelfirstsurface;
7231         msurface_t *surface;
7232         msurface_t *tempsurfaces;
7233
7234         memset(&vfirst, 0, sizeof(vfirst));
7235         memset(&vprev, 0, sizeof(vprev));
7236         memset(&vcurrent, 0, sizeof(vcurrent));
7237
7238         dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7239
7240         loadmodel->modeldatatypestring = "OBJ";
7241
7242         loadmodel->type = mod_obj;
7243         loadmodel->soundfromcenter = true;
7244         loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7245         loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7246         loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7247         loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7248         loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7249         loadmodel->brush.TraceLineOfSight = NULL;
7250         loadmodel->brush.SuperContentsFromNativeContents = NULL;
7251         loadmodel->brush.NativeContentsFromSuperContents = NULL;
7252         loadmodel->brush.GetPVS = NULL;
7253         loadmodel->brush.FatPVS = NULL;
7254         loadmodel->brush.BoxTouchingPVS = NULL;
7255         loadmodel->brush.BoxTouchingLeafPVS = NULL;
7256         loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7257         loadmodel->brush.FindBoxClusters = NULL;
7258         loadmodel->brush.LightPoint = NULL;
7259         loadmodel->brush.FindNonSolidLocation = NULL;
7260         loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7261         loadmodel->brush.RoundUpToHullSize = NULL;
7262         loadmodel->brush.PointInLeaf = NULL;
7263         loadmodel->Draw = R_Q1BSP_Draw;
7264         loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7265         loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7266         loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7267         loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7268         loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7269         loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7270         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7271         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7272         loadmodel->DrawLight = R_Q1BSP_DrawLight;
7273
7274         skinfiles = Mod_LoadSkinFiles();
7275         if (loadmodel->numskins < 1)
7276                 loadmodel->numskins = 1;
7277
7278         // make skinscenes for the skins (no groups)
7279         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7280         for (i = 0;i < loadmodel->numskins;i++)
7281         {
7282                 loadmodel->skinscenes[i].firstframe = i;
7283                 loadmodel->skinscenes[i].framecount = 1;
7284                 loadmodel->skinscenes[i].loop = true;
7285                 loadmodel->skinscenes[i].framerate = 10;
7286         }
7287
7288         VectorClear(mins);
7289         VectorClear(maxs);
7290
7291         // parse the OBJ text now
7292         for(;;)
7293         {
7294                 static char emptyarg[1] = "";
7295                 if (!*text)
7296                         break;
7297                 linenumber++;
7298                 linelen = 0;
7299                 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7300                         line[linelen] = text[linelen];
7301                 line[linelen] = 0;
7302                 for (argc = 0;argc < 4;argc++)
7303                         argv[argc] = emptyarg;
7304                 argc = 0;
7305                 s = line;
7306                 while (*s == ' ' || *s == '\t')
7307                         s++;
7308                 while (*s)
7309                 {
7310                         argv[argc++] = s;
7311                         while (*s > ' ')
7312                                 s++;
7313                         if (!*s)
7314                                 break;
7315                         *s++ = 0;
7316                         while (*s == ' ' || *s == '\t')
7317                                 s++;
7318                 }
7319                 text += linelen;
7320                 if (*text == '\r')
7321                         text++;
7322                 if (*text == '\n')
7323                         text++;
7324                 if (!argc)
7325                         continue;
7326                 if (argv[0][0] == '#')
7327                         continue;
7328                 if (!strcmp(argv[0], "v"))
7329                 {
7330                         if (maxv <= numv)
7331                         {
7332                                 maxv = max(maxv * 2, 1024);
7333                                 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7334                         }
7335                         v[numv*3+0] = atof(argv[1]);
7336                         v[numv*3+2] = atof(argv[2]);
7337                         v[numv*3+1] = atof(argv[3]);
7338                         numv++;
7339                 }
7340                 else if (!strcmp(argv[0], "vt"))
7341                 {
7342                         if (maxvt <= numvt)
7343                         {
7344                                 maxvt = max(maxvt * 2, 1024);
7345                                 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7346                         }
7347                         vt[numvt*2+0] = atof(argv[1]);
7348                         vt[numvt*2+1] = 1-atof(argv[2]);
7349                         numvt++;
7350                 }
7351                 else if (!strcmp(argv[0], "vn"))
7352                 {
7353                         if (maxvn <= numvn)
7354                         {
7355                                 maxvn = max(maxvn * 2, 1024);
7356                                 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7357                         }
7358                         vn[numvn*3+0] = atof(argv[1]);
7359                         vn[numvn*3+2] = atof(argv[2]);
7360                         vn[numvn*3+1] = atof(argv[3]);
7361                         numvn++;
7362                 }
7363                 else if (!strcmp(argv[0], "f"))
7364                 {
7365                         if (!numtextures)
7366                         {
7367                                 if (maxtextures <= numtextures)
7368                                 {
7369                                         maxtextures = max(maxtextures * 2, 256);
7370                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7371                                 }
7372                                 textureindex = numtextures++;
7373                                 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7374                         }
7375                         for (j = 1;j < argc;j++)
7376                         {
7377                                 index1 = atoi(argv[j]);
7378                                 while(argv[j][0] && argv[j][0] != '/')
7379                                         argv[j]++;
7380                                 if (argv[j][0])
7381                                         argv[j]++;
7382                                 index2 = atoi(argv[j]);
7383                                 while(argv[j][0] && argv[j][0] != '/')
7384                                         argv[j]++;
7385                                 if (argv[j][0])
7386                                         argv[j]++;
7387                                 index3 = atoi(argv[j]);
7388                                 // negative refers to a recent vertex
7389                                 // zero means not specified
7390                                 // positive means an absolute vertex index
7391                                 if (index1 < 0)
7392                                         index1 = numv - index1;
7393                                 if (index2 < 0)
7394                                         index2 = numvt - index2;
7395                                 if (index3 < 0)
7396                                         index3 = numvn - index3;
7397                                 vcurrent.nextindex = -1;
7398                                 vcurrent.textureindex = textureindex;
7399                                 vcurrent.submodelindex = submodelindex;
7400                                 if (v && index1 >= 0 && index1 < numv)
7401                                         VectorCopy(v + 3*index1, vcurrent.v);
7402                                 if (vt && index2 >= 0 && index2 < numvt)
7403                                         Vector2Copy(vt + 2*index2, vcurrent.vt);
7404                                 if (vn && index3 >= 0 && index3 < numvn)
7405                                         VectorCopy(vn + 3*index3, vcurrent.vn);
7406                                 if (numtriangles == 0)
7407                                 {
7408                                         VectorCopy(vcurrent.v, mins);
7409                                         VectorCopy(vcurrent.v, maxs);
7410                                 }
7411                                 else
7412                                 {
7413                                         mins[0] = min(mins[0], vcurrent.v[0]);
7414                                         mins[1] = min(mins[1], vcurrent.v[1]);
7415                                         mins[2] = min(mins[2], vcurrent.v[2]);
7416                                         maxs[0] = max(maxs[0], vcurrent.v[0]);
7417                                         maxs[1] = max(maxs[1], vcurrent.v[1]);
7418                                         maxs[2] = max(maxs[2], vcurrent.v[2]);
7419                                 }
7420                                 if (j == 1)
7421                                         vfirst = vcurrent;
7422                                 else if (j >= 3)
7423                                 {
7424                                         if (maxtriangles <= numtriangles)
7425                                         {
7426                                                 maxtriangles = max(maxtriangles * 2, 32768);
7427                                                 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7428                                         }
7429                                         vertices[numtriangles*3+0] = vfirst;
7430                                         vertices[numtriangles*3+1] = vprev;
7431                                         vertices[numtriangles*3+2] = vcurrent;
7432                                         numtriangles++;
7433                                 }
7434                                 vprev = vcurrent;
7435                         }
7436                 }
7437                 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7438                 {
7439                         submodelindex = atof(argv[1]);
7440                         loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7441                 }
7442                 else if (!strcmp(argv[0], "usemtl"))
7443                 {
7444                         for (i = 0;i < numtextures;i++)
7445                                 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7446                                         break;
7447                         if (i < numtextures)
7448                                 textureindex = i;
7449                         else
7450                         {
7451                                 if (maxtextures <= numtextures)
7452                                 {
7453                                         maxtextures = max(maxtextures * 2, 256);
7454                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7455                                 }
7456                                 textureindex = numtextures++;
7457                                 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7458                         }
7459                 }
7460         }
7461
7462         // now that we have the OBJ data loaded as-is, we can convert it
7463
7464         // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7465         VectorCopy(mins, loadmodel->normalmins);
7466         VectorCopy(maxs, loadmodel->normalmaxs);
7467         dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7468         modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7469         modelyawradius = dist*dist+modelyawradius*modelyawradius;
7470         modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7471         modelradius = modelyawradius + modelradius * modelradius;
7472         modelyawradius = sqrt(modelyawradius);
7473         modelradius = sqrt(modelradius);
7474         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7475         loadmodel->yawmins[2] = loadmodel->normalmins[2];
7476         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] =  modelyawradius;
7477         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7478         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7479         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] =  modelradius;
7480         loadmodel->radius = modelradius;
7481         loadmodel->radius2 = modelradius * modelradius;
7482
7483         // allocate storage for triangles
7484         loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7485         // allocate vertex hash structures to build an optimal vertex subset
7486         vertexhashsize = numtriangles*2;
7487         vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7488         memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7489         vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7490         vertexhashcount = 0;
7491
7492         // gather surface stats for assigning vertex/triangle ranges
7493         firstvertex = 0;
7494         firsttriangle = 0;
7495         elementindex = 0;
7496         loadmodel->num_surfaces = 0;
7497         // allocate storage for the worst case number of surfaces, later we resize
7498         tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7499         submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7500         surface = tempsurfaces;
7501         for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7502         {
7503                 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7504                 for (textureindex = 0;textureindex < numtextures;textureindex++)
7505                 {
7506                         for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7507                         {
7508                                 thisvertex = vertices + vertexindex;
7509                                 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7510                                         break;
7511                         }
7512                         // skip the surface creation if there are no triangles for it
7513                         if (vertexindex == numtriangles*3)
7514                                 continue;
7515                         // create a surface for these vertices
7516                         surfacevertices = 0;
7517                         surfaceelements = 0;
7518                         // we hack in a texture index in the surface to be fixed up later...
7519                         surface->texture = (texture_t *)((size_t)textureindex);
7520                         // calculate bounds as we go
7521                         VectorCopy(thisvertex->v, surface->mins);
7522                         VectorCopy(thisvertex->v, surface->maxs);
7523                         for (;vertexindex < numtriangles*3;vertexindex++)
7524                         {
7525                                 thisvertex = vertices + vertexindex;
7526                                 if (thisvertex->submodelindex != submodelindex)
7527                                         continue;
7528                                 if (thisvertex->textureindex != textureindex)
7529                                         continue;
7530                                 // add vertex to surface bounds
7531                                 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7532                                 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7533                                 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7534                                 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7535                                 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7536                                 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7537                                 // add the vertex if it is not found in the merged set, and
7538                                 // get its index (triangle element) for the surface
7539                                 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7540                                 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7541                                 {
7542                                         vdata = vertexhashdata + i;
7543                                         if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7544                                                 break;
7545                                 }
7546                                 if (i < 0)
7547                                 {
7548                                         i = vertexhashcount++;
7549                                         vdata = vertexhashdata + i;
7550                                         *vdata = *thisvertex;
7551                                         vdata->nextindex = vertexhashtable[vertexhashindex];
7552                                         vertexhashtable[vertexhashindex] = i;
7553                                         surfacevertices++;
7554                                 }
7555                                 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7556                                 surfaceelements++;
7557                         }
7558                         surfacetriangles = surfaceelements / 3;
7559                         surface->num_vertices = surfacevertices;
7560                         surface->num_triangles = surfacetriangles;
7561                         surface->num_firstvertex = firstvertex;
7562                         surface->num_firsttriangle = firsttriangle;
7563                         firstvertex += surface->num_vertices;
7564                         firsttriangle += surface->num_triangles;
7565                         surface++;
7566                         loadmodel->num_surfaces++;
7567                 }
7568         }
7569         submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7570         numvertices = firstvertex;
7571         loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7572         tempsurfaces = NULL;
7573
7574         // allocate storage for final mesh data
7575         loadmodel->num_textures = numtextures * loadmodel->numskins;
7576         loadmodel->num_texturesperskin = numtextures;
7577         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 *));
7578         loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7579         loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7580         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7581         loadmodel->surfmesh.num_vertices = numvertices;
7582         loadmodel->surfmesh.num_triangles = numtriangles;
7583         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7584         loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7585         loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7586         loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7587         loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7588         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7589         if (loadmodel->surfmesh.num_vertices <= 65536)
7590                 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7591
7592         for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7593         {
7594                 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7595                 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7596                 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7597         }
7598
7599         // load the textures
7600         for (textureindex = 0;textureindex < numtextures;textureindex++)
7601                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7602         Mod_FreeSkinFiles(skinfiles);
7603
7604         // set the surface textures to their real values now that we loaded them...
7605         for (i = 0;i < loadmodel->num_surfaces;i++)
7606                 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7607
7608         // free data
7609         Mem_Free(vertices);
7610         Mem_Free(texturenames);
7611         Mem_Free(v);
7612         Mem_Free(vt);
7613         Mem_Free(vn);
7614         Mem_Free(vertexhashtable);
7615         Mem_Free(vertexhashdata);
7616
7617         // make a single combined shadow mesh to allow optimized shadow volume creation
7618         Mod_Q1BSP_CreateShadowMesh(loadmodel);
7619
7620         // compute all the mesh information that was not loaded from the file
7621         if (loadmodel->surfmesh.data_element3s)
7622                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7623                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7624         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7625         // generate normals if the file did not have them
7626         if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7627                 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
7628         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
7629         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7630
7631         // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7632         loadmodel->brush.num_visleafs = 1;
7633         loadmodel->brush.num_leafs = 1;
7634         loadmodel->brush.num_nodes = 0;
7635         loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7636         loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7637         loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7638         loadmodel->brush.num_pvsclusters = 1;
7639         loadmodel->brush.num_pvsclusterbytes = 1;
7640         loadmodel->brush.data_pvsclusters = nobsp_pvs;
7641         //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7642         //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7643         loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7644         VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7645         VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7646         loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7647         loadmodel->brush.data_leafs->clusterindex = 0;
7648         loadmodel->brush.data_leafs->areaindex = 0;
7649         loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7650         loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7651         loadmodel->brush.data_leafs->numleafbrushes = 0;
7652         loadmodel->brush.data_leafs->firstleafbrush = NULL;
7653         loadmodel->brush.supportwateralpha = true;
7654
7655         if (loadmodel->brush.numsubmodels)
7656                 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7657
7658         mod = loadmodel;
7659         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7660         {
7661                 if (i > 0)
7662                 {
7663                         char name[10];
7664                         // duplicate the basic information
7665                         dpsnprintf(name, sizeof(name), "*%i", i);
7666                         mod = Mod_FindName(name, loadmodel->name);
7667                         // copy the base model to this one
7668                         *mod = *loadmodel;
7669                         // rename the clone back to its proper name
7670                         strlcpy(mod->name, name, sizeof(mod->name));
7671                         mod->brush.parentmodel = loadmodel;
7672                         // textures and memory belong to the main model
7673                         mod->texturepool = NULL;
7674                         mod->mempool = NULL;
7675                         mod->brush.GetPVS = NULL;
7676                         mod->brush.FatPVS = NULL;
7677                         mod->brush.BoxTouchingPVS = NULL;
7678                         mod->brush.BoxTouchingLeafPVS = NULL;
7679                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7680                         mod->brush.FindBoxClusters = NULL;
7681                         mod->brush.LightPoint = NULL;
7682                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7683                 }
7684                 mod->brush.submodel = i;
7685                 if (loadmodel->brush.submodels)
7686                         loadmodel->brush.submodels[i] = mod;
7687
7688                 // make the model surface list (used by shadowing/lighting)
7689                 mod->firstmodelsurface = submodelfirstsurface[i];
7690                 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7691                 mod->firstmodelbrush = 0;
7692                 mod->nummodelbrushes = 0;
7693                 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7694                 Mod_MakeSortedSurfaces(mod);
7695
7696                 VectorClear(mod->normalmins);
7697                 VectorClear(mod->normalmaxs);
7698                 l = false;
7699                 for (j = 0;j < mod->nummodelsurfaces;j++)
7700                 {
7701                         const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7702                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7703                         int k;
7704                         if (!surface->num_vertices)
7705                                 continue;
7706                         if (!l)
7707                         {
7708                                 l = true;
7709                                 VectorCopy(v, mod->normalmins);
7710                                 VectorCopy(v, mod->normalmaxs);
7711                         }
7712                         for (k = 0;k < surface->num_vertices;k++, v += 3)
7713                         {
7714                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7715                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7716                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7717                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7718                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7719                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7720                         }
7721                 }
7722                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7723                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7724                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7725                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7726                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7727                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7728                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7729                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7730                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7731                 mod->yawmins[2] = mod->normalmins[2];
7732                 mod->yawmaxs[2] = mod->normalmaxs[2];
7733                 mod->radius = modelradius;
7734                 mod->radius2 = modelradius * modelradius;
7735
7736                 // this gets altered below if sky or water is used
7737                 mod->DrawSky = NULL;
7738                 mod->DrawAddWaterPlanes = NULL;
7739
7740                 for (j = 0;j < mod->nummodelsurfaces;j++)
7741                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7742                                 break;
7743                 if (j < mod->nummodelsurfaces)
7744                         mod->DrawSky = R_Q1BSP_DrawSky;
7745
7746                 for (j = 0;j < mod->nummodelsurfaces;j++)
7747                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7748                                 break;
7749                 if (j < mod->nummodelsurfaces)
7750                         mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7751
7752                 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
7753                 mod->render_bih = mod->collision_bih;
7754
7755                 // generate VBOs and other shared data before cloning submodels
7756                 if (i == 0)
7757                         Mod_BuildVBOs();
7758         }
7759         mod = loadmodel;
7760         Mem_Free(submodelfirstsurface);
7761
7762         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);
7763 }
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774 #else // OBJASMODEL
7775
7776 #ifdef OBJWORKS
7777 typedef struct objvertex_s
7778 {
7779         float v[3];
7780         float vt[2];
7781         float vn[3];
7782 }
7783 objvertex_t;
7784
7785 typedef struct objtriangle_s
7786 {
7787         objvertex_t vertex[3];
7788         int textureindex;
7789         // these fields are used only in conversion to surfaces
7790         int axis;
7791         int surfaceindex;
7792         int surfacevertexindex[3];
7793         float edgeplane[3][4];
7794 }
7795 objtriangle_t;
7796
7797 typedef objnode_s
7798 {
7799         struct objnode_s *children[2];
7800         struct objnode_s *parent;
7801         objtriangle_t *triangles;
7802         float normal[3];
7803         float dist;
7804         float mins[3];
7805         float maxs[3];
7806         int numtriangles;
7807 }
7808 objnode_t;
7809
7810 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)
7811 {
7812         int i, j;
7813         float normal[3];
7814         float dist;
7815         int score;
7816         float bestnormal[3];
7817         float bestdist;
7818         int bestscore;
7819         float mins[3];
7820         float maxs[3];
7821         int numfronttriangles;
7822         int numbacktriangles;
7823         int count_front;
7824         int count_back;
7825         int count_both;
7826         int count_on;
7827         float outfrontpoints[5][3];
7828         float outbackpoints[5][3];
7829         int neededfrontpoints;
7830         int neededbackpoints;
7831         int countonpoints;
7832         objnode_t *node;
7833
7834         node = (objnode_t *)Mem_ExpandableArray_AllocRecord(array);
7835         node->parent = parent;
7836         if (numtriangles)
7837         {
7838                 VectorCopy(triangles[0].vertex[0].v, mins);
7839                 VectorCopy(triangles[0].vertex[0].v, maxs);
7840         }
7841         else if (parent && parent->children[0] == node)
7842         {
7843                 VectorCopy(parent->mins, mins);
7844                 Vectorcopy(parent->maxs, maxs);
7845         }
7846         else if (parent && parent->children[1] == node)
7847         {
7848                 VectorCopy(parent->mins, mins);
7849                 Vectorcopy(parent->maxs, maxs);
7850         }
7851         else
7852         {
7853                 VectorClear(mins);
7854                 VectorClear(maxs);
7855         }
7856         for (i = 0;i < numtriangles;i++)
7857         {
7858                 for (j = 0;j < 3;j++)
7859                 {
7860                         mins[0] = min(mins[0], triangles[i].vertex[j].v[0]);
7861                         mins[1] = min(mins[1], triangles[i].vertex[j].v[1]);
7862                         mins[2] = min(mins[2], triangles[i].vertex[j].v[2]);
7863                         maxs[0] = max(maxs[0], triangles[i].vertex[j].v[0]);
7864                         maxs[1] = max(maxs[1], triangles[i].vertex[j].v[1]);
7865                         maxs[2] = max(maxs[2], triangles[i].vertex[j].v[2]);
7866                 }
7867         }
7868         VectorCopy(mins, node->mins);
7869         VectorCopy(maxs, node->maxs);
7870         if (numtriangles <= mod_obj_leaftriangles.integer)
7871         {
7872                 // create a leaf
7873                 loadmodel->brush.num_leafs++;
7874                 node->triangles = triangles;
7875                 node->numtriangles = numtriangles;
7876                 return node;
7877         }
7878
7879         // create a node
7880         loadmodel->brush.num_nodes++;
7881         // pick a splitting plane from the various choices available to us...
7882         // early splits simply halve the interval
7883         bestscore = 0;
7884         VectorClear(bestnormal);
7885         bestdist = 0;
7886         if (numtriangles <= mod_obj_splitterlimit.integer)
7887                 limit = numtriangles;
7888         else
7889                 limit = 0;
7890         for (i = -3;i < limit;i++)
7891         {
7892                 if (i < 0)
7893                 {
7894                         // first we try 3 axial splits (kdtree-like)
7895                         j = i + 3;
7896                         VectorClear(normal);
7897                         normal[j] = 1;
7898                         dist = (mins[j] + maxs[j]) * 0.5f;
7899                 }
7900                 else
7901                 {
7902                         // then we try each triangle plane
7903                         TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7904                         VectorNormalize(normal);
7905                         dist = DotProduct(normal, triangles[i].vertex[0].v);
7906                         // use positive axial values whenever possible
7907                         if (normal[0] == -1)
7908                                 normal[0] = 1;
7909                         if (normal[1] == -1)
7910                                 normal[1] = 1;
7911                         if (normal[2] == -1)
7912                                 normal[2] = 1;
7913                         // skip planes that match the current best
7914                         if (VectorCompare(normal, bestnormal) && dist == bestdist)
7915                                 continue;
7916                 }
7917                 count_on = 0;
7918                 count_front = 0;
7919                 count_back = 0;
7920                 count_both = 0;
7921                 for (j = 0;j < numtriangles;j++)
7922                 {
7923                         dists[0] = DotProduct(normal, triangles[j].vertex[0].v) - dist;
7924                         dists[1] = DotProduct(normal, triangles[j].vertex[1].v) - dist;
7925                         dists[2] = DotProduct(normal, triangles[j].vertex[2].v) - dist;
7926                         if (dists[0] < -DIST_EPSILON || dists[1] < -DIST_EPSILON || dists[2] < -DIST_EPSILON)
7927                         {
7928                                 if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7929                                         count_both++;
7930                                 else
7931                                         count_back++;
7932                         }
7933                         else if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7934                                 count_front++;
7935                         else
7936                                 count_on++;
7937                 }
7938                 // score is supposed to:
7939                 // prefer axial splits
7940                 // prefer evenly dividing the input triangles
7941                 // prefer triangles on the plane
7942                 // avoid triangles crossing the plane
7943                 score = count_on*count_on - count_both*count_both + min(count_front, count_back)*(count_front+count_back);
7944                 if (normal[0] == 1 || normal[1] == 1 || normal[2] == 1)
7945                         score *= 2;
7946                 if (i == -3 || bestscore < score)
7947                 {
7948                         VectorCopy(normal, bestnormal);
7949                         bestdist = dist;
7950                         bestscore = score;
7951                 }
7952         }
7953
7954         // now we have chosen an optimal split plane...
7955
7956         // divide triangles by the splitting plane
7957         numfronttriangles = 0;
7958         numbacktriangles = 0;
7959         for (i = 0;i < numtriangles;i++)
7960         {
7961                 neededfrontpoints = 0;
7962                 neededbackpoints = 0;
7963                 countonpoints = 0;
7964                 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);
7965                 if (countonpoints > 1)
7966                 {
7967                         // triangle lies on plane, assign it to one child only
7968                         TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7969                         if (DotProduct(bestnormal, normal) >= 0)
7970                         {
7971                                 // assign to front side child
7972                                 obj_fronttriangles[numfronttriangles++] = triangles[i];
7973                         }
7974                         else
7975                         {
7976                                 // assign to back side child
7977                                 obj_backtriangles[numbacktriangles++] = triangles[i];
7978                         }
7979                 }
7980                 else
7981                 {
7982                         // convert clipped polygons to triangles
7983                         for (j = 0;j < neededfrontpoints-2;j++)
7984                         {
7985                                 obj_fronttriangles[numfronttriangles] = triangles[i];
7986                                 VectorCopy(outfrontpoints[0], obj_fronttriangles[numfronttriangles].vertex[0].v);
7987                                 VectorCopy(outfrontpoints[j+1], obj_fronttriangles[numfronttriangles].vertex[1].v);
7988                                 VectorCopy(outfrontpoints[j+2], obj_fronttriangles[numfronttriangles].vertex[2].v);
7989                                 numfronttriangles++;
7990                         }
7991                         for (j = 0;j < neededbackpoints-2;j++)
7992                         {
7993                                 obj_backtriangles[numbacktriangles] = triangles[i];
7994                                 VectorCopy(outbackpoints[0], obj_backtriangles[numbacktriangles].vertex[0].v);
7995                                 VectorCopy(outbackpoints[j+1], obj_backtriangles[numbacktriangles].vertex[1].v);
7996                                 VectorCopy(outbackpoints[j+2], obj_backtriangles[numbacktriangles].vertex[2].v);
7997                                 numbacktriangles++;
7998                         }
7999                 }
8000         }
8001
8002         // now copy the triangles out of the big buffer
8003         if (numfronttriangles)
8004         {
8005                 fronttriangles = Mem_Alloc(loadmodel->mempool, fronttriangles * sizeof(*fronttriangles));
8006                 memcpy(fronttriangles, obj_fronttriangles, numfronttriangles * sizeof(*fronttriangles));
8007         }
8008         else
8009                 fronttriangles = NULL;
8010         if (numbacktriangles)
8011         {
8012                 backtriangles = Mem_Alloc(loadmodel->mempool, backtriangles * sizeof(*backtriangles));
8013                 memcpy(backtriangles, obj_backtriangles, numbacktriangles * sizeof(*backtriangles));
8014         }
8015         else
8016                 backtriangles = NULL;
8017
8018         // free the original triangles we were given
8019         if (triangles)
8020                 Mem_Free(triangles);
8021         triangles = NULL;
8022         numtriangles = 0;
8023
8024         // now create the children...
8025         node->children[0] = Mod_OBJ_BSPNodeForTriangles(node, fronttriangles, numfronttriangles, frontmins, frontmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8026         node->children[1] = Mod_OBJ_BSPNodeForTriangles(node, backtriangles, numbacktriangles, backmins, backmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8027         return node;
8028 }
8029
8030 void Mod_OBJ_SnapVertex(float *v)
8031 {
8032         int i;
8033         float a = mod_obj_vertexprecision.value;
8034         float b = 1.0f / a;
8035         v[0] -= floor(v[0] * a + 0.5f) * b;
8036         v[1] -= floor(v[1] * a + 0.5f) * b;
8037         v[2] -= floor(v[2] * a + 0.5f) * b;
8038 }
8039
8040 void Mod_OBJ_ConvertBSPNode(objnode_t *objnode, mnode_t *mnodeparent)
8041 {
8042         if (objnode->children[0])
8043         {
8044                 // convert to mnode_t
8045                 mnode_t *mnode = loadmodel->brush.data_nodes + loadmodel->brush.num_nodes++;
8046                 mnode->parent = mnodeparent;
8047                 mnode->plane = loadmodel->brush.data_planes + loadmodel->brush.num_planes++;
8048                 VectorCopy(objnode->normal, mnode->plane->normal);
8049                 mnode->plane->dist = objnode->dist;
8050                 PlaneClassify(mnode->plane);
8051                 VectorCopy(objnode->mins, mnode->mins);
8052                 VectorCopy(objnode->maxs, mnode->maxs);
8053                 // push combinedsupercontents up to the parent
8054                 if (mnodeparent)
8055                         mnodeparent->combinedsupercontents |= mnode->combinedsupercontents;
8056                 mnode->children[0] = Mod_OBJ_ConvertBSPNode(objnode->children[0], mnode);
8057                 mnode->children[1] = Mod_OBJ_ConvertBSPNode(objnode->children[1], mnode);
8058         }
8059         else
8060         {
8061                 // convert to mleaf_t
8062                 mleaf_t *mleaf = loadmodel->brush.data_leafs + loadmodel->brush.num_leafs++;
8063                 mleaf->parent = mnodeparent;
8064                 VectorCopy(objnode->mins, mleaf->mins);
8065                 VectorCopy(objnode->maxs, mleaf->maxs);
8066                 mleaf->clusterindex = loadmodel->brush.num_leafs - 1;
8067                 if (objnode->numtriangles)
8068                 {
8069                         objtriangle_t *triangles = objnode->triangles;
8070                         int numtriangles = objnode->numtriangles;
8071                         texture_t *texture;
8072                         float edge[3][3];
8073                         float normal[3];
8074                         objvertex_t vertex[3];
8075                         numsurfaces = 0;
8076                         maxsurfaces = numtriangles;
8077                         surfaces = NULL;
8078                         // calculate some more data on each triangle for surface gathering
8079                         for (i = 0;i < numtriangles;i++)
8080                         {
8081                                 triangle = triangles + i;
8082                                 texture = loadmodel->data_textures + triangle->textureindex;
8083                                 Mod_OBJ_SnapVertex(triangle->vertex[0].v);
8084                                 Mod_OBJ_SnapVertex(triangle->vertex[1].v);
8085                                 Mod_OBJ_SnapVertex(triangle->vertex[2].v);
8086                                 TriangleNormal(triangle->vertex[0].v, triangle->vertex[1].v, triangle->vertex[2].v, normal);
8087                                 axis = 0;
8088                                 if (fabs(normal[axis]) < fabs(normal[1]))
8089                                         axis = 1;
8090                                 if (fabs(normal[axis]) < fabs(normal[2]))
8091                                         axis = 2;
8092                                 VectorClear(normal);
8093                                 normal[axis] = 1;
8094                                 triangle->axis = axis;
8095                                 VectorSubtract(triangle->vertex[1].v, triangle->vertex[0].v, edge[0]);
8096                                 VectorSubtract(triangle->vertex[2].v, triangle->vertex[1].v, edge[1]);
8097                                 VectorSubtract(triangle->vertex[0].v, triangle->vertex[2].v, edge[2]);
8098                                 CrossProduct(edge[0], normal, triangle->edgeplane[0]);
8099                                 CrossProduct(edge[1], normal, triangle->edgeplane[1]);
8100                                 CrossProduct(edge[2], normal, triangle->edgeplane[2]);
8101                                 VectorNormalize(triangle->edgeplane[0]);
8102                                 VectorNormalize(triangle->edgeplane[1]);
8103                                 VectorNormalize(triangle->edgeplane[2]);
8104                                 triangle->edgeplane[0][3] = DotProduct(triangle->edgeplane[0], triangle->vertex[0].v);
8105                                 triangle->edgeplane[1][3] = DotProduct(triangle->edgeplane[1], triangle->vertex[1].v);
8106                                 triangle->edgeplane[2][3] = DotProduct(triangle->edgeplane[2], triangle->vertex[2].v);
8107                                 triangle->surfaceindex = 0;
8108                                 // add to the combined supercontents while we're here...
8109                                 mleaf->combinedsupercontents |= texture->supercontents;
8110                         }
8111                         surfaceindex = 1;
8112                         for (i = 0;i < numtriangles;i++)
8113                         {
8114                                 // skip already-assigned triangles
8115                                 if (triangles[i].surfaceindex)
8116                                         continue;
8117                                 texture = loadmodel->data_textures + triangles[i].textureindex;
8118                                 // assign a new surface to this triangle
8119                                 triangles[i].surfaceindex = surfaceindex++;
8120                                 axis = triangles[i].axis;
8121                                 numvertices = 3;
8122                                 // find the triangle's neighbors, this can take multiple passes
8123                                 retry = true;
8124                                 while (retry)
8125                                 {
8126                                         retry = false;
8127                                         for (j = i+1;j < numtriangles;j++)
8128                                         {
8129                                                 if (triangles[j].surfaceindex || triangles[j].axis != axis || triangles[j].texture != texture)
8130                                                         continue;
8131                                                 triangle = triangles + j;
8132                                                 for (k = i;k < j;k++)
8133                                                 {
8134                                                         if (triangles[k].surfaceindex != surfaceindex)
8135                                                                 continue;
8136                                                         if (VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[0].v)
8137                                                          || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[1].v)
8138                                                          || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[2].v)
8139                                                          || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[0].v)
8140                                                          || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[1].v)
8141                                                          || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[2].v)
8142                                                          || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[0].v)
8143                                                          || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[1].v)
8144                                                          || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[2].v))
8145                                                         {
8146                                                                 // shares a vertex position
8147                                                                 --- FIXME ---
8148                                                         }
8149                                                 }
8150                                                 for (k = 0;k < numvertices;k++)
8151                                                         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))
8152                                                                 break;
8153                                                 if (k == numvertices)
8154                                                         break; // not a neighbor
8155                                                 // this triangle is a neighbor and has the same axis and texture
8156                                                 // check now if it overlaps in lightmap projection space
8157                                                 triangles[j].surfaceindex;
8158                                                 if (triangles[j].
8159                                         }
8160                                 }
8161                                 //triangles[i].surfaceindex = surfaceindex++;
8162                                 for (surfaceindex = 0;surfaceindex < numsurfaces;surfaceindex++)
8163                                 {
8164                                         if (surfaces[surfaceindex].texture != texture)
8165                                                 continue;
8166                                         // check if any triangles already in this surface overlap in lightmap projection space
8167                                         
8168                                         {
8169                                         }
8170                                         break;
8171                                 }
8172                         }
8173                         // let the collision code simply use the surfaces
8174                         mleaf->containscollisionsurfaces = mleaf->combinedsupercontents != 0;
8175                         mleaf->numleafsurfaces = ?;
8176                         mleaf->firstleafsurface = ?;
8177                 }
8178                 // push combinedsupercontents up to the parent
8179                 if (mnodeparent)
8180                         mnodeparent->combinedsupercontents |= mleaf->combinedsupercontents;
8181         }
8182 }
8183 #endif
8184
8185 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8186 {
8187 #ifdef OBJWORKS
8188         const char *textbase = (char *)buffer, *text = textbase;
8189         char *s;
8190         char *argv[512];
8191         char line[1024];
8192         char materialname[MAX_QPATH];
8193         int j, index1, index2, index3, first, prev, index;
8194         int argc;
8195         int linelen;
8196         int numtriangles = 0;
8197         int maxtriangles = 131072;
8198         objtriangle_t *triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8199         int linenumber = 0;
8200         int maxtextures = 256, numtextures = 0, textureindex = 0;
8201         int maxv = 1024, numv = 0;
8202         int maxvt = 1024, numvt = 0;
8203         int maxvn = 1024, numvn = 0;
8204         char **texturenames;
8205         float *v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8206         float *vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8207         float *vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8208         objvertex_t vfirst, vprev, vcurrent;
8209         float mins[3];
8210         float maxs[3];
8211 #if 0
8212         int hashindex;
8213         int maxverthash = 65536, numverthash = 0;
8214         int numhashindex = 65536;
8215         struct objverthash_s
8216         {
8217                 struct objverthash_s *next;
8218                 int s;
8219                 int v;
8220                 int vt;
8221                 int vn;
8222         }
8223         *hash, **verthash = Mem_Alloc(tempmempool, numhashindex * sizeof(*verthash)), *verthashdata = Mem_Alloc(tempmempool, maxverthash * sizeof(*verthashdata)), *oldverthashdata;
8224 #endif
8225
8226         dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8227
8228         loadmodel->modeldatatypestring = "OBJ";
8229
8230         loadmodel->type = mod_obj;
8231         loadmodel->soundfromcenter = true;
8232         loadmodel->TraceBox = Mod_OBJ_TraceBox;
8233         loadmodel->TraceLine = Mod_OBJ_TraceLine;
8234         loadmodel->TracePoint = Mod_OBJ_TracePoint;
8235         loadmodel->PointSuperContents = Mod_OBJ_PointSuperContents;
8236         loadmodel->brush.TraceLineOfSight = Mod_OBJ_TraceLineOfSight;
8237         loadmodel->brush.SuperContentsFromNativeContents = Mod_OBJ_SuperContentsFromNativeContents;
8238         loadmodel->brush.NativeContentsFromSuperContents = Mod_OBJ_NativeContentsFromSuperContents;
8239         loadmodel->brush.GetPVS = Mod_OBJ_GetPVS;
8240         loadmodel->brush.FatPVS = Mod_OBJ_FatPVS;
8241         loadmodel->brush.BoxTouchingPVS = Mod_OBJ_BoxTouchingPVS;
8242         loadmodel->brush.BoxTouchingLeafPVS = Mod_OBJ_BoxTouchingLeafPVS;
8243         loadmodel->brush.BoxTouchingVisibleLeafs = Mod_OBJ_BoxTouchingVisibleLeafs;
8244         loadmodel->brush.FindBoxClusters = Mod_OBJ_FindBoxClusters;
8245         loadmodel->brush.LightPoint = Mod_OBJ_LightPoint;
8246         loadmodel->brush.FindNonSolidLocation = Mod_OBJ_FindNonSolidLocation;
8247         loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8248         loadmodel->brush.RoundUpToHullSize = NULL;
8249         loadmodel->brush.PointInLeaf = Mod_OBJ_PointInLeaf;
8250         loadmodel->Draw = R_Q1BSP_Draw;
8251         loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8252         loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8253         loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8254         loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8255         loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8256         loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8257         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
8258         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
8259         loadmodel->DrawLight = R_Q1BSP_DrawLight;
8260
8261         VectorClear(mins);
8262         VectorClear(maxs);
8263
8264         // parse the OBJ text now
8265         for(;;)
8266         {
8267                 if (!*text)
8268                         break;
8269                 linenumber++;
8270                 linelen = 0;
8271                 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8272                         line[linelen] = text[linelen];
8273                 line[linelen] = 0;
8274                 for (argc = 0;argc < (int)(sizeof(argv)/sizeof(argv[0]));argc++)
8275                         argv[argc] = "";
8276                 argc = 0;
8277                 s = line;
8278                 while (*s == ' ' || *s == '\t')
8279                         s++;
8280                 while (*s)
8281                 {
8282                         argv[argc++] = s;
8283                         while (*s > ' ')
8284                                 s++;
8285                         if (!*s)
8286                                 break;
8287                         *s++ = 0;
8288                         while (*s == ' ' || *s == '\t')
8289                                 s++;
8290                 }
8291                 if (!argc)
8292                         continue;
8293                 if (argv[0][0] == '#')
8294                         continue;
8295                 if (!strcmp(argv[0], "v"))
8296                 {
8297                         if (maxv <= numv)
8298                         {
8299                                 float *oldv = v;
8300                                 maxv *= 2;
8301                                 v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8302                                 if (oldv)
8303                                 {
8304                                         memcpy(v, oldv, numv * sizeof(float[3]));
8305                                         Mem_Free(oldv);
8306                                 }
8307                         }
8308                         v[numv*3+0] = atof(argv[1]);
8309                         v[numv*3+1] = atof(argv[2]);
8310                         v[numv*3+2] = atof(argv[3]);
8311                         numv++;
8312                 }
8313                 else if (!strcmp(argv[0], "vt"))
8314                 {
8315                         if (maxvt <= numvt)
8316                         {
8317                                 float *oldvt = vt;
8318                                 maxvt *= 2;
8319                                 vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8320                                 if (oldvt)
8321                                 {
8322                                         memcpy(vt, oldvt, numvt * sizeof(float[2]));
8323                                         Mem_Free(oldvt);
8324                                 }
8325                         }
8326                         vt[numvt*2+0] = atof(argv[1]);
8327                         vt[numvt*2+1] = atof(argv[2]);
8328                         numvt++;
8329                 }
8330                 else if (!strcmp(argv[0], "vn"))
8331                 {
8332                         if (maxvn <= numvn)
8333                         {
8334                                 float *oldvn = vn;
8335                                 maxvn *= 2;
8336                                 vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8337                                 if (oldvn)
8338                                 {
8339                                         memcpy(vn, oldvn, numvn * sizeof(float[3]));
8340                                         Mem_Free(oldvn);
8341                                 }
8342                         }
8343                         vn[numvn*3+0] = atof(argv[1]);
8344                         vn[numvn*3+1] = atof(argv[2]);
8345                         vn[numvn*3+2] = atof(argv[3]);
8346                         numvn++;
8347                 }
8348                 else if (!strcmp(argv[0], "f"))
8349                 {
8350                         for (j = 1;j < argc;j++)
8351                         {
8352                                 index1 = atoi(argv[j]);
8353                                 while(argv[j][0] && argv[j][0] != '/')
8354                                         argv[j]++;
8355                                 if (argv[j][0])
8356                                         argv[j]++;
8357                                 index2 = atoi(argv[j]);
8358                                 while(argv[j][0] && argv[j][0] != '/')
8359                                         argv[j]++;
8360                                 if (argv[j][0])
8361                                         argv[j]++;
8362                                 index3 = atoi(argv[j]);
8363                                 // negative refers to a recent vertex
8364                                 // zero means not specified
8365                                 // positive means an absolute vertex index
8366                                 if (index1 < 0)
8367                                         index1 = numv - index1;
8368                                 if (index2 < 0)
8369                                         index2 = numvt - index2;
8370                                 if (index3 < 0)
8371                                         index3 = numvn - index3;
8372                                 VectorCopy(v + 3*index1, vcurrent.v);
8373                                 Vector2Copy(vt + 2*index2, vcurrent.vt);
8374                                 VectorCopy(vn + 3*index3, vcurrent.vn);
8375                                 if (numtriangles == 0)
8376                                 {
8377                                         VectorCopy(vcurrent.v, mins);
8378                                         VectorCopy(vcurrent.v, maxs);
8379                                 }
8380                                 else
8381                                 {
8382                                         mins[0] = min(mins[0], vcurrent.v[0]);
8383                                         mins[1] = min(mins[1], vcurrent.v[1]);
8384                                         mins[2] = min(mins[2], vcurrent.v[2]);
8385                                         maxs[0] = max(maxs[0], vcurrent.v[0]);
8386                                         maxs[1] = max(maxs[1], vcurrent.v[1]);
8387                                         maxs[2] = max(maxs[2], vcurrent.v[2]);
8388                                 }
8389                                 if (j == 1)
8390                                         vfirst = vcurrent;
8391                                 else if (j >= 3)
8392                                 {
8393                                         if (maxtriangles <= numtriangles)
8394                                         {
8395                                                 objtriangle_t *oldtriangles = triangles;
8396                                                 maxtriangles *= 2;
8397                                                 triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8398                                                 if (oldtriangles)
8399                                                 {
8400                                                         memcpy(triangles, oldtriangles, maxtriangles * sizeof(*triangles));
8401                                                         Mem_Free(oldtriangles);
8402                                                 }
8403                                         }
8404                                         triangles[numtriangles].textureindex = textureindex;
8405                                         triangles[numtriangles].vertex[0] = vfirst;
8406                                         triangles[numtriangles].vertex[1] = vprev;
8407                                         triangles[numtriangles].vertex[2] = vcurrent;
8408                                         numtriangles++;
8409                                 }
8410                                 vprev = vcurrent;
8411                                 prev = index;
8412                         }
8413                 }
8414                 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8415                         ;
8416                 else if (!!strcmp(argv[0], "usemtl"))
8417                 {
8418                         for (i = 0;i < numtextures;i++)
8419                                 if (!strcmp(texturenames[numtextures], argv[1]))
8420                                         break;
8421                         if (i < numtextures)
8422                                 texture = textures + i;
8423                         else
8424                         {
8425                                 if (maxtextures <= numtextures)
8426                                 {
8427                                         texture_t *oldtextures = textures;
8428                                         maxtextures *= 2;
8429                                         textures = Mem_Alloc(tempmempool, maxtextures * sizeof(*textures));
8430                                         if (oldtextures)
8431                                         {
8432                                                 memcpy(textures, oldtextures, numtextures * sizeof(*textures));
8433                                                 Mem_Free(oldtextures);
8434                                         }
8435                                 }
8436                                 textureindex = numtextures++;
8437                                 texturenames[textureindex] = Mem_Alloc(tempmempool, strlen(argv[1]) + 1);
8438                                 memcpy(texturenames[textureindex], argv[1], strlen(argv[1]) + 1);
8439                         }
8440                 }
8441                 text += linelen;
8442                 if (*text == '\r')
8443                         text++;
8444                 if (*text == '\n')
8445                         text++;
8446         }
8447
8448         // now that we have the OBJ data loaded as-is, we can convert it
8449
8450         // load the textures
8451         loadmodel->num_textures = numtextures;
8452         loadmodel->data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
8453         for (i = 0;i < numtextures;i++)
8454                 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, texturenames[i], true, true, TEXF_MIPMAP | TEXF_ALPHA | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
8455
8456         // free the texturenames array since we are now done with it
8457         for (i = 0;i < numtextures;i++)
8458         {
8459                 Mem_Free(texturenames[i]);
8460                 texturenames[i] = NULL;
8461         }
8462         Mem_Free(texturenames);
8463         texturenames = NULL;
8464
8465         // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8466         VectorCopy(mins, loadmodel->normalmins);
8467         VectorCopy(maxs, loadmodel->normalmaxs);
8468         dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8469         modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8470         modelyawradius = dist*dist+modelyawradius*modelyawradius;
8471         modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8472         modelradius = modelyawradius + modelradius * modelradius;
8473         modelyawradius = sqrt(modelyawradius);
8474         modelradius = sqrt(modelradius);
8475         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8476         loadmodel->yawmins[2] = loadmodel->normalmins[2];
8477         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] =  modelyawradius;
8478         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8479         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8480         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] =  modelradius;
8481         loadmodel->radius = modelradius;
8482         loadmodel->radius2 = modelradius * modelradius;
8483
8484         // make sure the temp triangle buffer is big enough for BSP building
8485         maxclippedtriangles = numtriangles*4;
8486         if (numtriangles > 0)
8487         {
8488                 clippedfronttriangles = Mem_Alloc(loadmodel->mempool, maxclippedtriangles * 2 * sizeof(objtriangle_t));
8489                 clippedbacktriangles = clippedfronttriangles + maxclippedtriangles;
8490         }
8491
8492         // 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
8493         loadmodel->brush.num_leafs = 0;
8494         loadmodel->brush.num_nodes = 0;
8495         Mem_ExpandableArray_NewArray(&nodesarray, loadmodel->mempool, sizeof(objnode_t), 1024);
8496         rootnode = Mod_OBJ_BSPNodeForTriangles(triangles, numtriangles, mins, maxs, &nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8497
8498         // convert the BSP tree to mnode_t and mleaf_t structures and convert the triangles to msurface_t...
8499         loadmodel->brush.data_leafs = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8500         loadmodel->brush.data_nodes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mnode_t));
8501         loadmodel->brush.data_planes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mplane_t));
8502         loadmodel->brush.num_leafs = 0;
8503         loadmodel->brush.num_nodes = 0;
8504         loadmodel->brush.num_planes = 0;
8505         Mod_OBJ_ConvertAndFreeBSPNode(rootnode);
8506
8507         if (clippedfronttriangles)
8508                 Mem_Free(clippedfronttriangles);
8509         maxclippedtriangles = 0;
8510         clippedfronttriangles = NULL;
8511         clippedbacktriangles = NULL;
8512
8513 --- NOTHING DONE PAST THIS POINT ---
8514
8515         loadmodel->numskins = LittleLong(pinmodel->num_skins);
8516         numxyz = LittleLong(pinmodel->num_xyz);
8517         numst = LittleLong(pinmodel->num_st);
8518         loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
8519         loadmodel->numframes = LittleLong(pinmodel->num_frames);
8520         loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
8521         loadmodel->num_poses = loadmodel->surfmesh.num_morphframes;
8522         skinwidth = LittleLong(pinmodel->skinwidth);
8523         skinheight = LittleLong(pinmodel->skinheight);
8524         iskinwidth = 1.0f / skinwidth;
8525         iskinheight = 1.0f / skinheight;
8526
8527         loadmodel->num_surfaces = 1;
8528         loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
8529         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]));
8530         loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
8531         loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8532         loadmodel->sortedmodelsurfaces[0] = 0;
8533         loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
8534         loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
8535         loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8536         loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8537
8538         loadmodel->synctype = ST_RAND;
8539
8540         // load the skins
8541         inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
8542         skinfiles = Mod_LoadSkinFiles();
8543         if (skinfiles)
8544         {
8545                 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8546                 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8547                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8548                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
8549                 Mod_FreeSkinFiles(skinfiles);
8550         }
8551         else if (loadmodel->numskins)
8552         {
8553                 // skins found (most likely not a player model)
8554                 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8555                 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8556                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8557                 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
8558                         Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i * loadmodel->num_surfaces, inskin, true, true, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP | TEXF_COMPRESS);
8559         }
8560         else
8561         {
8562                 // no skins (most likely a player model)
8563                 loadmodel->numskins = 1;
8564                 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8565                 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8566                 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8567                 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
8568         }
8569
8570         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8571         for (i = 0;i < loadmodel->numskins;i++)
8572         {
8573                 loadmodel->skinscenes[i].firstframe = i;
8574                 loadmodel->skinscenes[i].framecount = 1;
8575                 loadmodel->skinscenes[i].loop = true;
8576                 loadmodel->skinscenes[i].framerate = 10;
8577         }
8578
8579         // load the triangles and stvert data
8580         inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
8581         intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
8582         md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
8583         md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
8584         // swap the triangle list
8585         loadmodel->surfmesh.num_vertices = 0;
8586         for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
8587         {
8588                 for (j = 0;j < 3;j++)
8589                 {
8590                         xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
8591                         st = (unsigned short) LittleShort (intri[i].index_st[j]);
8592                         if (xyz >= numxyz)
8593                         {
8594                                 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
8595                                 xyz = 0;
8596                         }
8597                         if (st >= numst)
8598                         {
8599                                 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
8600                                 st = 0;
8601                         }
8602                         hashindex = (xyz * 256 + st) & 65535;
8603                         for (hash = md2verthash[hashindex];hash;hash = hash->next)
8604                                 if (hash->xyz == xyz && hash->st == st)
8605                                         break;
8606                         if (hash == NULL)
8607                         {
8608                                 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
8609                                 hash->xyz = xyz;
8610                                 hash->st = st;
8611                                 hash->next = md2verthash[hashindex];
8612                                 md2verthash[hashindex] = hash;
8613                         }
8614                         loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
8615                 }
8616         }
8617
8618         vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
8619         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));
8620         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
8621         loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
8622         for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
8623         {
8624                 int sts, stt;
8625                 hash = md2verthashdata + i;
8626                 vertremap[i] = hash->xyz;
8627                 sts = LittleShort(inst[hash->st*2+0]);
8628                 stt = LittleShort(inst[hash->st*2+1]);
8629                 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
8630                 {
8631                         Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
8632                         sts = 0;
8633                         stt = 0;
8634                 }
8635                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
8636                 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
8637         }
8638
8639         Mem_Free(md2verthash);
8640         Mem_Free(md2verthashdata);
8641
8642         // generate ushort elements array if possible
8643         if (loadmodel->surfmesh.num_vertices <= 65536)
8644                 loadmodel->surfmesh.data_element3s = (unsigned short *)Mem_Alloc(loadmodel->mempool, sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles);
8645
8646         // load the frames
8647         datapointer = (base + LittleLong(pinmodel->ofs_frames));
8648         for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
8649         {
8650                 int k;
8651                 trivertx_t *v;
8652                 trivertx_t *out;
8653                 pinframe = (md2frame_t *)datapointer;
8654                 datapointer += sizeof(md2frame_t);
8655                 // store the frame scale/translate into the appropriate array
8656                 for (j = 0;j < 3;j++)
8657                 {
8658                         loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
8659                         loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
8660                 }
8661                 // convert the vertices
8662                 v = (trivertx_t *)datapointer;
8663                 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
8664                 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
8665                         out[k] = v[vertremap[k]];
8666                 datapointer += numxyz * sizeof(trivertx_t);
8667
8668                 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
8669                 loadmodel->animscenes[i].firstframe = i;
8670                 loadmodel->animscenes[i].framecount = 1;
8671                 loadmodel->animscenes[i].framerate = 10;
8672                 loadmodel->animscenes[i].loop = true;
8673         }
8674
8675         Mem_Free(vertremap);
8676
8677         Mod_MakeSortedSurfaces(loadmodel);
8678         Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8679         Mod_Alias_CalculateBoundingBox();
8680         Mod_Alias_MorphMesh_CompileFrames();
8681
8682         surface = loadmodel->data_surfaces;
8683         surface->texture = loadmodel->data_textures;
8684         surface->num_firsttriangle = 0;
8685         surface->num_triangles = loadmodel->surfmesh.num_triangles;
8686         surface->num_firstvertex = 0;
8687         surface->num_vertices = loadmodel->surfmesh.num_vertices;
8688
8689         loadmodel->surfmesh.isanimated = false;
8690
8691         if (loadmodel->surfmesh.data_element3s)
8692                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8693                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8694 #endif
8695 }
8696 #endif // !OBJASMODEL
8697
8698 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
8699 {
8700         // we already have done PVS culling at this point...
8701         // so we don't need to do it again.
8702
8703         int i;
8704         vec3_t testorigin, mins, maxs;
8705
8706         testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
8707         testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
8708         testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
8709
8710         if(model->brush.TraceLineOfSight(model, eye, testorigin))
8711                 return 1;
8712
8713         // expand the box a little
8714         mins[0] = (t+1) * minsX[0] - t * maxsX[0];
8715         maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
8716         mins[1] = (t+1) * minsX[1] - t * maxsX[1];
8717         maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
8718         mins[2] = (t+1) * minsX[2] - t * maxsX[2];
8719         maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
8720
8721         for(i = 0; i != numsamples; ++i)
8722         {
8723                 testorigin[0] = lhrandom(mins[0], maxs[0]);
8724                 testorigin[1] = lhrandom(mins[1], maxs[1]);
8725                 testorigin[2] = lhrandom(mins[2], maxs[2]);
8726
8727                 if(model->brush.TraceLineOfSight(model, eye, testorigin))
8728                         return 1;
8729         }
8730
8731         return 0;
8732 }
8733