2129d75fd03cdc0473f876cf2d8a2a2633994558
[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         Mod_Q1BSP_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, vid.sRGB3D);
1582         loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
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 zeroopaque[4], zerotrans[4];
1599         Vector4Set(zeroopaque, 0, 0, 0, 255);
1600         Vector4Set(zerotrans, 0, 0, 0, 128);
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, false, NULL);
1774                                 if (!data)
1775                                         data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, false, 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, true);
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                                         tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1826                                         tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1827                                 }
1828                                 else if (!strncmp(tx->name,"*lava",5)
1829                                  || !strncmp(tx->name,"*teleport",9)
1830                                  || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1831                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1832                                 else
1833                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1834                                 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1835                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1836                         }
1837                         else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1838                         {
1839                                 // replace the texture with black
1840                                 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1841                                 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1842                         }
1843                         else if (!strncmp(tx->name, "sky", 3))
1844                                 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1845                         else if (!strcmp(tx->name, "caulk"))
1846                                 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1847                         else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1848                                 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1849
1850                         // start out with no animation
1851                         tx->currentframe = tx;
1852                         tx->currentskinframe = tx->skinframes[0];
1853                 }
1854         }
1855
1856         // sequence the animations
1857         for (i = 0;i < m->nummiptex;i++)
1858         {
1859                 tx = loadmodel->data_textures + i;
1860                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1861                         continue;
1862                 if (tx->anim_total[0] || tx->anim_total[1])
1863                         continue;       // already sequenced
1864
1865                 // find the number of frames in the animation
1866                 memset(anims, 0, sizeof(anims));
1867                 memset(altanims, 0, sizeof(altanims));
1868
1869                 for (j = i;j < m->nummiptex;j++)
1870                 {
1871                         tx2 = loadmodel->data_textures + j;
1872                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1873                                 continue;
1874
1875                         num = tx2->name[1];
1876                         if (num >= '0' && num <= '9')
1877                                 anims[num - '0'] = tx2;
1878                         else if (num >= 'a' && num <= 'j')
1879                                 altanims[num - 'a'] = tx2;
1880                         else
1881                                 Con_Printf("Bad animating texture %s\n", tx->name);
1882                 }
1883
1884                 max = altmax = 0;
1885                 for (j = 0;j < 10;j++)
1886                 {
1887                         if (anims[j])
1888                                 max = j + 1;
1889                         if (altanims[j])
1890                                 altmax = j + 1;
1891                 }
1892                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1893
1894                 incomplete = false;
1895                 for (j = 0;j < max;j++)
1896                 {
1897                         if (!anims[j])
1898                         {
1899                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1900                                 incomplete = true;
1901                         }
1902                 }
1903                 for (j = 0;j < altmax;j++)
1904                 {
1905                         if (!altanims[j])
1906                         {
1907                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1908                                 incomplete = true;
1909                         }
1910                 }
1911                 if (incomplete)
1912                         continue;
1913
1914                 if (altmax < 1)
1915                 {
1916                         // if there is no alternate animation, duplicate the primary
1917                         // animation into the alternate
1918                         altmax = max;
1919                         for (k = 0;k < 10;k++)
1920                                 altanims[k] = anims[k];
1921                 }
1922
1923                 // link together the primary animation
1924                 for (j = 0;j < max;j++)
1925                 {
1926                         tx2 = anims[j];
1927                         tx2->animated = true;
1928                         tx2->anim_total[0] = max;
1929                         tx2->anim_total[1] = altmax;
1930                         for (k = 0;k < 10;k++)
1931                         {
1932                                 tx2->anim_frames[0][k] = anims[k];
1933                                 tx2->anim_frames[1][k] = altanims[k];
1934                         }
1935                 }
1936
1937                 // if there really is an alternate anim...
1938                 if (anims[0] != altanims[0])
1939                 {
1940                         // link together the alternate animation
1941                         for (j = 0;j < altmax;j++)
1942                         {
1943                                 tx2 = altanims[j];
1944                                 tx2->animated = true;
1945                                 // the primary/alternate are reversed here
1946                                 tx2->anim_total[0] = altmax;
1947                                 tx2->anim_total[1] = max;
1948                                 for (k = 0;k < 10;k++)
1949                                 {
1950                                         tx2->anim_frames[0][k] = altanims[k];
1951                                         tx2->anim_frames[1][k] = anims[k];
1952                                 }
1953                         }
1954                 }
1955         }
1956 }
1957
1958 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1959 {
1960         int i;
1961         unsigned char *in, *out, *data, d;
1962         char litfilename[MAX_QPATH];
1963         char dlitfilename[MAX_QPATH];
1964         fs_offset_t filesize;
1965         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1966         {
1967                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1968                 for (i=0; i<l->filelen; i++)
1969                         loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1970         }
1971         else // LordHavoc: bsp version 29 (normal white lighting)
1972         {
1973                 // LordHavoc: hope is not lost yet, check for a .lit file to load
1974                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1975                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1976                 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1977                 strlcat (litfilename, ".lit", sizeof (litfilename));
1978                 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1979                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1980                 if (data)
1981                 {
1982                         if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1983                         {
1984                                 i = LittleLong(((int *)data)[1]);
1985                                 if (i == 1)
1986                                 {
1987                                         if (developer_loading.integer)
1988                                                 Con_Printf("loaded %s\n", litfilename);
1989                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1990                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1991                                         Mem_Free(data);
1992                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1993                                         if (data)
1994                                         {
1995                                                 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1996                                                 {
1997                                                         i = LittleLong(((int *)data)[1]);
1998                                                         if (i == 1)
1999                                                         {
2000                                                                 if (developer_loading.integer)
2001                                                                         Con_Printf("loaded %s\n", dlitfilename);
2002                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2003                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2004                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
2005                                                                 loadmodel->brushq3.deluxemapping = true;
2006                                                         }
2007                                                 }
2008                                                 Mem_Free(data);
2009                                                 data = NULL;
2010                                         }
2011                                         return;
2012                                 }
2013                                 else
2014                                         Con_Printf("Unknown .lit file version (%d)\n", i);
2015                         }
2016                         else if (filesize == 8)
2017                                 Con_Print("Empty .lit file, ignoring\n");
2018                         else
2019                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
2020                         if (data)
2021                         {
2022                                 Mem_Free(data);
2023                                 data = NULL;
2024                         }
2025                 }
2026                 // LordHavoc: oh well, expand the white lighting data
2027                 if (!l->filelen)
2028                         return;
2029                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
2030                 in = mod_base + l->fileofs;
2031                 out = loadmodel->brushq1.lightdata;
2032                 for (i = 0;i < l->filelen;i++)
2033                 {
2034                         d = *in++;
2035                         *out++ = d;
2036                         *out++ = d;
2037                         *out++ = d;
2038                 }
2039         }
2040 }
2041
2042 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
2043 {
2044         loadmodel->brushq1.num_compressedpvs = 0;
2045         loadmodel->brushq1.data_compressedpvs = NULL;
2046         if (!l->filelen)
2047                 return;
2048         loadmodel->brushq1.num_compressedpvs = l->filelen;
2049         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
2050         memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
2051 }
2052
2053 // used only for HalfLife maps
2054 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2055 {
2056         char key[128], value[4096];
2057         int i, j, k;
2058         if (!data)
2059                 return;
2060         if (!COM_ParseToken_Simple(&data, false, false))
2061                 return; // error
2062         if (com_token[0] != '{')
2063                 return; // error
2064         while (1)
2065         {
2066                 if (!COM_ParseToken_Simple(&data, false, false))
2067                         return; // error
2068                 if (com_token[0] == '}')
2069                         break; // end of worldspawn
2070                 if (com_token[0] == '_')
2071                         strlcpy(key, com_token + 1, sizeof(key));
2072                 else
2073                         strlcpy(key, com_token, sizeof(key));
2074                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2075                         key[strlen(key)-1] = 0;
2076                 if (!COM_ParseToken_Simple(&data, false, false))
2077                         return; // error
2078                 dpsnprintf(value, sizeof(value), "%s", com_token);
2079                 if (!strcmp("wad", key)) // for HalfLife maps
2080                 {
2081                         if (loadmodel->brush.ishlbsp)
2082                         {
2083                                 j = 0;
2084                                 for (i = 0;i < (int)sizeof(value);i++)
2085                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2086                                                 break;
2087                                 if (value[i])
2088                                 {
2089                                         for (;i < (int)sizeof(value);i++)
2090                                         {
2091                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2092                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2093                                                         j = i+1;
2094                                                 else if (value[i] == ';' || value[i] == 0)
2095                                                 {
2096                                                         k = value[i];
2097                                                         value[i] = 0;
2098                                                         W_LoadTextureWadFile(&value[j], false);
2099                                                         j = i+1;
2100                                                         if (!k)
2101                                                                 break;
2102                                                 }
2103                                         }
2104                                 }
2105                         }
2106                 }
2107         }
2108 }
2109
2110 static void Mod_Q1BSP_LoadEntities(lump_t *l)
2111 {
2112         loadmodel->brush.entities = NULL;
2113         if (!l->filelen)
2114                 return;
2115         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
2116         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
2117         loadmodel->brush.entities[l->filelen] = 0;
2118         if (loadmodel->brush.ishlbsp)
2119                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2120 }
2121
2122
2123 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
2124 {
2125         dvertex_t       *in;
2126         mvertex_t       *out;
2127         int                     i, count;
2128
2129         in = (dvertex_t *)(mod_base + l->fileofs);
2130         if (l->filelen % sizeof(*in))
2131                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2132         count = l->filelen / sizeof(*in);
2133         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2134
2135         loadmodel->brushq1.vertexes = out;
2136         loadmodel->brushq1.numvertexes = count;
2137
2138         for ( i=0 ; i<count ; i++, in++, out++)
2139         {
2140                 out->position[0] = LittleFloat(in->point[0]);
2141                 out->position[1] = LittleFloat(in->point[1]);
2142                 out->position[2] = LittleFloat(in->point[2]);
2143         }
2144 }
2145
2146 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
2147 // can be used for this
2148 // REMOVEME
2149 int SB_ReadInt (unsigned char **buffer)
2150 {
2151         int     i;
2152         i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
2153         (*buffer) += 4;
2154         return i;
2155 }
2156
2157 // REMOVEME
2158 float SB_ReadFloat (unsigned char **buffer)
2159 {
2160         union
2161         {
2162                 int             i;
2163                 float   f;
2164         } u;
2165
2166         u.i = SB_ReadInt (buffer);
2167         return u.f;
2168 }
2169
2170 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
2171 {
2172         unsigned char           *index;
2173         dmodel_t        *out;
2174         int                     i, j, count;
2175
2176         index = (unsigned char *)(mod_base + l->fileofs);
2177         if (l->filelen % (48+4*hullinfo->filehulls))
2178                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2179
2180         count = l->filelen / (48+4*hullinfo->filehulls);
2181         out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2182
2183         loadmodel->brushq1.submodels = out;
2184         loadmodel->brush.numsubmodels = count;
2185
2186         for (i = 0; i < count; i++, out++)
2187         {
2188         // spread out the mins / maxs by a pixel
2189                 out->mins[0] = SB_ReadFloat (&index) - 1;
2190                 out->mins[1] = SB_ReadFloat (&index) - 1;
2191                 out->mins[2] = SB_ReadFloat (&index) - 1;
2192                 out->maxs[0] = SB_ReadFloat (&index) + 1;
2193                 out->maxs[1] = SB_ReadFloat (&index) + 1;
2194                 out->maxs[2] = SB_ReadFloat (&index) + 1;
2195                 out->origin[0] = SB_ReadFloat (&index);
2196                 out->origin[1] = SB_ReadFloat (&index);
2197                 out->origin[2] = SB_ReadFloat (&index);
2198                 for (j = 0; j < hullinfo->filehulls; j++)
2199                         out->headnode[j] = SB_ReadInt (&index);
2200                 out->visleafs = SB_ReadInt (&index);
2201                 out->firstface = SB_ReadInt (&index);
2202                 out->numfaces = SB_ReadInt (&index);
2203         }
2204 }
2205
2206 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2207 {
2208         dedge_t *in;
2209         medge_t *out;
2210         int     i, count;
2211
2212         in = (dedge_t *)(mod_base + l->fileofs);
2213         if (l->filelen % sizeof(*in))
2214                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2215         count = l->filelen / sizeof(*in);
2216         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2217
2218         loadmodel->brushq1.edges = out;
2219         loadmodel->brushq1.numedges = count;
2220
2221         for ( i=0 ; i<count ; i++, in++, out++)
2222         {
2223                 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2224                 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2225                 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2226                 {
2227                         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);
2228                         if(!loadmodel->brushq1.numvertexes)
2229                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2230                                 
2231                         out->v[0] = 0;
2232                         out->v[1] = 0;
2233                 }
2234         }
2235 }
2236
2237 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2238 {
2239         texinfo_t *in;
2240         mtexinfo_t *out;
2241         int i, j, k, count, miptex;
2242
2243         in = (texinfo_t *)(mod_base + l->fileofs);
2244         if (l->filelen % sizeof(*in))
2245                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2246         count = l->filelen / sizeof(*in);
2247         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2248
2249         loadmodel->brushq1.texinfo = out;
2250         loadmodel->brushq1.numtexinfo = count;
2251
2252         for (i = 0;i < count;i++, in++, out++)
2253         {
2254                 for (k = 0;k < 2;k++)
2255                         for (j = 0;j < 4;j++)
2256                                 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2257
2258                 miptex = LittleLong(in->miptex);
2259                 out->flags = LittleLong(in->flags);
2260
2261                 out->texture = NULL;
2262                 if (loadmodel->data_textures)
2263                 {
2264                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2265                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2266                         else
2267                                 out->texture = loadmodel->data_textures + miptex;
2268                 }
2269                 if (out->flags & TEX_SPECIAL)
2270                 {
2271                         // if texture chosen is NULL or the shader needs a lightmap,
2272                         // force to notexture water shader
2273                         if (out->texture == NULL)
2274                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2275                 }
2276                 else
2277                 {
2278                         // if texture chosen is NULL, force to notexture
2279                         if (out->texture == NULL)
2280                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2281                 }
2282         }
2283 }
2284
2285 #if 0
2286 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2287 {
2288         int             i, j;
2289         float   *v;
2290
2291         mins[0] = mins[1] = mins[2] = 9999;
2292         maxs[0] = maxs[1] = maxs[2] = -9999;
2293         v = verts;
2294         for (i = 0;i < numverts;i++)
2295         {
2296                 for (j = 0;j < 3;j++, v++)
2297                 {
2298                         if (*v < mins[j])
2299                                 mins[j] = *v;
2300                         if (*v > maxs[j])
2301                                 maxs[j] = *v;
2302                 }
2303         }
2304 }
2305
2306 #define MAX_SUBDIVPOLYTRIANGLES 4096
2307 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2308
2309 static int subdivpolyverts, subdivpolytriangles;
2310 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2311 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2312
2313 static int subdivpolylookupvert(vec3_t v)
2314 {
2315         int i;
2316         for (i = 0;i < subdivpolyverts;i++)
2317                 if (subdivpolyvert[i][0] == v[0]
2318                  && subdivpolyvert[i][1] == v[1]
2319                  && subdivpolyvert[i][2] == v[2])
2320                         return i;
2321         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2322                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2323         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2324         return subdivpolyverts++;
2325 }
2326
2327 static void SubdividePolygon(int numverts, float *verts)
2328 {
2329         int             i, i1, i2, i3, f, b, c, p;
2330         vec3_t  mins, maxs, front[256], back[256];
2331         float   m, *pv, *cv, dist[256], frac;
2332
2333         if (numverts > 250)
2334                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2335
2336         BoundPoly(numverts, verts, mins, maxs);
2337
2338         for (i = 0;i < 3;i++)
2339         {
2340                 m = (mins[i] + maxs[i]) * 0.5;
2341                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2342                 if (maxs[i] - m < 8)
2343                         continue;
2344                 if (m - mins[i] < 8)
2345                         continue;
2346
2347                 // cut it
2348                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2349                         dist[c] = cv[i] - m;
2350
2351                 f = b = 0;
2352                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2353                 {
2354                         if (dist[p] >= 0)
2355                         {
2356                                 VectorCopy(pv, front[f]);
2357                                 f++;
2358                         }
2359                         if (dist[p] <= 0)
2360                         {
2361                                 VectorCopy(pv, back[b]);
2362                                 b++;
2363                         }
2364                         if (dist[p] == 0 || dist[c] == 0)
2365                                 continue;
2366                         if ((dist[p] > 0) != (dist[c] > 0) )
2367                         {
2368                                 // clip point
2369                                 frac = dist[p] / (dist[p] - dist[c]);
2370                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2371                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2372                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2373                                 f++;
2374                                 b++;
2375                         }
2376                 }
2377
2378                 SubdividePolygon(f, front[0]);
2379                 SubdividePolygon(b, back[0]);
2380                 return;
2381         }
2382
2383         i1 = subdivpolylookupvert(verts);
2384         i2 = subdivpolylookupvert(verts + 3);
2385         for (i = 2;i < numverts;i++)
2386         {
2387                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2388                 {
2389                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2390                         return;
2391                 }
2392
2393                 i3 = subdivpolylookupvert(verts + i * 3);
2394                 subdivpolyindex[subdivpolytriangles][0] = i1;
2395                 subdivpolyindex[subdivpolytriangles][1] = i2;
2396                 subdivpolyindex[subdivpolytriangles][2] = i3;
2397                 i2 = i3;
2398                 subdivpolytriangles++;
2399         }
2400 }
2401
2402 //Breaks a polygon up along axial 64 unit
2403 //boundaries so that turbulent and sky warps
2404 //can be done reasonably.
2405 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2406 {
2407         int i, j;
2408         surfvertex_t *v;
2409         surfmesh_t *mesh;
2410
2411         subdivpolytriangles = 0;
2412         subdivpolyverts = 0;
2413         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2414         if (subdivpolytriangles < 1)
2415                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2416
2417         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2418         mesh->num_vertices = subdivpolyverts;
2419         mesh->num_triangles = subdivpolytriangles;
2420         mesh->vertex = (surfvertex_t *)(mesh + 1);
2421         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2422         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2423
2424         for (i = 0;i < mesh->num_triangles;i++)
2425                 for (j = 0;j < 3;j++)
2426                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2427
2428         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2429         {
2430                 VectorCopy(subdivpolyvert[i], v->v);
2431                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2432                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2433         }
2434 }
2435 #endif
2436
2437 extern cvar_t gl_max_lightmapsize;
2438 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2439 {
2440         dface_t *in;
2441         msurface_t *surface;
2442         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2443         float texmins[2], texmaxs[2], val;
2444         rtexture_t *lightmaptexture, *deluxemaptexture;
2445
2446         in = (dface_t *)(mod_base + l->fileofs);
2447         if (l->filelen % sizeof(*in))
2448                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2449         count = l->filelen / sizeof(*in);
2450         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2451         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2452
2453         loadmodel->num_surfaces = count;
2454
2455         loadmodel->brushq1.firstrender = true;
2456         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2457
2458         totalverts = 0;
2459         totaltris = 0;
2460         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2461         {
2462                 numedges = (unsigned short)LittleShort(in->numedges);
2463                 totalverts += numedges;
2464                 totaltris += numedges - 2;
2465         }
2466
2467         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2468
2469         lightmaptexture = NULL;
2470         deluxemaptexture = r_texture_blanknormalmap;
2471         lightmapnumber = 0;
2472         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2473         totallightmapsamples = 0;
2474
2475         totalverts = 0;
2476         totaltris = 0;
2477         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2478         {
2479                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2480
2481                 // FIXME: validate edges, texinfo, etc?
2482                 firstedge = LittleLong(in->firstedge);
2483                 numedges = (unsigned short)LittleShort(in->numedges);
2484                 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)
2485                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2486                 i = (unsigned short)LittleShort(in->texinfo);
2487                 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2488                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2489                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2490                 surface->texture = surface->lightmapinfo->texinfo->texture;
2491
2492                 planenum = (unsigned short)LittleShort(in->planenum);
2493                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2494                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2495
2496                 //surface->flags = surface->texture->flags;
2497                 //if (LittleShort(in->side))
2498                 //      surface->flags |= SURF_PLANEBACK;
2499                 //surface->plane = loadmodel->brush.data_planes + planenum;
2500
2501                 surface->num_firstvertex = totalverts;
2502                 surface->num_vertices = numedges;
2503                 surface->num_firsttriangle = totaltris;
2504                 surface->num_triangles = numedges - 2;
2505                 totalverts += numedges;
2506                 totaltris += numedges - 2;
2507
2508                 // convert edges back to a normal polygon
2509                 for (i = 0;i < surface->num_vertices;i++)
2510                 {
2511                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2512                         float s, t;
2513                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2514                         if (lindex >= 0)
2515                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2516                         else
2517                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2518                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2519                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2520                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2521                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2522                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2523                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2524                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2525                 }
2526
2527                 for (i = 0;i < surface->num_triangles;i++)
2528                 {
2529                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2530                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2531                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2532                 }
2533
2534                 // compile additional data about the surface geometry
2535                 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);
2536                 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);
2537                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2538
2539                 // generate surface extents information
2540                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2541                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2542                 for (i = 1;i < surface->num_vertices;i++)
2543                 {
2544                         for (j = 0;j < 2;j++)
2545                         {
2546                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2547                                 texmins[j] = min(texmins[j], val);
2548                                 texmaxs[j] = max(texmaxs[j], val);
2549                         }
2550                 }
2551                 for (i = 0;i < 2;i++)
2552                 {
2553                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2554                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2555                 }
2556
2557                 smax = surface->lightmapinfo->extents[0] >> 4;
2558                 tmax = surface->lightmapinfo->extents[1] >> 4;
2559                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2560                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2561
2562                 // lighting info
2563                 for (i = 0;i < MAXLIGHTMAPS;i++)
2564                         surface->lightmapinfo->styles[i] = in->styles[i];
2565                 surface->lightmaptexture = NULL;
2566                 surface->deluxemaptexture = r_texture_blanknormalmap;
2567                 i = LittleLong(in->lightofs);
2568                 if (i == -1)
2569                 {
2570                         surface->lightmapinfo->samples = NULL;
2571 #if 1
2572                         // give non-lightmapped water a 1x white lightmap
2573                         if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2574                         {
2575                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2576                                 surface->lightmapinfo->styles[0] = 0;
2577                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2578                         }
2579 #endif
2580                 }
2581                 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2582                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2583                 else // LordHavoc: white lighting (bsp version 29)
2584                 {
2585                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2586                         if (loadmodel->brushq1.nmaplightdata)
2587                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2588                 }
2589
2590                 // check if we should apply a lightmap to this
2591                 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2592                 {
2593                         if (ssize > 256 || tsize > 256)
2594                                 Host_Error("Bad surface extents");
2595
2596                         if (lightmapsize < ssize)
2597                                 lightmapsize = ssize;
2598                         if (lightmapsize < tsize)
2599                                 lightmapsize = tsize;
2600
2601                         totallightmapsamples += ssize*tsize;
2602
2603                         // force lightmap upload on first time seeing the surface
2604                         //
2605                         // additionally this is used by the later code to see if a
2606                         // lightmap is needed on this surface (rather than duplicating the
2607                         // logic above)
2608                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2609                         loadmodel->lit = true;
2610                 }
2611         }
2612
2613         // small maps (such as ammo boxes especially) don't need big lightmap
2614         // textures, so this code tries to guess a good size based on
2615         // totallightmapsamples (size of the lightmaps lump basically), as well as
2616         // trying to max out the size if there is a lot of lightmap data to store
2617         // additionally, never choose a lightmapsize that is smaller than the
2618         // largest surface encountered (as it would fail)
2619         i = lightmapsize;
2620         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2621                 ;
2622
2623         // now that we've decided the lightmap texture size, we can do the rest
2624         if (cls.state != ca_dedicated)
2625         {
2626                 int stainmapsize = 0;
2627                 mod_alloclightmap_state_t allocState;
2628
2629                 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2630                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2631                 {
2632                         int i, iu, iv, lightmapx = 0, lightmapy = 0;
2633                         float u, v, ubase, vbase, uscale, vscale;
2634
2635                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2636                                 continue;
2637
2638                         smax = surface->lightmapinfo->extents[0] >> 4;
2639                         tmax = surface->lightmapinfo->extents[1] >> 4;
2640                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2641                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2642                         stainmapsize += ssize * tsize * 3;
2643
2644                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2645                         {
2646                                 // allocate a texture pool if we need it
2647                                 if (loadmodel->texturepool == NULL)
2648                                         loadmodel->texturepool = R_AllocTexturePool();
2649                                 // could not find room, make a new lightmap
2650                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2651                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2652                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2653                                 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);
2654                                 if (loadmodel->brushq1.nmaplightdata)
2655                                         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);
2656                                 lightmapnumber++;
2657                                 Mod_AllocLightmap_Reset(&allocState);
2658                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2659                         }
2660                         surface->lightmaptexture = lightmaptexture;
2661                         surface->deluxemaptexture = deluxemaptexture;
2662                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2663                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2664
2665                         uscale = 1.0f / (float)lightmapsize;
2666                         vscale = 1.0f / (float)lightmapsize;
2667                         ubase = lightmapx * uscale;
2668                         vbase = lightmapy * vscale;
2669
2670                         for (i = 0;i < surface->num_vertices;i++)
2671                         {
2672                                 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);
2673                                 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);
2674                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2675                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2676                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2677                                 iu = (int) u;
2678                                 iv = (int) v;
2679                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2680                         }
2681                 }
2682
2683                 if (cl_stainmaps.integer)
2684                 {
2685                         // allocate stainmaps for permanent marks on walls and clear white
2686                         unsigned char *stainsamples = NULL;
2687                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2688                         memset(stainsamples, 255, stainmapsize);
2689                         // assign pointers
2690                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2691                         {
2692                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2693                                         continue;
2694                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2695                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2696                                 surface->lightmapinfo->stainsamples = stainsamples;
2697                                 stainsamples += ssize * tsize * 3;
2698                         }
2699                 }
2700         }
2701
2702         // generate ushort elements array if possible
2703         if (loadmodel->surfmesh.data_element3s)
2704                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2705                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2706 }
2707
2708 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2709 {
2710         //if (node->parent)
2711         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2712         node->parent = parent;
2713         if (node->plane)
2714         {
2715                 // this is a node, recurse to children
2716                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2717                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2718                 // combine supercontents of children
2719                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2720         }
2721         else
2722         {
2723                 int j;
2724                 mleaf_t *leaf = (mleaf_t *)node;
2725                 // if this is a leaf, calculate supercontents mask from all collidable
2726                 // primitives in the leaf (brushes and collision surfaces)
2727                 // also flag if the leaf contains any collision surfaces
2728                 leaf->combinedsupercontents = 0;
2729                 // combine the supercontents values of all brushes in this leaf
2730                 for (j = 0;j < leaf->numleafbrushes;j++)
2731                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2732                 // check if this leaf contains any collision surfaces (q3 patches)
2733                 for (j = 0;j < leaf->numleafsurfaces;j++)
2734                 {
2735                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2736                         if (surface->num_collisiontriangles)
2737                         {
2738                                 leaf->containscollisionsurfaces = true;
2739                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2740                         }
2741                 }
2742         }
2743 }
2744
2745 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2746 {
2747         int                     i, j, count, p;
2748         dnode_t         *in;
2749         mnode_t         *out;
2750
2751         in = (dnode_t *)(mod_base + l->fileofs);
2752         if (l->filelen % sizeof(*in))
2753                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2754         count = l->filelen / sizeof(*in);
2755         if (count == 0)
2756                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2757         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2758
2759         loadmodel->brush.data_nodes = out;
2760         loadmodel->brush.num_nodes = count;
2761
2762         for ( i=0 ; i<count ; i++, in++, out++)
2763         {
2764                 for (j=0 ; j<3 ; j++)
2765                 {
2766                         out->mins[j] = LittleShort(in->mins[j]);
2767                         out->maxs[j] = LittleShort(in->maxs[j]);
2768                 }
2769
2770                 p = LittleLong(in->planenum);
2771                 out->plane = loadmodel->brush.data_planes + p;
2772
2773                 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2774                 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2775
2776                 for (j=0 ; j<2 ; j++)
2777                 {
2778                         // LordHavoc: this code supports broken bsp files produced by
2779                         // arguire qbsp which can produce more than 32768 nodes, any value
2780                         // below count is assumed to be a node number, any other value is
2781                         // assumed to be a leaf number
2782                         p = (unsigned short)LittleShort(in->children[j]);
2783                         if (p < count)
2784                         {
2785                                 if (p < loadmodel->brush.num_nodes)
2786                                         out->children[j] = loadmodel->brush.data_nodes + p;
2787                                 else
2788                                 {
2789                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2790                                         // map it to the solid leaf
2791                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2792                                 }
2793                         }
2794                         else
2795                         {
2796                                 // note this uses 65535 intentionally, -1 is leaf 0
2797                                 p = 65535 - p;
2798                                 if (p < loadmodel->brush.num_leafs)
2799                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2800                                 else
2801                                 {
2802                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2803                                         // map it to the solid leaf
2804                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2805                                 }
2806                         }
2807                 }
2808         }
2809
2810         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2811 }
2812
2813 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2814 {
2815         dleaf_t *in;
2816         mleaf_t *out;
2817         int i, j, count, p;
2818
2819         in = (dleaf_t *)(mod_base + l->fileofs);
2820         if (l->filelen % sizeof(*in))
2821                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2822         count = l->filelen / sizeof(*in);
2823         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2824
2825         loadmodel->brush.data_leafs = out;
2826         loadmodel->brush.num_leafs = count;
2827         // get visleafs from the submodel data
2828         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2829         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2830         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2831         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2832
2833         for ( i=0 ; i<count ; i++, in++, out++)
2834         {
2835                 for (j=0 ; j<3 ; j++)
2836                 {
2837                         out->mins[j] = LittleShort(in->mins[j]);
2838                         out->maxs[j] = LittleShort(in->maxs[j]);
2839                 }
2840
2841                 // FIXME: this function could really benefit from some error checking
2842
2843                 out->contents = LittleLong(in->contents);
2844
2845                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2846                 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2847                 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2848                 {
2849                         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);
2850                         out->firstleafsurface = NULL;
2851                         out->numleafsurfaces = 0;
2852                 }
2853
2854                 out->clusterindex = i - 1;
2855                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2856                         out->clusterindex = -1;
2857
2858                 p = LittleLong(in->visofs);
2859                 // ignore visofs errors on leaf 0 (solid)
2860                 if (p >= 0 && out->clusterindex >= 0)
2861                 {
2862                         if (p >= loadmodel->brushq1.num_compressedpvs)
2863                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2864                         else
2865                                 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);
2866                 }
2867
2868                 for (j = 0;j < 4;j++)
2869                         out->ambient_sound_level[j] = in->ambient_level[j];
2870
2871                 // FIXME: Insert caustics here
2872         }
2873 }
2874
2875 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2876 {
2877         int i, j;
2878         mleaf_t *leaf;
2879         const unsigned char *pvs;
2880         // if there's no vis data, assume supported (because everything is visible all the time)
2881         if (!loadmodel->brush.data_pvsclusters)
2882                 return true;
2883         // check all liquid leafs to see if they can see into empty leafs, if any
2884         // can we can assume this map supports r_wateralpha
2885         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2886         {
2887                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2888                 {
2889                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2890                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
2891                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2892                                         return true;
2893                 }
2894         }
2895         return false;
2896 }
2897
2898 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2899 {
2900         dclipnode_t *in;
2901         mclipnode_t *out;
2902         int                     i, count;
2903         hull_t          *hull;
2904
2905         in = (dclipnode_t *)(mod_base + l->fileofs);
2906         if (l->filelen % sizeof(*in))
2907                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2908         count = l->filelen / sizeof(*in);
2909         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2910
2911         loadmodel->brushq1.clipnodes = out;
2912         loadmodel->brushq1.numclipnodes = count;
2913
2914         for (i = 1; i < MAX_MAP_HULLS; i++)
2915         {
2916                 hull = &loadmodel->brushq1.hulls[i];
2917                 hull->clipnodes = out;
2918                 hull->firstclipnode = 0;
2919                 hull->lastclipnode = count-1;
2920                 hull->planes = loadmodel->brush.data_planes;
2921                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2922                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2923                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2924                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2925                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2926                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2927                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2928         }
2929
2930         for (i=0 ; i<count ; i++, out++, in++)
2931         {
2932                 out->planenum = LittleLong(in->planenum);
2933                 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2934                 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2935                 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2936                 if (out->children[0] >= count)
2937                         out->children[0] -= 65536;
2938                 if (out->children[1] >= count)
2939                         out->children[1] -= 65536;
2940                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2941                         Host_Error("Corrupt clipping hull(out of range planenum)");
2942         }
2943 }
2944
2945 //Duplicate the drawing hull structure as a clipping hull
2946 static void Mod_Q1BSP_MakeHull0(void)
2947 {
2948         mnode_t         *in;
2949         mclipnode_t *out;
2950         int                     i;
2951         hull_t          *hull;
2952
2953         hull = &loadmodel->brushq1.hulls[0];
2954
2955         in = loadmodel->brush.data_nodes;