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