new cvars:
[divverent/darkplaces.git] / model_brush.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "curves.h"
26 #include "wad.h"
27
28
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
31 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
32 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
33 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
34 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
35 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
36 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
37 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
38 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
39 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
40 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
41 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
42 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
43 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
44 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
45 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
46 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
47 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
48 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces"};
49
50 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)"};
51 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"};
52 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"};
53
54 static texture_t mod_q1bsp_texture_solid;
55 static texture_t mod_q1bsp_texture_sky;
56 static texture_t mod_q1bsp_texture_lava;
57 static texture_t mod_q1bsp_texture_slime;
58 static texture_t mod_q1bsp_texture_water;
59
60 void Mod_BrushInit(void)
61 {
62 //      Cvar_RegisterVariable(&r_subdivide_size);
63         Cvar_RegisterVariable(&r_novis);
64         Cvar_RegisterVariable(&r_nosurftextures);
65         Cvar_RegisterVariable(&r_subdivisions_tolerance);
66         Cvar_RegisterVariable(&r_subdivisions_mintess);
67         Cvar_RegisterVariable(&r_subdivisions_maxtess);
68         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
69         Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
70         Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
71         Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
72         Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
73         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
74         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
75         Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
76         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
77         Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
78         Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
79         Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
80         Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
81         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
82         Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
83         Cvar_RegisterVariable(&mod_collision_bih);
84         Cvar_RegisterVariable(&mod_recalculatenodeboxes);
85
86         memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
87         strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
88         mod_q1bsp_texture_solid.surfaceflags = 0;
89         mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
90
91         mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
92         strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
93         mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
94         mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
95
96         mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
97         strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
98         mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
99         mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
100
101         mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
102         strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
103         mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
104         mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
105
106         mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
107         strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
108         mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
109         mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
110 }
111
112 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
113 {
114         mnode_t *node;
115
116         if (model == NULL)
117                 return NULL;
118
119         // LordHavoc: modified to start at first clip node,
120         // in other words: first node of the (sub)model
121         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
122         while (node->plane)
123                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
124
125         return (mleaf_t *)node;
126 }
127
128 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
129 {
130         int i;
131         mleaf_t *leaf;
132         leaf = Mod_Q1BSP_PointInLeaf(model, p);
133         if (leaf)
134         {
135                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
136                 if (i)
137                 {
138                         memcpy(out, leaf->ambient_sound_level, i);
139                         out += i;
140                         outsize -= i;
141                 }
142         }
143         if (outsize)
144                 memset(out, 0, outsize);
145 }
146
147 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
148 {
149         int numclusters = 0;
150         int nodestackindex = 0;
151         mnode_t *node, *nodestack[1024];
152         if (!model->brush.num_pvsclusters)
153                 return -1;
154         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
155         for (;;)
156         {
157 #if 1
158                 if (node->plane)
159                 {
160                         // node - recurse down the BSP tree
161                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
162                         if (sides < 3)
163                         {
164                                 if (sides == 0)
165                                         return -1; // ERROR: NAN bounding box!
166                                 // box is on one side of plane, take that path
167                                 node = node->children[sides-1];
168                         }
169                         else
170                         {
171                                 // box crosses plane, take one path and remember the other
172                                 if (nodestackindex < 1024)
173                                         nodestack[nodestackindex++] = node->children[0];
174                                 node = node->children[1];
175                         }
176                         continue;
177                 }
178                 else
179                 {
180                         // leaf - add clusterindex to list
181                         if (numclusters < maxclusters)
182                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
183                         numclusters++;
184                 }
185 #else
186                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
187                 {
188                         if (node->plane)
189                         {
190                                 if (nodestackindex < 1024)
191                                         nodestack[nodestackindex++] = node->children[0];
192                                 node = node->children[1];
193                                 continue;
194                         }
195                         else
196                         {
197                                 // leaf - add clusterindex to list
198                                 if (numclusters < maxclusters)
199                                         clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
200                                 numclusters++;
201                         }
202                 }
203 #endif
204                 // try another path we didn't take earlier
205                 if (nodestackindex == 0)
206                         break;
207                 node = nodestack[--nodestackindex];
208         }
209         // return number of clusters found (even if more than the maxclusters)
210         return numclusters;
211 }
212
213 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
214 {
215         int nodestackindex = 0;
216         mnode_t *node, *nodestack[1024];
217         if (!model->brush.num_pvsclusters)
218                 return true;
219         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
220         for (;;)
221         {
222 #if 1
223                 if (node->plane)
224                 {
225                         // node - recurse down the BSP tree
226                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
227                         if (sides < 3)
228                         {
229                                 if (sides == 0)
230                                         return -1; // ERROR: NAN bounding box!
231                                 // box is on one side of plane, take that path
232                                 node = node->children[sides-1];
233                         }
234                         else
235                         {
236                                 // box crosses plane, take one path and remember the other
237                                 if (nodestackindex < 1024)
238                                         nodestack[nodestackindex++] = node->children[0];
239                                 node = node->children[1];
240                         }
241                         continue;
242                 }
243                 else
244                 {
245                         // leaf - check cluster bit
246                         int clusterindex = ((mleaf_t *)node)->clusterindex;
247                         if (CHECKPVSBIT(pvs, clusterindex))
248                         {
249                                 // it is visible, return immediately with the news
250                                 return true;
251                         }
252                 }
253 #else
254                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
255                 {
256                         if (node->plane)
257                         {
258                                 if (nodestackindex < 1024)
259                                         nodestack[nodestackindex++] = node->children[0];
260                                 node = node->children[1];
261                                 continue;
262                         }
263                         else
264                         {
265                                 // leaf - check cluster bit
266                                 int clusterindex = ((mleaf_t *)node)->clusterindex;
267                                 if (CHECKPVSBIT(pvs, clusterindex))
268                                 {
269                                         // it is visible, return immediately with the news
270                                         return true;
271                                 }
272                         }
273                 }
274 #endif
275                 // nothing to see here, try another path we didn't take earlier
276                 if (nodestackindex == 0)
277                         break;
278                 node = nodestack[--nodestackindex];
279         }
280         // it is not visible
281         return false;
282 }
283
284 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
285 {
286         int nodestackindex = 0;
287         mnode_t *node, *nodestack[1024];
288         if (!model->brush.num_leafs)
289                 return true;
290         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
291         for (;;)
292         {
293 #if 1
294                 if (node->plane)
295                 {
296                         // node - recurse down the BSP tree
297                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
298                         if (sides < 3)
299                         {
300                                 if (sides == 0)
301                                         return -1; // ERROR: NAN bounding box!
302                                 // box is on one side of plane, take that path
303                                 node = node->children[sides-1];
304                         }
305                         else
306                         {
307                                 // box crosses plane, take one path and remember the other
308                                 if (nodestackindex < 1024)
309                                         nodestack[nodestackindex++] = node->children[0];
310                                 node = node->children[1];
311                         }
312                         continue;
313                 }
314                 else
315                 {
316                         // leaf - check cluster bit
317                         int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
318                         if (CHECKPVSBIT(pvs, clusterindex))
319                         {
320                                 // it is visible, return immediately with the news
321                                 return true;
322                         }
323                 }
324 #else
325                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
326                 {
327                         if (node->plane)
328                         {
329                                 if (nodestackindex < 1024)
330                                         nodestack[nodestackindex++] = node->children[0];
331                                 node = node->children[1];
332                                 continue;
333                         }
334                         else
335                         {
336                                 // leaf - check cluster bit
337                                 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
338                                 if (CHECKPVSBIT(pvs, clusterindex))
339                                 {
340                                         // it is visible, return immediately with the news
341                                         return true;
342                                 }
343                         }
344                 }
345 #endif
346                 // nothing to see here, try another path we didn't take earlier
347                 if (nodestackindex == 0)
348                         break;
349                 node = nodestack[--nodestackindex];
350         }
351         // it is not visible
352         return false;
353 }
354
355 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
356 {
357         int nodestackindex = 0;
358         mnode_t *node, *nodestack[1024];
359         if (!model->brush.num_leafs)
360                 return true;
361         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
362         for (;;)
363         {
364 #if 1
365                 if (node->plane)
366                 {
367                         // node - recurse down the BSP tree
368                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
369                         if (sides < 3)
370                         {
371                                 if (sides == 0)
372                                         return -1; // ERROR: NAN bounding box!
373                                 // box is on one side of plane, take that path
374                                 node = node->children[sides-1];
375                         }
376                         else
377                         {
378                                 // box crosses plane, take one path and remember the other
379                                 if (nodestackindex < 1024)
380                                         nodestack[nodestackindex++] = node->children[0];
381                                 node = node->children[1];
382                         }
383                         continue;
384                 }
385                 else
386                 {
387                         // leaf - check if it is visible
388                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
389                         {
390                                 // it is visible, return immediately with the news
391                                 return true;
392                         }
393                 }
394 #else
395                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
396                 {
397                         if (node->plane)
398                         {
399                                 if (nodestackindex < 1024)
400                                         nodestack[nodestackindex++] = node->children[0];
401                                 node = node->children[1];
402                                 continue;
403                         }
404                         else
405                         {
406                                 // leaf - check if it is visible
407                                 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
408                                 {
409                                         // it is visible, return immediately with the news
410                                         return true;
411                                 }
412                         }
413                 }
414 #endif
415                 // nothing to see here, try another path we didn't take earlier
416                 if (nodestackindex == 0)
417                         break;
418                 node = nodestack[--nodestackindex];
419         }
420         // it is not visible
421         return false;
422 }
423
424 typedef struct findnonsolidlocationinfo_s
425 {
426         vec3_t center;
427         vec3_t absmin, absmax;
428         vec_t radius;
429         vec3_t nudge;
430         vec_t bestdist;
431         dp_model_t *model;
432 }
433 findnonsolidlocationinfo_t;
434
435 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
436 {
437         int i, *tri;
438         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
439
440         tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
441         VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
442         VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
443         VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
444         VectorSubtract(vert[1], vert[0], edge[0]);
445         VectorSubtract(vert[2], vert[1], edge[1]);
446         CrossProduct(edge[1], edge[0], facenormal);
447         if (facenormal[0] || facenormal[1] || facenormal[2])
448         {
449                 VectorNormalize(facenormal);
450                 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
451                 if (f <= info->bestdist && f >= -info->bestdist)
452                 {
453                         VectorSubtract(vert[0], vert[2], edge[2]);
454                         VectorNormalize(edge[0]);
455                         VectorNormalize(edge[1]);
456                         VectorNormalize(edge[2]);
457                         CrossProduct(facenormal, edge[0], edgenormal[0]);
458                         CrossProduct(facenormal, edge[1], edgenormal[1]);
459                         CrossProduct(facenormal, edge[2], edgenormal[2]);
460                         // face distance
461                         if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
462                                         && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
463                                         && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
464                         {
465                                 // we got lucky, the center is within the face
466                                 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
467                                 if (dist < 0)
468                                 {
469                                         dist = -dist;
470                                         if (info->bestdist > dist)
471                                         {
472                                                 info->bestdist = dist;
473                                                 VectorScale(facenormal, (info->radius - -dist), info->nudge);
474                                         }
475                                 }
476                                 else
477                                 {
478                                         if (info->bestdist > dist)
479                                         {
480                                                 info->bestdist = dist;
481                                                 VectorScale(facenormal, (info->radius - dist), info->nudge);
482                                         }
483                                 }
484                         }
485                         else
486                         {
487                                 // check which edge or vertex the center is nearest
488                                 for (i = 0;i < 3;i++)
489                                 {
490                                         f = DotProduct(info->center, edge[i]);
491                                         if (f >= DotProduct(vert[0], edge[i])
492                                                         && f <= DotProduct(vert[1], edge[i]))
493                                         {
494                                                 // on edge
495                                                 VectorMA(info->center, -f, edge[i], point);
496                                                 dist = sqrt(DotProduct(point, point));
497                                                 if (info->bestdist > dist)
498                                                 {
499                                                         info->bestdist = dist;
500                                                         VectorScale(point, (info->radius / dist), info->nudge);
501                                                 }
502                                                 // skip both vertex checks
503                                                 // (both are further away than this edge)
504                                                 i++;
505                                         }
506                                         else
507                                         {
508                                                 // not on edge, check first vertex of edge
509                                                 VectorSubtract(info->center, vert[i], point);
510                                                 dist = sqrt(DotProduct(point, point));
511                                                 if (info->bestdist > dist)
512                                                 {
513                                                         info->bestdist = dist;
514                                                         VectorScale(point, (info->radius / dist), info->nudge);
515                                                 }
516                                         }
517                                 }
518                         }
519                 }
520         }
521 }
522
523 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
524 {
525         int surfacenum, k, *mark;
526         msurface_t *surface;
527         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
528         {
529                 surface = info->model->data_surfaces + *mark;
530                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
531                 {
532                         if(surface->deprecatedq3num_bboxstride > 0)
533                         {
534                                 int i, cnt, tri;
535                                 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
536                                 for(i = 0; i < cnt; ++i)
537                                 {
538                                         if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
539                                         {
540                                                 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
541                                                 {
542                                                         tri = i * surface->deprecatedq3num_bboxstride + k;
543                                                         if(tri >= surface->num_triangles)
544                                                                 break;
545                                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
546                                                 }
547                                         }
548                                 }
549                         }
550                         else
551                         {
552                                 for (k = 0;k < surface->num_triangles;k++)
553                                 {
554                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
555                                 }
556                         }
557                 }
558         }
559 }
560
561 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
562 {
563         if (node->plane)
564         {
565                 float f = PlaneDiff(info->center, node->plane);
566                 if (f >= -info->bestdist)
567                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
568                 if (f <= info->bestdist)
569                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
570         }
571         else
572         {
573                 if (((mleaf_t *)node)->numleafsurfaces)
574                         Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
575         }
576 }
577
578 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
579 {
580         int i;
581         findnonsolidlocationinfo_t info;
582         if (model == NULL)
583         {
584                 VectorCopy(in, out);
585                 return;
586         }
587         VectorCopy(in, info.center);
588         info.radius = radius;
589         info.model = model;
590         i = 0;
591         do
592         {
593                 VectorClear(info.nudge);
594                 info.bestdist = radius;
595                 VectorCopy(info.center, info.absmin);
596                 VectorCopy(info.center, info.absmax);
597                 info.absmin[0] -= info.radius + 1;
598                 info.absmin[1] -= info.radius + 1;
599                 info.absmin[2] -= info.radius + 1;
600                 info.absmax[0] += info.radius + 1;
601                 info.absmax[1] += info.radius + 1;
602                 info.absmax[2] += info.radius + 1;
603                 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
604                 VectorAdd(info.center, info.nudge, info.center);
605         }
606         while (info.bestdist < radius && ++i < 10);
607         VectorCopy(info.center, out);
608 }
609
610 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
611 {
612         switch(nativecontents)
613         {
614                 case CONTENTS_EMPTY:
615                         return 0;
616                 case CONTENTS_SOLID:
617                         return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
618                 case CONTENTS_WATER:
619                         return SUPERCONTENTS_WATER;
620                 case CONTENTS_SLIME:
621                         return SUPERCONTENTS_SLIME;
622                 case CONTENTS_LAVA:
623                         return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
624                 case CONTENTS_SKY:
625                         return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
626         }
627         return 0;
628 }
629
630 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
631 {
632         if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
633                 return CONTENTS_SOLID;
634         if (supercontents & SUPERCONTENTS_SKY)
635                 return CONTENTS_SKY;
636         if (supercontents & SUPERCONTENTS_LAVA)
637                 return CONTENTS_LAVA;
638         if (supercontents & SUPERCONTENTS_SLIME)
639                 return CONTENTS_SLIME;
640         if (supercontents & SUPERCONTENTS_WATER)
641                 return CONTENTS_WATER;
642         return CONTENTS_EMPTY;
643 }
644
645 typedef struct RecursiveHullCheckTraceInfo_s
646 {
647         // the hull we're tracing through
648         const hull_t *hull;
649
650         // the trace structure to fill in
651         trace_t *trace;
652
653         // start, end, and end - start (in model space)
654         double start[3];
655         double end[3];
656         double dist[3];
657 }
658 RecursiveHullCheckTraceInfo_t;
659
660 // 1/32 epsilon to keep floating point happy
661 #define DIST_EPSILON (0.03125)
662
663 #define HULLCHECKSTATE_EMPTY 0
664 #define HULLCHECKSTATE_SOLID 1
665 #define HULLCHECKSTATE_DONE 2
666
667 extern cvar_t collision_prefernudgedfraction;
668 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
669 {
670         // status variables, these don't need to be saved on the stack when
671         // recursing...  but are because this should be thread-safe
672         // (note: tracing against a bbox is not thread-safe, yet)
673         int ret;
674         mplane_t *plane;
675         double t1, t2;
676
677         // variables that need to be stored on the stack when recursing
678         mclipnode_t *node;
679         int side;
680         double midf, mid[3];
681
682         // LordHavoc: a goto!  everyone flee in terror... :)
683 loc0:
684         // check for empty
685         if (num < 0)
686         {
687                 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
688                 if (!t->trace->startfound)
689                 {
690                         t->trace->startfound = true;
691                         t->trace->startsupercontents |= num;
692                 }
693                 if (num & SUPERCONTENTS_LIQUIDSMASK)
694                         t->trace->inwater = true;
695                 if (num == 0)
696                         t->trace->inopen = true;
697                 if (num & SUPERCONTENTS_SOLID)
698                         t->trace->hittexture = &mod_q1bsp_texture_solid;
699                 else if (num & SUPERCONTENTS_SKY)
700                         t->trace->hittexture = &mod_q1bsp_texture_sky;
701                 else if (num & SUPERCONTENTS_LAVA)
702                         t->trace->hittexture = &mod_q1bsp_texture_lava;
703                 else if (num & SUPERCONTENTS_SLIME)
704                         t->trace->hittexture = &mod_q1bsp_texture_slime;
705                 else
706                         t->trace->hittexture = &mod_q1bsp_texture_water;
707                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
708                 t->trace->hitsupercontents = num;
709                 if (num & t->trace->hitsupercontentsmask)
710                 {
711                         // if the first leaf is solid, set startsolid
712                         if (t->trace->allsolid)
713                                 t->trace->startsolid = true;
714 #if COLLISIONPARANOID >= 3
715                         Con_Print("S");
716 #endif
717                         return HULLCHECKSTATE_SOLID;
718                 }
719                 else
720                 {
721                         t->trace->allsolid = false;
722 #if COLLISIONPARANOID >= 3
723                         Con_Print("E");
724 #endif
725                         return HULLCHECKSTATE_EMPTY;
726                 }
727         }
728
729         // find the point distances
730         node = t->hull->clipnodes + num;
731
732         plane = t->hull->planes + node->planenum;
733         if (plane->type < 3)
734         {
735                 t1 = p1[plane->type] - plane->dist;
736                 t2 = p2[plane->type] - plane->dist;
737         }
738         else
739         {
740                 t1 = DotProduct (plane->normal, p1) - plane->dist;
741                 t2 = DotProduct (plane->normal, p2) - plane->dist;
742         }
743
744         if (t1 < 0)
745         {
746                 if (t2 < 0)
747                 {
748 #if COLLISIONPARANOID >= 3
749                         Con_Print("<");
750 #endif
751                         num = node->children[1];
752                         goto loc0;
753                 }
754                 side = 1;
755         }
756         else
757         {
758                 if (t2 >= 0)
759                 {
760 #if COLLISIONPARANOID >= 3
761                         Con_Print(">");
762 #endif
763                         num = node->children[0];
764                         goto loc0;
765                 }
766                 side = 0;
767         }
768
769         // the line intersects, find intersection point
770         // LordHavoc: this uses the original trace for maximum accuracy
771 #if COLLISIONPARANOID >= 3
772         Con_Print("M");
773 #endif
774         if (plane->type < 3)
775         {
776                 t1 = t->start[plane->type] - plane->dist;
777                 t2 = t->end[plane->type] - plane->dist;
778         }
779         else
780         {
781                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
782                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
783         }
784
785         midf = t1 / (t1 - t2);
786         midf = bound(p1f, midf, p2f);
787         VectorMA(t->start, midf, t->dist, mid);
788
789         // recurse both sides, front side first
790         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
791         // if this side is not empty, return what it is (solid or done)
792         if (ret != HULLCHECKSTATE_EMPTY)
793                 return ret;
794
795         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
796         // if other side is not solid, return what it is (empty or done)
797         if (ret != HULLCHECKSTATE_SOLID)
798                 return ret;
799
800         // front is air and back is solid, this is the impact point...
801         if (side)
802         {
803                 t->trace->plane.dist = -plane->dist;
804                 VectorNegate (plane->normal, t->trace->plane.normal);
805         }
806         else
807         {
808                 t->trace->plane.dist = plane->dist;
809                 VectorCopy (plane->normal, t->trace->plane.normal);
810         }
811
812         // calculate the true fraction
813         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
814         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
815         midf = t1 / (t1 - t2);
816         t->trace->realfraction = bound(0, midf, 1);
817
818         // calculate the return fraction which is nudged off the surface a bit
819         midf = (t1 - DIST_EPSILON) / (t1 - t2);
820         t->trace->fraction = bound(0, midf, 1);
821
822         if (collision_prefernudgedfraction.integer)
823                 t->trace->realfraction = t->trace->fraction;
824
825 #if COLLISIONPARANOID >= 3
826         Con_Print("D");
827 #endif
828         return HULLCHECKSTATE_DONE;
829 }
830
831 //#if COLLISIONPARANOID < 2
832 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
833 {
834         mplane_t *plane;
835         mclipnode_t *nodes = t->hull->clipnodes;
836         mplane_t *planes = t->hull->planes;
837         vec3_t point;
838         VectorCopy(t->start, point);
839         while (num >= 0)
840         {
841                 plane = planes + nodes[num].planenum;
842                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
843         }
844         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
845         t->trace->startsupercontents |= num;
846         if (num & SUPERCONTENTS_LIQUIDSMASK)
847                 t->trace->inwater = true;
848         if (num == 0)
849                 t->trace->inopen = true;
850         if (num & t->trace->hitsupercontentsmask)
851         {
852                 t->trace->allsolid = t->trace->startsolid = true;
853                 return HULLCHECKSTATE_SOLID;
854         }
855         else
856         {
857                 t->trace->allsolid = t->trace->startsolid = false;
858                 return HULLCHECKSTATE_EMPTY;
859         }
860 }
861 //#endif
862
863 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)
864 {
865         RecursiveHullCheckTraceInfo_t rhc;
866
867         memset(&rhc, 0, sizeof(rhc));
868         memset(trace, 0, sizeof(trace_t));
869         rhc.trace = trace;
870         rhc.trace->fraction = 1;
871         rhc.trace->realfraction = 1;
872         rhc.trace->allsolid = true;
873         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
874         VectorCopy(start, rhc.start);
875         VectorCopy(start, rhc.end);
876         Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
877 }
878
879 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)
880 {
881         RecursiveHullCheckTraceInfo_t rhc;
882
883         if (VectorCompare(start, end))
884         {
885                 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
886                 return;
887         }
888
889         memset(&rhc, 0, sizeof(rhc));
890         memset(trace, 0, sizeof(trace_t));
891         rhc.trace = trace;
892         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
893         rhc.trace->fraction = 1;
894         rhc.trace->realfraction = 1;
895         rhc.trace->allsolid = true;
896         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
897         VectorCopy(start, rhc.start);
898         VectorCopy(end, rhc.end);
899         VectorSubtract(rhc.end, rhc.start, rhc.dist);
900 #if COLLISIONPARANOID >= 2
901         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]);
902         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
903         {
904
905                 double test[3];
906                 trace_t testtrace;
907                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
908                 memset(&testtrace, 0, sizeof(trace_t));
909                 rhc.trace = &testtrace;
910                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
911                 rhc.trace->fraction = 1;
912                 rhc.trace->realfraction = 1;
913                 rhc.trace->allsolid = true;
914                 VectorCopy(test, rhc.start);
915                 VectorCopy(test, rhc.end);
916                 VectorClear(rhc.dist);
917                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
918                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
919                 if (!trace->startsolid && testtrace.startsolid)
920                         Con_Printf(" - ended in solid!\n");
921         }
922         Con_Print("\n");
923 #else
924         if (VectorLength2(rhc.dist))
925                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
926         else
927                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
928 #endif
929 }
930
931 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)
932 {
933         // this function currently only supports same size start and end
934         double boxsize[3];
935         RecursiveHullCheckTraceInfo_t rhc;
936
937         if (VectorCompare(boxmins, boxmaxs))
938         {
939                 if (VectorCompare(start, end))
940                         Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
941                 else
942                         Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
943                 return;
944         }
945
946         memset(&rhc, 0, sizeof(rhc));
947         memset(trace, 0, sizeof(trace_t));
948         rhc.trace = trace;
949         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
950         rhc.trace->fraction = 1;
951         rhc.trace->realfraction = 1;
952         rhc.trace->allsolid = true;
953         VectorSubtract(boxmaxs, boxmins, boxsize);
954         if (boxsize[0] < 3)
955                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
956         else if (model->brush.ishlbsp)
957         {
958                 // LordHavoc: this has to have a minor tolerance (the .1) because of
959                 // minor float precision errors from the box being transformed around
960                 if (boxsize[0] < 32.1)
961                 {
962                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
963                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
964                         else
965                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
966                 }
967                 else
968                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
969         }
970         else
971         {
972                 // LordHavoc: this has to have a minor tolerance (the .1) because of
973                 // minor float precision errors from the box being transformed around
974                 if (boxsize[0] < 32.1)
975                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
976                 else
977                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
978         }
979         VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
980         VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
981         VectorSubtract(rhc.end, rhc.start, rhc.dist);
982 #if COLLISIONPARANOID >= 2
983         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]);
984         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
985         {
986
987                 double test[3];
988                 trace_t testtrace;
989                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
990                 memset(&testtrace, 0, sizeof(trace_t));
991                 rhc.trace = &testtrace;
992                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
993                 rhc.trace->fraction = 1;
994                 rhc.trace->realfraction = 1;
995                 rhc.trace->allsolid = true;
996                 VectorCopy(test, rhc.start);
997                 VectorCopy(test, rhc.end);
998                 VectorClear(rhc.dist);
999                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1000                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1001                 if (!trace->startsolid && testtrace.startsolid)
1002                         Con_Printf(" - ended in solid!\n");
1003         }
1004         Con_Print("\n");
1005 #else
1006         if (VectorLength2(rhc.dist))
1007                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1008         else
1009                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1010 #endif
1011 }
1012
1013 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1014 {
1015         int num = model->brushq1.hulls[0].firstclipnode;
1016         mplane_t *plane;
1017         mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1018         mplane_t *planes = model->brushq1.hulls[0].planes;
1019         while (num >= 0)
1020         {
1021                 plane = planes + nodes[num].planenum;
1022                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1023         }
1024         return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1025 }
1026
1027 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)
1028 {
1029 #if 1
1030         colbrushf_t cbox;
1031         colplanef_t cbox_planes[6];
1032         cbox.isaabb = true;
1033         cbox.hasaabbplanes = true;
1034         cbox.supercontents = boxsupercontents;
1035         cbox.numplanes = 6;
1036         cbox.numpoints = 0;
1037         cbox.numtriangles = 0;
1038         cbox.planes = cbox_planes;
1039         cbox.points = NULL;
1040         cbox.elements = NULL;
1041         cbox.markframe = 0;
1042         cbox.mins[0] = 0;
1043         cbox.mins[1] = 0;
1044         cbox.mins[2] = 0;
1045         cbox.maxs[0] = 0;
1046         cbox.maxs[1] = 0;
1047         cbox.maxs[2] = 0;
1048         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];
1049         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];
1050         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];
1051         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];
1052         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];
1053         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];
1054         cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1055         cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1056         cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1057         cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1058         cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1059         cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1060         memset(trace, 0, sizeof(trace_t));
1061         trace->hitsupercontentsmask = hitsupercontentsmask;
1062         trace->fraction = 1;
1063         trace->realfraction = 1;
1064         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1065 #else
1066         RecursiveHullCheckTraceInfo_t rhc;
1067         static hull_t box_hull;
1068         static mclipnode_t box_clipnodes[6];
1069         static mplane_t box_planes[6];
1070         // fill in a default trace
1071         memset(&rhc, 0, sizeof(rhc));
1072         memset(trace, 0, sizeof(trace_t));
1073         //To keep everything totally uniform, bounding boxes are turned into small
1074         //BSP trees instead of being compared directly.
1075         // create a temp hull from bounding box sizes
1076         box_planes[0].dist = cmaxs[0] - mins[0];
1077         box_planes[1].dist = cmins[0] - maxs[0];
1078         box_planes[2].dist = cmaxs[1] - mins[1];
1079         box_planes[3].dist = cmins[1] - maxs[1];
1080         box_planes[4].dist = cmaxs[2] - mins[2];
1081         box_planes[5].dist = cmins[2] - maxs[2];
1082 #if COLLISIONPARANOID >= 3
1083         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]);
1084 #endif
1085
1086         if (box_hull.clipnodes == NULL)
1087         {
1088                 int i, side;
1089
1090                 //Set up the planes and clipnodes so that the six floats of a bounding box
1091                 //can just be stored out and get a proper hull_t structure.
1092
1093                 box_hull.clipnodes = box_clipnodes;
1094                 box_hull.planes = box_planes;
1095                 box_hull.firstclipnode = 0;
1096                 box_hull.lastclipnode = 5;
1097
1098                 for (i = 0;i < 6;i++)
1099                 {
1100                         box_clipnodes[i].planenum = i;
1101
1102                         side = i&1;
1103
1104                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1105                         if (i != 5)
1106                                 box_clipnodes[i].children[side^1] = i + 1;
1107                         else
1108                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1109
1110                         box_planes[i].type = i>>1;
1111                         box_planes[i].normal[i>>1] = 1;
1112                 }
1113         }
1114
1115         // trace a line through the generated clipping hull
1116         //rhc.boxsupercontents = boxsupercontents;
1117         rhc.hull = &box_hull;
1118         rhc.trace = trace;
1119         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1120         rhc.trace->fraction = 1;
1121         rhc.trace->realfraction = 1;
1122         rhc.trace->allsolid = true;
1123         VectorCopy(start, rhc.start);
1124         VectorCopy(end, rhc.end);
1125         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1126         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1127         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1128         if (rhc.trace->startsupercontents)
1129                 rhc.trace->startsupercontents = boxsupercontents;
1130 #endif
1131 }
1132
1133 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)
1134 {
1135         memset(trace, 0, sizeof(trace_t));
1136         trace->fraction = 1;
1137         trace->realfraction = 1;
1138         if (BoxesOverlap(start, start, cmins, cmaxs))
1139         {
1140                 trace->startsupercontents |= boxsupercontents;
1141                 if (hitsupercontentsmask & boxsupercontents)
1142                 {
1143                         trace->startsolid = true;
1144                         trace->allsolid = true;
1145                 }
1146         }
1147 }
1148
1149 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1150 {
1151         trace_t trace;
1152         model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1153         return trace.fraction == 1;
1154 }
1155
1156 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)
1157 {
1158         int side;
1159         float front, back;
1160         float mid, distz = endz - startz;
1161
1162 loc0:
1163         if (!node->plane)
1164                 return false;           // didn't hit anything
1165
1166         switch (node->plane->type)
1167         {
1168         case PLANE_X:
1169                 node = node->children[x < node->plane->dist];
1170                 goto loc0;
1171         case PLANE_Y:
1172                 node = node->children[y < node->plane->dist];
1173                 goto loc0;
1174         case PLANE_Z:
1175                 side = startz < node->plane->dist;
1176                 if ((endz < node->plane->dist) == side)
1177                 {
1178                         node = node->children[side];
1179                         goto loc0;
1180                 }
1181                 // found an intersection
1182                 mid = node->plane->dist;
1183                 break;
1184         default:
1185                 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1186                 front += startz * node->plane->normal[2];
1187                 back += endz * node->plane->normal[2];
1188                 side = front < node->plane->dist;
1189                 if ((back < node->plane->dist) == side)
1190                 {
1191                         node = node->children[side];
1192                         goto loc0;
1193                 }
1194                 // found an intersection
1195                 mid = startz + distz * (front - node->plane->dist) / (front - back);
1196                 break;
1197         }
1198
1199         // go down front side
1200         if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1201                 return true;    // hit something
1202         else
1203         {
1204                 // check for impact on this node
1205                 if (node->numsurfaces)
1206                 {
1207                         int i, dsi, dti, lmwidth, lmheight;
1208                         float ds, dt;
1209                         msurface_t *surface;
1210                         unsigned char *lightmap;
1211                         int maps, line3, size3;
1212                         float dsfrac;
1213                         float dtfrac;
1214                         float scale, w, w00, w01, w10, w11;
1215
1216                         surface = model->data_surfaces + node->firstsurface;
1217                         for (i = 0;i < node->numsurfaces;i++, surface++)
1218                         {
1219                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1220                                         continue;       // no lightmaps
1221
1222                                 // location we want to sample in the lightmap
1223                                 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;
1224                                 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;
1225
1226                                 // check the bounds
1227                                 dsi = (int)ds;
1228                                 dti = (int)dt;
1229                                 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1230                                 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1231
1232                                 // is it in bounds?
1233                                 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1234                                 {
1235                                         // calculate bilinear interpolation factors
1236                                         // and also multiply by fixedpoint conversion factors
1237                                         dsfrac = ds - dsi;
1238                                         dtfrac = dt - dti;
1239                                         w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1240                                         w01 = (    dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1241                                         w10 = (1 - dsfrac) * (    dtfrac) * (1.0f / 32768.0f);
1242                                         w11 = (    dsfrac) * (    dtfrac) * (1.0f / 32768.0f);
1243
1244                                         // values for pointer math
1245                                         line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1246                                         size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1247
1248                                         // look up the pixel
1249                                         lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1250
1251                                         // bilinear filter each lightmap style, and sum them
1252                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1253                                         {
1254                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1255                                                 w = w00 * scale;VectorMA(ambientcolor, w, lightmap            , ambientcolor);
1256                                                 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3        , ambientcolor);
1257                                                 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3    , ambientcolor);
1258                                                 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1259                                                 lightmap += size3;
1260                                         }
1261
1262                                         return true; // success
1263                                 }
1264                         }
1265                 }
1266
1267                 // go down back side
1268                 node = node->children[side ^ 1];
1269                 startz = mid;
1270                 distz = endz - startz;
1271                 goto loc0;
1272         }
1273 }
1274
1275 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1276 {
1277         // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1278         VectorSet(diffusenormal, 0, 0, 1);
1279
1280         if (!model->brushq1.lightdata)
1281         {
1282                 VectorSet(ambientcolor, 1, 1, 1);
1283                 VectorSet(diffusecolor, 0, 0, 0);
1284                 return;
1285         }
1286
1287         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);
1288 }
1289
1290 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1291 {
1292         int c;
1293         unsigned char *outstart = out;
1294         while (out < outend)
1295         {
1296                 if (in == inend)
1297                 {
1298                         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));
1299                         return;
1300                 }
1301                 c = *in++;
1302                 if (c)
1303                         *out++ = c;
1304                 else
1305                 {
1306                         if (in == inend)
1307                         {
1308                                 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));
1309                                 return;
1310                         }
1311                         for (c = *in++;c > 0;c--)
1312                         {
1313                                 if (out == outend)
1314                                 {
1315                                         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));
1316                                         return;
1317                                 }
1318                                 *out++ = 0;
1319                         }
1320                 }
1321         }
1322 }
1323
1324 /*
1325 =============
1326 R_Q1BSP_LoadSplitSky
1327
1328 A sky texture is 256*128, with the right side being a masked overlay
1329 ==============
1330 */
1331 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1332 {
1333         int x, y;
1334         int w = width/2;
1335         int h = height;
1336         unsigned *solidpixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1337         unsigned *alphapixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1338
1339         // allocate a texture pool if we need it
1340         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1341                 loadmodel->texturepool = R_AllocTexturePool();
1342
1343         if (bytesperpixel == 4)
1344         {
1345                 for (y = 0;y < h;y++)
1346                 {
1347                         for (x = 0;x < w;x++)
1348                         {
1349                                 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1350                                 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1351                         }
1352                 }
1353         }
1354         else
1355         {
1356                 // make an average value for the back to avoid
1357                 // a fringe on the top level
1358                 int p, r, g, b;
1359                 union
1360                 {
1361                         unsigned int i;
1362                         unsigned char b[4];
1363                 }
1364                 bgra;
1365                 r = g = b = 0;
1366                 for (y = 0;y < h;y++)
1367                 {
1368                         for (x = 0;x < w;x++)
1369                         {
1370                                 p = src[x*width+y+w];
1371                                 r += palette_rgb[p][0];
1372                                 g += palette_rgb[p][1];
1373                                 b += palette_rgb[p][2];
1374                         }
1375                 }
1376                 bgra.b[2] = r/(w*h);
1377                 bgra.b[1] = g/(w*h);
1378                 bgra.b[0] = b/(w*h);
1379                 bgra.b[3] = 0;
1380                 for (y = 0;y < h;y++)
1381                 {
1382                         for (x = 0;x < w;x++)
1383                         {
1384                                 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1385                                 p = src[y*width+x];
1386                                 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1387                         }
1388                 }
1389         }
1390
1391         loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0         , (unsigned char *) solidpixels, w, h);
1392         loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1393         Mem_Free(solidpixels);
1394         Mem_Free(alphapixels);
1395 }
1396
1397 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1398 {
1399         int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1400         skinframe_t *skinframe;
1401         miptex_t *dmiptex;
1402         texture_t *tx, *tx2, *anims[10], *altanims[10];
1403         dmiptexlump_t *m;
1404         unsigned char *data, *mtdata;
1405         const char *s;
1406         char mapname[MAX_QPATH], name[MAX_QPATH];
1407         unsigned char zero[4];
1408
1409         memset(zero, 0, sizeof(zero));
1410
1411         loadmodel->data_textures = NULL;
1412
1413         // add two slots for notexture walls and notexture liquids
1414         if (l->filelen)
1415         {
1416                 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1417                 m->nummiptex = LittleLong (m->nummiptex);
1418                 loadmodel->num_textures = m->nummiptex + 2;
1419                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1420         }
1421         else
1422         {
1423                 m = NULL;
1424                 loadmodel->num_textures = 2;
1425                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1426         }
1427
1428         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1429
1430         // fill out all slots with notexture
1431         if (cls.state != ca_dedicated)
1432                 skinframe = R_SkinFrame_LoadMissing();
1433         else
1434                 skinframe = NULL;
1435         for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1436         {
1437                 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1438                 tx->width = 16;
1439                 tx->height = 16;
1440                 if (cls.state != ca_dedicated)
1441                 {
1442                         tx->numskinframes = 1;
1443                         tx->skinframerate = 1;
1444                         tx->skinframes[0] = skinframe;
1445                         tx->currentskinframe = tx->skinframes[0];
1446                 }
1447                 tx->basematerialflags = MATERIALFLAG_WALL;
1448                 if (i == loadmodel->num_textures - 1)
1449                 {
1450                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1451                         tx->supercontents = mod_q1bsp_texture_water.supercontents;
1452                         tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1453                 }
1454                 else
1455                 {
1456                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1457                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1458                 }
1459                 tx->currentframe = tx;
1460
1461                 // clear water settings
1462                 tx->reflectmin = 0;
1463                 tx->reflectmax = 1;
1464                 tx->refractfactor = 1;
1465                 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1466                 tx->reflectfactor = 1;
1467                 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1468                 tx->r_water_wateralpha = 1;
1469                 tx->offsetmapping = OFFSETMAPPING_OFF;
1470                 tx->offsetscale = 1;
1471                 tx->specularscalemod = 1;
1472                 tx->specularpowermod = 1;
1473         }
1474
1475         if (!m)
1476         {
1477                 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1478                 return;
1479         }
1480
1481         s = loadmodel->name;
1482         if (!strncasecmp(s, "maps/", 5))
1483                 s += 5;
1484         FS_StripExtension(s, mapname, sizeof(mapname));
1485
1486         // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1487         dofs = m->dataofs;
1488         // LordHavoc: mostly rewritten map texture loader
1489         for (i = 0;i < m->nummiptex;i++)
1490         {
1491                 dofs[i] = LittleLong(dofs[i]);
1492                 if (r_nosurftextures.integer)
1493                         continue;
1494                 if (dofs[i] == -1)
1495                 {
1496                         Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1497                         continue;
1498                 }
1499                 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1500
1501                 // copy name, but only up to 16 characters
1502                 // (the output buffer can hold more than this, but the input buffer is
1503                 //  only 16)
1504                 for (j = 0;j < 16 && dmiptex->name[j];j++)
1505                         name[j] = dmiptex->name[j];
1506                 name[j] = 0;
1507
1508                 if (!name[0])
1509                 {
1510                         dpsnprintf(name, sizeof(name), "unnamed%i", i);
1511                         Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1512                 }
1513
1514                 mtwidth = LittleLong(dmiptex->width);
1515                 mtheight = LittleLong(dmiptex->height);
1516                 mtdata = NULL;
1517                 j = LittleLong(dmiptex->offsets[0]);
1518                 if (j)
1519                 {
1520                         // texture included
1521                         if (j < 40 || j + mtwidth * mtheight > l->filelen)
1522                         {
1523                                 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1524                                 continue;
1525                         }
1526                         mtdata = (unsigned char *)dmiptex + j;
1527                 }
1528
1529                 if ((mtwidth & 15) || (mtheight & 15))
1530                         Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1531
1532                 // LordHavoc: force all names to lowercase
1533                 for (j = 0;name[j];j++)
1534                         if (name[j] >= 'A' && name[j] <= 'Z')
1535                                 name[j] += 'a' - 'A';
1536
1537                 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1538                         continue;
1539
1540                 tx = loadmodel->data_textures + i;
1541                 strlcpy(tx->name, name, sizeof(tx->name));
1542                 tx->width = mtwidth;
1543                 tx->height = mtheight;
1544
1545                 if (tx->name[0] == '*')
1546                 {
1547                         if (!strncmp(tx->name, "*lava", 5))
1548                         {
1549                                 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1550                                 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1551                         }
1552                         else if (!strncmp(tx->name, "*slime", 6))
1553                         {
1554                                 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1555                                 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1556                         }
1557                         else
1558                         {
1559                                 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1560                                 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1561                         }
1562                 }
1563                 else if (!strncmp(tx->name, "sky", 3))
1564                 {
1565                         tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1566                         tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1567                 }
1568                 else
1569                 {
1570                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1571                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1572                 }
1573
1574                 if (cls.state != ca_dedicated)
1575                 {
1576                         // LordHavoc: HL sky textures are entirely different than quake
1577                         if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1578                         {
1579                                 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), false, false, r_texture_convertsRGB_skin.integer);
1580                                 if (!data)
1581                                         data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, r_texture_convertsRGB_skin.integer);
1582                                 if (data && image_width == image_height * 2)
1583                                 {
1584                                         R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1585                                         Mem_Free(data);
1586                                 }
1587                                 else if (mtdata != NULL)
1588                                         R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1589                         }
1590                         else
1591                         {
1592                                 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);
1593                                 if (!skinframe)
1594                                         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);
1595                                 if (!skinframe)
1596                                 {
1597                                         // did not find external texture, load it from the bsp or wad3
1598                                         if (loadmodel->brush.ishlbsp)
1599                                         {
1600                                                 // internal texture overrides wad
1601                                                 unsigned char *pixels, *freepixels;
1602                                                 pixels = freepixels = NULL;
1603                                                 if (mtdata)
1604                                                         pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1605                                                 if (pixels == NULL)
1606                                                         pixels = freepixels = W_GetTextureBGRA(tx->name);
1607                                                 if (pixels != NULL)
1608                                                 {
1609                                                         tx->width = image_width;
1610                                                         tx->height = image_height;
1611                                                         skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height);
1612                                                 }
1613                                                 if (freepixels)
1614                                                         Mem_Free(freepixels);
1615                                         }
1616                                         else if (mtdata) // texture included
1617                                                 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1618                                 }
1619                                 // if skinframe is still NULL the "missing" texture will be used
1620                                 if (skinframe)
1621                                         tx->skinframes[0] = skinframe;
1622                         }
1623
1624                         tx->basematerialflags = MATERIALFLAG_WALL;
1625                         if (tx->name[0] == '*')
1626                         {
1627                                 // LordHavoc: some turbulent textures should not be affected by wateralpha
1628                                 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1629                                 {
1630                                         // replace the texture with transparent black
1631                                         Vector4Set(zero, 128, 128, 128, 128);
1632                                         tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1633                                         tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1634                                 }
1635                                 else if (!strncmp(tx->name,"*lava",5)
1636                                  || !strncmp(tx->name,"*teleport",9)
1637                                  || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1638                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1639                                 else
1640                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1641                                 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1642                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1643                         }
1644                         else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1645                         {
1646                                 // replace the texture with black
1647                                 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1648                                 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1649                         }
1650                         else if (!strncmp(tx->name, "sky", 3))
1651                                 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1652                         else if (!strcmp(tx->name, "caulk"))
1653                                 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1654                         else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1655                                 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1656
1657                         // start out with no animation
1658                         tx->currentframe = tx;
1659                         tx->currentskinframe = tx->skinframes[0];
1660                 }
1661         }
1662
1663         // sequence the animations
1664         for (i = 0;i < m->nummiptex;i++)
1665         {
1666                 tx = loadmodel->data_textures + i;
1667                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1668                         continue;
1669                 if (tx->anim_total[0] || tx->anim_total[1])
1670                         continue;       // already sequenced
1671
1672                 // find the number of frames in the animation
1673                 memset(anims, 0, sizeof(anims));
1674                 memset(altanims, 0, sizeof(altanims));
1675
1676                 for (j = i;j < m->nummiptex;j++)
1677                 {
1678                         tx2 = loadmodel->data_textures + j;
1679                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1680                                 continue;
1681
1682                         num = tx2->name[1];
1683                         if (num >= '0' && num <= '9')
1684                                 anims[num - '0'] = tx2;
1685                         else if (num >= 'a' && num <= 'j')
1686                                 altanims[num - 'a'] = tx2;
1687                         else
1688                                 Con_Printf("Bad animating texture %s\n", tx->name);
1689                 }
1690
1691                 max = altmax = 0;
1692                 for (j = 0;j < 10;j++)
1693                 {
1694                         if (anims[j])
1695                                 max = j + 1;
1696                         if (altanims[j])
1697                                 altmax = j + 1;
1698                 }
1699                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1700
1701                 incomplete = false;
1702                 for (j = 0;j < max;j++)
1703                 {
1704                         if (!anims[j])
1705                         {
1706                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1707                                 incomplete = true;
1708                         }
1709                 }
1710                 for (j = 0;j < altmax;j++)
1711                 {
1712                         if (!altanims[j])
1713                         {
1714                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1715                                 incomplete = true;
1716                         }
1717                 }
1718                 if (incomplete)
1719                         continue;
1720
1721                 if (altmax < 1)
1722                 {
1723                         // if there is no alternate animation, duplicate the primary
1724                         // animation into the alternate
1725                         altmax = max;
1726                         for (k = 0;k < 10;k++)
1727                                 altanims[k] = anims[k];
1728                 }
1729
1730                 // link together the primary animation
1731                 for (j = 0;j < max;j++)
1732                 {
1733                         tx2 = anims[j];
1734                         tx2->animated = true;
1735                         tx2->anim_total[0] = max;
1736                         tx2->anim_total[1] = altmax;
1737                         for (k = 0;k < 10;k++)
1738                         {
1739                                 tx2->anim_frames[0][k] = anims[k];
1740                                 tx2->anim_frames[1][k] = altanims[k];
1741                         }
1742                 }
1743
1744                 // if there really is an alternate anim...
1745                 if (anims[0] != altanims[0])
1746                 {
1747                         // link together the alternate animation
1748                         for (j = 0;j < altmax;j++)
1749                         {
1750                                 tx2 = altanims[j];
1751                                 tx2->animated = true;
1752                                 // the primary/alternate are reversed here
1753                                 tx2->anim_total[0] = altmax;
1754                                 tx2->anim_total[1] = max;
1755                                 for (k = 0;k < 10;k++)
1756                                 {
1757                                         tx2->anim_frames[0][k] = altanims[k];
1758                                         tx2->anim_frames[1][k] = anims[k];
1759                                 }
1760                         }
1761                 }
1762         }
1763 }
1764
1765 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1766 {
1767         int i;
1768         unsigned char *in, *out, *data, d;
1769         char litfilename[MAX_QPATH];
1770         char dlitfilename[MAX_QPATH];
1771         fs_offset_t filesize;
1772         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1773         {
1774                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1775                 for (i=0; i<l->filelen; i++)
1776                         loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1777         }
1778         else // LordHavoc: bsp version 29 (normal white lighting)
1779         {
1780                 // LordHavoc: hope is not lost yet, check for a .lit file to load
1781                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1782                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1783                 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1784                 strlcat (litfilename, ".lit", sizeof (litfilename));
1785                 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1786                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1787                 if (data)
1788                 {
1789                         if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1790                         {
1791                                 i = LittleLong(((int *)data)[1]);
1792                                 if (i == 1)
1793                                 {
1794                                         if (developer_loading.integer)
1795                                                 Con_Printf("loaded %s\n", litfilename);
1796                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1797                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1798                                         Mem_Free(data);
1799                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1800                                         if (data)
1801                                         {
1802                                                 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1803                                                 {
1804                                                         i = LittleLong(((int *)data)[1]);
1805                                                         if (i == 1)
1806                                                         {
1807                                                                 if (developer_loading.integer)
1808                                                                         Con_Printf("loaded %s\n", dlitfilename);
1809                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1810                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1811                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
1812                                                                 loadmodel->brushq3.deluxemapping = true;
1813                                                         }
1814                                                 }
1815                                                 Mem_Free(data);
1816                                                 data = NULL;
1817                                         }
1818                                         return;
1819                                 }
1820                                 else
1821                                         Con_Printf("Unknown .lit file version (%d)\n", i);
1822                         }
1823                         else if (filesize == 8)
1824                                 Con_Print("Empty .lit file, ignoring\n");
1825                         else
1826                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
1827                         if (data)
1828                         {
1829                                 Mem_Free(data);
1830                                 data = NULL;
1831                         }
1832                 }
1833                 // LordHavoc: oh well, expand the white lighting data
1834                 if (!l->filelen)
1835                         return;
1836                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1837                 in = mod_base + l->fileofs;
1838                 out = loadmodel->brushq1.lightdata;
1839                 for (i = 0;i < l->filelen;i++)
1840                 {
1841                         d = *in++;
1842                         *out++ = d;
1843                         *out++ = d;
1844                         *out++ = d;
1845                 }
1846         }
1847 }
1848
1849 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1850 {
1851         loadmodel->brushq1.num_compressedpvs = 0;
1852         loadmodel->brushq1.data_compressedpvs = NULL;
1853         if (!l->filelen)
1854                 return;
1855         loadmodel->brushq1.num_compressedpvs = l->filelen;
1856         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1857         memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1858 }
1859
1860 // used only for HalfLife maps
1861 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1862 {
1863         char key[128], value[4096];
1864         int i, j, k;
1865         if (!data)
1866                 return;
1867         if (!COM_ParseToken_Simple(&data, false, false))
1868                 return; // error
1869         if (com_token[0] != '{')
1870                 return; // error
1871         while (1)
1872         {
1873                 if (!COM_ParseToken_Simple(&data, false, false))
1874                         return; // error
1875                 if (com_token[0] == '}')
1876                         break; // end of worldspawn
1877                 if (com_token[0] == '_')
1878                         strlcpy(key, com_token + 1, sizeof(key));
1879                 else
1880                         strlcpy(key, com_token, sizeof(key));
1881                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1882                         key[strlen(key)-1] = 0;
1883                 if (!COM_ParseToken_Simple(&data, false, false))
1884                         return; // error
1885                 dpsnprintf(value, sizeof(value), "%s", com_token);
1886                 if (!strcmp("wad", key)) // for HalfLife maps
1887                 {
1888                         if (loadmodel->brush.ishlbsp)
1889                         {
1890                                 j = 0;
1891                                 for (i = 0;i < (int)sizeof(value);i++)
1892                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1893                                                 break;
1894                                 if (value[i])
1895                                 {
1896                                         for (;i < (int)sizeof(value);i++)
1897                                         {
1898                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1899                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1900                                                         j = i+1;
1901                                                 else if (value[i] == ';' || value[i] == 0)
1902                                                 {
1903                                                         k = value[i];
1904                                                         value[i] = 0;
1905                                                         W_LoadTextureWadFile(&value[j], false);
1906                                                         j = i+1;
1907                                                         if (!k)
1908                                                                 break;
1909                                                 }
1910                                         }
1911                                 }
1912                         }
1913                 }
1914         }
1915 }
1916
1917 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1918 {
1919         loadmodel->brush.entities = NULL;
1920         if (!l->filelen)
1921                 return;
1922         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
1923         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1924         loadmodel->brush.entities[l->filelen] = 0;
1925         if (loadmodel->brush.ishlbsp)
1926                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1927 }
1928
1929
1930 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1931 {
1932         dvertex_t       *in;
1933         mvertex_t       *out;
1934         int                     i, count;
1935
1936         in = (dvertex_t *)(mod_base + l->fileofs);
1937         if (l->filelen % sizeof(*in))
1938                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1939         count = l->filelen / sizeof(*in);
1940         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1941
1942         loadmodel->brushq1.vertexes = out;
1943         loadmodel->brushq1.numvertexes = count;
1944
1945         for ( i=0 ; i<count ; i++, in++, out++)
1946         {
1947                 out->position[0] = LittleFloat(in->point[0]);
1948                 out->position[1] = LittleFloat(in->point[1]);
1949                 out->position[2] = LittleFloat(in->point[2]);
1950         }
1951 }
1952
1953 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1954 // can be used for this
1955 // REMOVEME
1956 int SB_ReadInt (unsigned char **buffer)
1957 {
1958         int     i;
1959         i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1960         (*buffer) += 4;
1961         return i;
1962 }
1963
1964 // REMOVEME
1965 float SB_ReadFloat (unsigned char **buffer)
1966 {
1967         union
1968         {
1969                 int             i;
1970                 float   f;
1971         } u;
1972
1973         u.i = SB_ReadInt (buffer);
1974         return u.f;
1975 }
1976
1977 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1978 {
1979         unsigned char           *index;
1980         dmodel_t        *out;
1981         int                     i, j, count;
1982
1983         index = (unsigned char *)(mod_base + l->fileofs);
1984         if (l->filelen % (48+4*hullinfo->filehulls))
1985                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1986
1987         count = l->filelen / (48+4*hullinfo->filehulls);
1988         out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1989
1990         loadmodel->brushq1.submodels = out;
1991         loadmodel->brush.numsubmodels = count;
1992
1993         for (i = 0; i < count; i++, out++)
1994         {
1995         // spread out the mins / maxs by a pixel
1996                 out->mins[0] = SB_ReadFloat (&index) - 1;
1997                 out->mins[1] = SB_ReadFloat (&index) - 1;
1998                 out->mins[2] = SB_ReadFloat (&index) - 1;
1999                 out->maxs[0] = SB_ReadFloat (&index) + 1;
2000                 out->maxs[1] = SB_ReadFloat (&index) + 1;
2001                 out->maxs[2] = SB_ReadFloat (&index) + 1;
2002                 out->origin[0] = SB_ReadFloat (&index);
2003                 out->origin[1] = SB_ReadFloat (&index);
2004                 out->origin[2] = SB_ReadFloat (&index);
2005                 for (j = 0; j < hullinfo->filehulls; j++)
2006                         out->headnode[j] = SB_ReadInt (&index);
2007                 out->visleafs = SB_ReadInt (&index);
2008                 out->firstface = SB_ReadInt (&index);
2009                 out->numfaces = SB_ReadInt (&index);
2010         }
2011 }
2012
2013 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2014 {
2015         dedge_t *in;
2016         medge_t *out;
2017         int     i, count;
2018
2019         in = (dedge_t *)(mod_base + l->fileofs);
2020         if (l->filelen % sizeof(*in))
2021                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2022         count = l->filelen / sizeof(*in);
2023         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2024
2025         loadmodel->brushq1.edges = out;
2026         loadmodel->brushq1.numedges = count;
2027
2028         for ( i=0 ; i<count ; i++, in++, out++)
2029         {
2030                 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2031                 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2032                 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2033                 {
2034                         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);
2035                         if(!loadmodel->brushq1.numvertexes)
2036                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2037                                 
2038                         out->v[0] = 0;
2039                         out->v[1] = 0;
2040                 }
2041         }
2042 }
2043
2044 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2045 {
2046         texinfo_t *in;
2047         mtexinfo_t *out;
2048         int i, j, k, count, miptex;
2049
2050         in = (texinfo_t *)(mod_base + l->fileofs);
2051         if (l->filelen % sizeof(*in))
2052                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2053         count = l->filelen / sizeof(*in);
2054         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2055
2056         loadmodel->brushq1.texinfo = out;
2057         loadmodel->brushq1.numtexinfo = count;
2058
2059         for (i = 0;i < count;i++, in++, out++)
2060         {
2061                 for (k = 0;k < 2;k++)
2062                         for (j = 0;j < 4;j++)
2063                                 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2064
2065                 miptex = LittleLong(in->miptex);
2066                 out->flags = LittleLong(in->flags);
2067
2068                 out->texture = NULL;
2069                 if (loadmodel->data_textures)
2070                 {
2071                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2072                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2073                         else
2074                                 out->texture = loadmodel->data_textures + miptex;
2075                 }
2076                 if (out->flags & TEX_SPECIAL)
2077                 {
2078                         // if texture chosen is NULL or the shader needs a lightmap,
2079                         // force to notexture water shader
2080                         if (out->texture == NULL)
2081                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2082                 }
2083                 else
2084                 {
2085                         // if texture chosen is NULL, force to notexture
2086                         if (out->texture == NULL)
2087                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2088                 }
2089         }
2090 }
2091
2092 #if 0
2093 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2094 {
2095         int             i, j;
2096         float   *v;
2097
2098         mins[0] = mins[1] = mins[2] = 9999;
2099         maxs[0] = maxs[1] = maxs[2] = -9999;
2100         v = verts;
2101         for (i = 0;i < numverts;i++)
2102         {
2103                 for (j = 0;j < 3;j++, v++)
2104                 {
2105                         if (*v < mins[j])
2106                                 mins[j] = *v;
2107                         if (*v > maxs[j])
2108                                 maxs[j] = *v;
2109                 }
2110         }
2111 }
2112
2113 #define MAX_SUBDIVPOLYTRIANGLES 4096
2114 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2115
2116 static int subdivpolyverts, subdivpolytriangles;
2117 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2118 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2119
2120 static int subdivpolylookupvert(vec3_t v)
2121 {
2122         int i;
2123         for (i = 0;i < subdivpolyverts;i++)
2124                 if (subdivpolyvert[i][0] == v[0]
2125                  && subdivpolyvert[i][1] == v[1]
2126                  && subdivpolyvert[i][2] == v[2])
2127                         return i;
2128         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2129                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2130         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2131         return subdivpolyverts++;
2132 }
2133
2134 static void SubdividePolygon(int numverts, float *verts)
2135 {
2136         int             i, i1, i2, i3, f, b, c, p;
2137         vec3_t  mins, maxs, front[256], back[256];
2138         float   m, *pv, *cv, dist[256], frac;
2139
2140         if (numverts > 250)
2141                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2142
2143         BoundPoly(numverts, verts, mins, maxs);
2144
2145         for (i = 0;i < 3;i++)
2146         {
2147                 m = (mins[i] + maxs[i]) * 0.5;
2148                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2149                 if (maxs[i] - m < 8)
2150                         continue;
2151                 if (m - mins[i] < 8)
2152                         continue;
2153
2154                 // cut it
2155                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2156                         dist[c] = cv[i] - m;
2157
2158                 f = b = 0;
2159                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2160                 {
2161                         if (dist[p] >= 0)
2162                         {
2163                                 VectorCopy(pv, front[f]);
2164                                 f++;
2165                         }
2166                         if (dist[p] <= 0)
2167                         {
2168                                 VectorCopy(pv, back[b]);
2169                                 b++;
2170                         }
2171                         if (dist[p] == 0 || dist[c] == 0)
2172                                 continue;
2173                         if ((dist[p] > 0) != (dist[c] > 0) )
2174                         {
2175                                 // clip point
2176                                 frac = dist[p] / (dist[p] - dist[c]);
2177                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2178                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2179                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2180                                 f++;
2181                                 b++;
2182                         }
2183                 }
2184
2185                 SubdividePolygon(f, front[0]);
2186                 SubdividePolygon(b, back[0]);
2187                 return;
2188         }
2189
2190         i1 = subdivpolylookupvert(verts);
2191         i2 = subdivpolylookupvert(verts + 3);
2192         for (i = 2;i < numverts;i++)
2193         {
2194                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2195                 {
2196                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2197                         return;
2198                 }
2199
2200                 i3 = subdivpolylookupvert(verts + i * 3);
2201                 subdivpolyindex[subdivpolytriangles][0] = i1;
2202                 subdivpolyindex[subdivpolytriangles][1] = i2;
2203                 subdivpolyindex[subdivpolytriangles][2] = i3;
2204                 i2 = i3;
2205                 subdivpolytriangles++;
2206         }
2207 }
2208
2209 //Breaks a polygon up along axial 64 unit
2210 //boundaries so that turbulent and sky warps
2211 //can be done reasonably.
2212 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2213 {
2214         int i, j;
2215         surfvertex_t *v;
2216         surfmesh_t *mesh;
2217
2218         subdivpolytriangles = 0;
2219         subdivpolyverts = 0;
2220         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2221         if (subdivpolytriangles < 1)
2222                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2223
2224         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2225         mesh->num_vertices = subdivpolyverts;
2226         mesh->num_triangles = subdivpolytriangles;
2227         mesh->vertex = (surfvertex_t *)(mesh + 1);
2228         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2229         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2230
2231         for (i = 0;i < mesh->num_triangles;i++)
2232                 for (j = 0;j < 3;j++)
2233                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2234
2235         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2236         {
2237                 VectorCopy(subdivpolyvert[i], v->v);
2238                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2239                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2240         }
2241 }
2242 #endif
2243
2244 extern cvar_t gl_max_lightmapsize;
2245 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2246 {
2247         dface_t *in;
2248         msurface_t *surface;
2249         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2250         float texmins[2], texmaxs[2], val;
2251         rtexture_t *lightmaptexture, *deluxemaptexture;
2252
2253         in = (dface_t *)(mod_base + l->fileofs);
2254         if (l->filelen % sizeof(*in))
2255                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2256         count = l->filelen / sizeof(*in);
2257         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2258         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2259
2260         loadmodel->num_surfaces = count;
2261
2262         loadmodel->brushq1.firstrender = true;
2263         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2264
2265         totalverts = 0;
2266         totaltris = 0;
2267         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2268         {
2269                 numedges = (unsigned short)LittleShort(in->numedges);
2270                 totalverts += numedges;
2271                 totaltris += numedges - 2;
2272         }
2273
2274         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2275
2276         lightmaptexture = NULL;
2277         deluxemaptexture = r_texture_blanknormalmap;
2278         lightmapnumber = 0;
2279         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2280         totallightmapsamples = 0;
2281
2282         totalverts = 0;
2283         totaltris = 0;
2284         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2285         {
2286                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2287
2288                 // FIXME: validate edges, texinfo, etc?
2289                 firstedge = LittleLong(in->firstedge);
2290                 numedges = (unsigned short)LittleShort(in->numedges);
2291                 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)
2292                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2293                 i = (unsigned short)LittleShort(in->texinfo);
2294                 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2295                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2296                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2297                 surface->texture = surface->lightmapinfo->texinfo->texture;
2298
2299                 planenum = (unsigned short)LittleShort(in->planenum);
2300                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2301                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2302
2303                 //surface->flags = surface->texture->flags;
2304                 //if (LittleShort(in->side))
2305                 //      surface->flags |= SURF_PLANEBACK;
2306                 //surface->plane = loadmodel->brush.data_planes + planenum;
2307
2308                 surface->num_firstvertex = totalverts;
2309                 surface->num_vertices = numedges;
2310                 surface->num_firsttriangle = totaltris;
2311                 surface->num_triangles = numedges - 2;
2312                 totalverts += numedges;
2313                 totaltris += numedges - 2;
2314
2315                 // convert edges back to a normal polygon
2316                 for (i = 0;i < surface->num_vertices;i++)
2317                 {
2318                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2319                         float s, t;
2320                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2321                         if (lindex >= 0)
2322                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2323                         else
2324                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2325                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2326                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2327                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2328                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2329                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2330                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2331                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2332                 }
2333
2334                 for (i = 0;i < surface->num_triangles;i++)
2335                 {
2336                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2337                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2338                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2339                 }
2340
2341                 // compile additional data about the surface geometry
2342                 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_normal3f, true);
2343                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, true);
2344                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2345
2346                 // generate surface extents information
2347                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2348                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2349                 for (i = 1;i < surface->num_vertices;i++)
2350                 {
2351                         for (j = 0;j < 2;j++)
2352                         {
2353                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2354                                 texmins[j] = min(texmins[j], val);
2355                                 texmaxs[j] = max(texmaxs[j], val);
2356                         }
2357                 }
2358                 for (i = 0;i < 2;i++)
2359                 {
2360                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2361                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2362                 }
2363
2364                 smax = surface->lightmapinfo->extents[0] >> 4;
2365                 tmax = surface->lightmapinfo->extents[1] >> 4;
2366                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2367                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2368
2369                 // lighting info
2370                 for (i = 0;i < MAXLIGHTMAPS;i++)
2371                         surface->lightmapinfo->styles[i] = in->styles[i];
2372                 surface->lightmaptexture = NULL;
2373                 surface->deluxemaptexture = r_texture_blanknormalmap;
2374                 i = LittleLong(in->lightofs);
2375                 if (i == -1)
2376                 {
2377                         surface->lightmapinfo->samples = NULL;
2378 #if 1
2379                         // give non-lightmapped water a 1x white lightmap
2380                         if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2381                         {
2382                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2383                                 surface->lightmapinfo->styles[0] = 0;
2384                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2385                         }
2386 #endif
2387                 }
2388                 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2389                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2390                 else // LordHavoc: white lighting (bsp version 29)
2391                 {
2392                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2393                         if (loadmodel->brushq1.nmaplightdata)
2394                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2395                 }
2396
2397                 // check if we should apply a lightmap to this
2398                 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2399                 {
2400                         if (ssize > 256 || tsize > 256)
2401                                 Host_Error("Bad surface extents");
2402
2403                         if (lightmapsize < ssize)
2404                                 lightmapsize = ssize;
2405                         if (lightmapsize < tsize)
2406                                 lightmapsize = tsize;
2407
2408                         totallightmapsamples += ssize*tsize;
2409
2410                         // force lightmap upload on first time seeing the surface
2411                         //
2412                         // additionally this is used by the later code to see if a
2413                         // lightmap is needed on this surface (rather than duplicating the
2414                         // logic above)
2415                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2416                 }
2417         }
2418
2419         // small maps (such as ammo boxes especially) don't need big lightmap
2420         // textures, so this code tries to guess a good size based on
2421         // totallightmapsamples (size of the lightmaps lump basically), as well as
2422         // trying to max out the size if there is a lot of lightmap data to store
2423         // additionally, never choose a lightmapsize that is smaller than the
2424         // largest surface encountered (as it would fail)
2425         i = lightmapsize;
2426         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2427                 ;
2428
2429         // now that we've decided the lightmap texture size, we can do the rest
2430         if (cls.state != ca_dedicated)
2431         {
2432                 int stainmapsize = 0;
2433                 mod_alloclightmap_state_t allocState;
2434
2435                 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2436                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2437                 {
2438                         int i, iu, iv, lightmapx = 0, lightmapy = 0;
2439                         float u, v, ubase, vbase, uscale, vscale;
2440
2441                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2442                                 continue;
2443
2444                         smax = surface->lightmapinfo->extents[0] >> 4;
2445                         tmax = surface->lightmapinfo->extents[1] >> 4;
2446                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2447                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2448                         stainmapsize += ssize * tsize * 3;
2449
2450                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2451                         {
2452                                 // allocate a texture pool if we need it
2453                                 if (loadmodel->texturepool == NULL)
2454                                         loadmodel->texturepool = R_AllocTexturePool();
2455                                 // could not find room, make a new lightmap
2456                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2457                                 loadmodel->brushq3.data_lightmaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2458                                 loadmodel->brushq3.data_deluxemaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2459                                 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2460                                 if (loadmodel->brushq1.nmaplightdata)
2461                                         loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2462                                 lightmapnumber++;
2463                                 Mod_AllocLightmap_Reset(&allocState);
2464                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2465                         }
2466                         surface->lightmaptexture = lightmaptexture;
2467                         surface->deluxemaptexture = deluxemaptexture;
2468                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2469                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2470
2471                         uscale = 1.0f / (float)lightmapsize;
2472                         vscale = 1.0f / (float)lightmapsize;
2473                         ubase = lightmapx * uscale;
2474                         vbase = lightmapy * vscale;
2475
2476                         for (i = 0;i < surface->num_vertices;i++)
2477                         {
2478                                 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);
2479                                 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);
2480                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2481                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2482                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2483                                 iu = (int) u;
2484                                 iv = (int) v;
2485                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2486                         }
2487                 }
2488
2489                 if (cl_stainmaps.integer)
2490                 {
2491                         // allocate stainmaps for permanent marks on walls and clear white
2492                         unsigned char *stainsamples = NULL;
2493                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2494                         memset(stainsamples, 255, stainmapsize);
2495                         // assign pointers
2496                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2497                         {
2498                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2499                                         continue;
2500                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2501                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2502                                 surface->lightmapinfo->stainsamples = stainsamples;
2503                                 stainsamples += ssize * tsize * 3;
2504                         }
2505                 }
2506         }
2507
2508         // generate ushort elements array if possible
2509         if (loadmodel->surfmesh.data_element3s)
2510                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2511                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2512 }
2513
2514 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2515 {
2516         //if (node->parent)
2517         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2518         node->parent = parent;
2519         if (node->plane)
2520         {
2521                 // this is a node, recurse to children
2522                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2523                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2524                 // combine supercontents of children
2525                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2526         }
2527         else
2528         {
2529                 int j;
2530                 mleaf_t *leaf = (mleaf_t *)node;
2531                 // if this is a leaf, calculate supercontents mask from all collidable
2532                 // primitives in the leaf (brushes and collision surfaces)
2533                 // also flag if the leaf contains any collision surfaces
2534                 leaf->combinedsupercontents = 0;
2535                 // combine the supercontents values of all brushes in this leaf
2536                 for (j = 0;j < leaf->numleafbrushes;j++)
2537                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2538                 // check if this leaf contains any collision surfaces (q3 patches)
2539                 for (j = 0;j < leaf->numleafsurfaces;j++)
2540                 {
2541                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2542                         if (surface->num_collisiontriangles)
2543                         {
2544                                 leaf->containscollisionsurfaces = true;
2545                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2546                         }
2547                 }
2548         }
2549 }
2550
2551 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2552 {
2553         int                     i, j, count, p;
2554         dnode_t         *in;
2555         mnode_t         *out;
2556
2557         in = (dnode_t *)(mod_base + l->fileofs);
2558         if (l->filelen % sizeof(*in))
2559                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2560         count = l->filelen / sizeof(*in);
2561         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2562
2563         loadmodel->brush.data_nodes = out;
2564         loadmodel->brush.num_nodes = count;
2565
2566         for ( i=0 ; i<count ; i++, in++, out++)
2567         {
2568                 for (j=0 ; j<3 ; j++)
2569                 {
2570                         out->mins[j] = LittleShort(in->mins[j]);
2571                         out->maxs[j] = LittleShort(in->maxs[j]);
2572                 }
2573
2574                 p = LittleLong(in->planenum);
2575                 out->plane = loadmodel->brush.data_planes + p;
2576
2577                 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2578                 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2579
2580                 for (j=0 ; j<2 ; j++)
2581                 {
2582                         // LordHavoc: this code supports broken bsp files produced by
2583                         // arguire qbsp which can produce more than 32768 nodes, any value
2584                         // below count is assumed to be a node number, any other value is
2585                         // assumed to be a leaf number
2586                         p = (unsigned short)LittleShort(in->children[j]);
2587                         if (p < count)
2588                         {
2589                                 if (p < loadmodel->brush.num_nodes)
2590                                         out->children[j] = loadmodel->brush.data_nodes + p;
2591                                 else
2592                                 {
2593                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2594                                         // map it to the solid leaf
2595                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2596                                 }
2597                         }
2598                         else
2599                         {
2600                                 // note this uses 65535 intentionally, -1 is leaf 0
2601                                 p = 65535 - p;
2602                                 if (p < loadmodel->brush.num_leafs)
2603                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2604                                 else
2605                                 {
2606                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2607                                         // map it to the solid leaf
2608                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2609                                 }
2610                         }
2611                 }
2612         }
2613
2614         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2615 }
2616
2617 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2618 {
2619         dleaf_t *in;
2620         mleaf_t *out;
2621         int i, j, count, p;
2622
2623         in = (dleaf_t *)(mod_base + l->fileofs);
2624         if (l->filelen % sizeof(*in))
2625                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2626         count = l->filelen / sizeof(*in);
2627         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2628
2629         loadmodel->brush.data_leafs = out;
2630         loadmodel->brush.num_leafs = count;
2631         // get visleafs from the submodel data
2632         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2633         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2634         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2635         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2636
2637         for ( i=0 ; i<count ; i++, in++, out++)
2638         {
2639                 for (j=0 ; j<3 ; j++)
2640                 {
2641                         out->mins[j] = LittleShort(in->mins[j]);
2642                         out->maxs[j] = LittleShort(in->maxs[j]);
2643                 }
2644
2645                 // FIXME: this function could really benefit from some error checking
2646
2647                 out->contents = LittleLong(in->contents);
2648
2649                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2650                 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2651                 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2652                 {
2653                         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);
2654                         out->firstleafsurface = NULL;
2655                         out->numleafsurfaces = 0;
2656                 }
2657
2658                 out->clusterindex = i - 1;
2659                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2660                         out->clusterindex = -1;
2661
2662                 p = LittleLong(in->visofs);
2663                 // ignore visofs errors on leaf 0 (solid)
2664                 if (p >= 0 && out->clusterindex >= 0)
2665                 {
2666                         if (p >= loadmodel->brushq1.num_compressedpvs)
2667                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2668                         else
2669                                 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);
2670                 }
2671
2672                 for (j = 0;j < 4;j++)
2673                         out->ambient_sound_level[j] = in->ambient_level[j];
2674
2675                 // FIXME: Insert caustics here
2676         }
2677 }
2678
2679 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2680 {
2681         int i, j;
2682         mleaf_t *leaf;
2683         const unsigned char *pvs;
2684         // if there's no vis data, assume supported (because everything is visible all the time)
2685         if (!loadmodel->brush.data_pvsclusters)
2686                 return true;
2687         // check all liquid leafs to see if they can see into empty leafs, if any
2688         // can we can assume this map supports r_wateralpha
2689         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2690         {
2691                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2692                 {
2693                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2694                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
2695                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2696                                         return true;
2697                 }
2698         }
2699         return false;
2700 }
2701
2702 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2703 {
2704         dclipnode_t *in;
2705         mclipnode_t *out;
2706         int                     i, count;
2707         hull_t          *hull;
2708
2709         in = (dclipnode_t *)(mod_base + l->fileofs);
2710         if (l->filelen % sizeof(*in))
2711                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2712         count = l->filelen / sizeof(*in);
2713         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2714
2715         loadmodel->brushq1.clipnodes = out;
2716         loadmodel->brushq1.numclipnodes = count;
2717
2718         for (i = 1; i < MAX_MAP_HULLS; i++)
2719         {
2720                 hull = &loadmodel->brushq1.hulls[i];
2721                 hull->clipnodes = out;
2722                 hull->firstclipnode = 0;
2723                 hull->lastclipnode = count-1;
2724                 hull->planes = loadmodel->brush.data_planes;
2725                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2726                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2727                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2728                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2729                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2730                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2731                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2732         }
2733
2734         for (i=0 ; i<count ; i++, out++, in++)
2735         {
2736                 out->planenum = LittleLong(in->planenum);
2737                 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2738                 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2739                 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2740                 if (out->children[0] >= count)
2741                         out->children[0] -= 65536;
2742                 if (out->children[1] >= count)
2743                         out->children[1] -= 65536;
2744                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2745                         Host_Error("Corrupt clipping hull(out of range planenum)");
2746         }
2747 }
2748
2749 //Duplicate the drawing hull structure as a clipping hull
2750 static void Mod_Q1BSP_MakeHull0(void)
2751 {
2752         mnode_t         *in;
2753         mclipnode_t *out;
2754         int                     i;
2755         hull_t          *hull;
2756
2757         hull = &loadmodel->brushq1.hulls[0];
2758
2759         in = loadmodel->brush.data_nodes;
2760         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2761
2762         hull->clipnodes = out;
2763         hull->firstclipnode = 0;
2764         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2765         hull->planes = loadmodel->brush.data_planes;
2766
2767         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2768         {
2769                 out->planenum = in->plane - loadmodel->brush.data_planes;
2770                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2771                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2772         }
2773 }
2774
2775 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2776 {
2777         int i, j;
2778         short *in;
2779
2780         in = (short *)(mod_base + l->fileofs);
2781         if (l->filelen % sizeof(*in))
2782                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2783         loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2784         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2785
2786         for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2787         {
2788                 j = (unsigned short) LittleShort(in[i]);
2789                 if (j >= loadmodel->num_surfaces)
2790                         Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2791                 loadmodel->brush.data_leafsurfaces[i] = j;
2792         }
2793 }
2794
2795 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2796 {
2797         int             i;
2798         int             *in;
2799
2800         in = (int *)(mod_base + l->fileofs);
2801         if (l->filelen % sizeof(*in))
2802                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2803         loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2804         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2805
2806         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2807                 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2808 }
2809
2810
2811 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2812 {
2813         int                     i;
2814         mplane_t        *out;
2815         dplane_t        *in;
2816
2817         in = (dplane_t *)(mod_base + l->fileofs);
2818         if (l->filelen % sizeof(*in))
2819                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2820
2821         loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2822         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2823
2824         for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2825         {
2826                 out->normal[0] = LittleFloat(in->normal[0]);
2827                 out->normal[1] = LittleFloat(in->normal[1]);
2828                 out->normal[2] = LittleFloat(in->normal[2]);
2829                 out->dist = LittleFloat(in->dist);
2830
2831                 PlaneClassify(out);
2832         }
2833 }
2834
2835 static void Mod_Q1BSP_LoadMapBrushes(void)
2836 {
2837 #if 0
2838 // unfinished
2839         int submodel, numbrushes;
2840         qboolean firstbrush;
2841         char *text, *maptext;
2842         char mapfilename[MAX_QPATH];
2843         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2844         strlcat (mapfilename, ".map", sizeof (mapfilename));
2845         maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
2846         if (!maptext)
2847                 return;
2848         text = maptext;
2849         if (!COM_ParseToken_Simple(&data, false, false))
2850                 return; // error
2851         submodel = 0;
2852         for (;;)
2853         {
2854                 if (!COM_ParseToken_Simple(&data, false, false))
2855                         break;
2856                 if (com_token[0] != '{')
2857                         return; // error
2858                 // entity
2859                 firstbrush = true;
2860                 numbrushes = 0;
2861                 maxbrushes = 256;
2862                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2863                 for (;;)
2864                 {
2865                         if (!COM_ParseToken_Simple(&data, false, false))
2866                                 return; // error
2867                         if (com_token[0] == '}')
2868                                 break; // end of entity
2869                         if (com_token[0] == '{')
2870                         {
2871                                 // brush
2872                                 if (firstbrush)
2873                                 {
2874                                         if (submodel)
2875                                         {
2876                                                 if (submodel > loadmodel->brush.numsubmodels)
2877                                                 {
2878                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2879                                                         model = NULL;
2880                                                 }
2881                                                 else
2882                                                         model = loadmodel->brush.submodels[submodel];
2883                                         }
2884                                         else
2885                                                 model = loadmodel;
2886                                 }
2887                                 for (;;)
2888                                 {
2889                                         if (!COM_ParseToken_Simple(&data, false, false))
2890                                                 return; // error
2891                                         if (com_token[0] == '}')
2892                                                 break; // end of brush
2893                                         // each brush face should be this format:
2894                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2895                                         // FIXME: support hl .map format
2896                                         for (pointnum = 0;pointnum < 3;pointnum++)
2897                                         {
2898                                                 COM_ParseToken_Simple(&data, false, false);
2899                                                 for (componentnum = 0;componentnum < 3;componentnum++)
2900                                                 {
2901                                                         COM_ParseToken_Simple(&data, false, false);
2902                                                         point[pointnum][componentnum] = atof(com_token);
2903                                                 }
2904                                                 COM_ParseToken_Simple(&data, false, false);
2905                                         }
2906                                         COM_ParseToken_Simple(&data, false, false);
2907                                         strlcpy(facetexture, com_token, sizeof(facetexture));
2908                                         COM_ParseToken_Simple(&data, false, false);
2909                                         //scroll_s = atof(com_token);
2910                                         COM_ParseToken_Simple(&data, false, false);
2911                                         //scroll_t = atof(com_token);
2912                                         COM_ParseToken_Simple(&data, false, false);
2913                                         //rotate = atof(com_token);
2914                                         COM_ParseToken_Simple(&data, false, false);
2915                                         //scale_s = atof(com_token);
2916                                         COM_ParseToken_Simple(&data, false, false);
2917                                         //scale_t = atof(com_token);
2918                                         TriangleNormal(point[0], point[1], point[2], planenormal);
2919