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