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