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