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