6f2651f6def8dbdc7802d6e6f42e9da578eb4f4f
[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 (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1884                 {
1885                         // replace the texture with black
1886                         tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1887                 }
1888                 else if (!strncmp(tx->name, "sky", 3))
1889                         tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1890                 else if (!strcmp(tx->name, "caulk"))
1891                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1892                 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1893                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1894
1895                 // start out with no animation
1896                 tx->currentframe = tx;
1897                 tx->currentskinframe = tx->skinframes[0];
1898                 tx->currentmaterialflags = tx->basematerialflags;
1899         }
1900
1901         // sequence the animations
1902         for (i = 0;i < nummiptex;i++)
1903         {
1904                 tx = loadmodel->data_textures + i;
1905                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1906                         continue;
1907                 if (tx->anim_total[0] || tx->anim_total[1])
1908                         continue;       // already sequenced
1909
1910                 // find the number of frames in the animation
1911                 memset(anims, 0, sizeof(anims));
1912                 memset(altanims, 0, sizeof(altanims));
1913
1914                 for (j = i;j < nummiptex;j++)
1915                 {
1916                         tx2 = loadmodel->data_textures + j;
1917                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1918                                 continue;
1919
1920                         num = tx2->name[1];
1921                         if (num >= '0' && num <= '9')
1922                                 anims[num - '0'] = tx2;
1923                         else if (num >= 'a' && num <= 'j')
1924                                 altanims[num - 'a'] = tx2;
1925                         else
1926                                 Con_Printf("Bad animating texture %s\n", tx->name);
1927                 }
1928
1929                 max = altmax = 0;
1930                 for (j = 0;j < 10;j++)
1931                 {
1932                         if (anims[j])
1933                                 max = j + 1;
1934                         if (altanims[j])
1935                                 altmax = j + 1;
1936                 }
1937                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1938
1939                 incomplete = false;
1940                 for (j = 0;j < max;j++)
1941                 {
1942                         if (!anims[j])
1943                         {
1944                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1945                                 incomplete = true;
1946                         }
1947                 }
1948                 for (j = 0;j < altmax;j++)
1949                 {
1950                         if (!altanims[j])
1951                         {
1952                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1953                                 incomplete = true;
1954                         }
1955                 }
1956                 if (incomplete)
1957                         continue;
1958
1959                 if (altmax < 1)
1960                 {
1961                         // if there is no alternate animation, duplicate the primary
1962                         // animation into the alternate
1963                         altmax = max;
1964                         for (k = 0;k < 10;k++)
1965                                 altanims[k] = anims[k];
1966                 }
1967
1968                 // link together the primary animation
1969                 for (j = 0;j < max;j++)
1970                 {
1971                         tx2 = anims[j];
1972                         tx2->animated = 1; // q1bsp
1973                         tx2->anim_total[0] = max;
1974                         tx2->anim_total[1] = altmax;
1975                         for (k = 0;k < 10;k++)
1976                         {
1977                                 tx2->anim_frames[0][k] = anims[k];
1978                                 tx2->anim_frames[1][k] = altanims[k];
1979                         }
1980                 }
1981
1982                 // if there really is an alternate anim...
1983                 if (anims[0] != altanims[0])
1984                 {
1985                         // link together the alternate animation
1986                         for (j = 0;j < altmax;j++)
1987                         {
1988                                 tx2 = altanims[j];
1989                                 tx2->animated = 1; // q1bsp
1990                                 // the primary/alternate are reversed here
1991                                 tx2->anim_total[0] = altmax;
1992                                 tx2->anim_total[1] = max;
1993                                 for (k = 0;k < 10;k++)
1994                                 {
1995                                         tx2->anim_frames[0][k] = altanims[k];
1996                                         tx2->anim_frames[1][k] = anims[k];
1997                                 }
1998                         }
1999                 }
2000         }
2001 }
2002
2003 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2004 {
2005         int i;
2006         unsigned char *in, *out, *data, d;
2007         char litfilename[MAX_QPATH];
2008         char dlitfilename[MAX_QPATH];
2009         fs_offset_t filesize;
2010         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2011         {
2012                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2013                 for (i = 0;i < sb->cursize;i++)
2014                         loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2015         }
2016         else // LordHavoc: bsp version 29 (normal white lighting)
2017         {
2018                 // LordHavoc: hope is not lost yet, check for a .lit file to load
2019                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2020                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2021                 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2022                 strlcat (litfilename, ".lit", sizeof (litfilename));
2023                 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2024                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2025                 if (data)
2026                 {
2027                         if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2028                         {
2029                                 i = LittleLong(((int *)data)[1]);
2030                                 if (i == 1)
2031                                 {
2032                                         if (developer_loading.integer)
2033                                                 Con_Printf("loaded %s\n", litfilename);
2034                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2035                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2036                                         Mem_Free(data);
2037                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2038                                         if (data)
2039                                         {
2040                                                 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2041                                                 {
2042                                                         i = LittleLong(((int *)data)[1]);
2043                                                         if (i == 1)
2044                                                         {
2045                                                                 if (developer_loading.integer)
2046                                                                         Con_Printf("loaded %s\n", dlitfilename);
2047                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2048                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2049                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
2050                                                                 loadmodel->brushq3.deluxemapping = true;
2051                                                         }
2052                                                 }
2053                                                 Mem_Free(data);
2054                                                 data = NULL;
2055                                         }
2056                                         return;
2057                                 }
2058                                 else
2059                                         Con_Printf("Unknown .lit file version (%d)\n", i);
2060                         }
2061                         else if (filesize == 8)
2062                                 Con_Print("Empty .lit file, ignoring\n");
2063                         else
2064                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2065                         if (data)
2066                         {
2067                                 Mem_Free(data);
2068                                 data = NULL;
2069                         }
2070                 }
2071                 // LordHavoc: oh well, expand the white lighting data
2072                 if (!sb->cursize)
2073                         return;
2074                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2075                 in = sb->data;
2076                 out = loadmodel->brushq1.lightdata;
2077                 for (i = 0;i < sb->cursize;i++)
2078                 {
2079                         d = *in++;
2080                         *out++ = d;
2081                         *out++ = d;
2082                         *out++ = d;
2083                 }
2084         }
2085 }
2086
2087 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2088 {
2089         loadmodel->brushq1.num_compressedpvs = 0;
2090         loadmodel->brushq1.data_compressedpvs = NULL;
2091         if (!sb->cursize)
2092                 return;
2093         loadmodel->brushq1.num_compressedpvs = sb->cursize;
2094         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2095         MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2096 }
2097
2098 // used only for HalfLife maps
2099 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2100 {
2101         char key[128], value[4096];
2102         int i, j, k;
2103         if (!data)
2104                 return;
2105         if (!COM_ParseToken_Simple(&data, false, false, true))
2106                 return; // error
2107         if (com_token[0] != '{')
2108                 return; // error
2109         while (1)
2110         {
2111                 if (!COM_ParseToken_Simple(&data, false, false, true))
2112                         return; // error
2113                 if (com_token[0] == '}')
2114                         break; // end of worldspawn
2115                 if (com_token[0] == '_')
2116                         strlcpy(key, com_token + 1, sizeof(key));
2117                 else
2118                         strlcpy(key, com_token, sizeof(key));
2119                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2120                         key[strlen(key)-1] = 0;
2121                 if (!COM_ParseToken_Simple(&data, false, false, true))
2122                         return; // error
2123                 dpsnprintf(value, sizeof(value), "%s", com_token);
2124                 if (!strcmp("wad", key)) // for HalfLife maps
2125                 {
2126                         if (loadmodel->brush.ishlbsp)
2127                         {
2128                                 j = 0;
2129                                 for (i = 0;i < (int)sizeof(value);i++)
2130                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2131                                                 break;
2132                                 if (value[i])
2133                                 {
2134                                         for (;i < (int)sizeof(value);i++)
2135                                         {
2136                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2137                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2138                                                         j = i+1;
2139                                                 else if (value[i] == ';' || value[i] == 0)
2140                                                 {
2141                                                         k = value[i];
2142                                                         value[i] = 0;
2143                                                         W_LoadTextureWadFile(&value[j], false);
2144                                                         j = i+1;
2145                                                         if (!k)
2146                                                                 break;
2147                                                 }
2148                                         }
2149                                 }
2150                         }
2151                 }
2152         }
2153 }
2154
2155 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2156 {
2157         loadmodel->brush.entities = NULL;
2158         if (!sb->cursize)
2159                 return;
2160         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2161         MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2162         loadmodel->brush.entities[sb->cursize] = 0;
2163         if (loadmodel->brush.ishlbsp)
2164                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2165 }
2166
2167
2168 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2169 {
2170         mvertex_t       *out;
2171         int                     i, count;
2172         int                     structsize = 12;
2173
2174         if (sb->cursize % structsize)
2175                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2176         count = sb->cursize / structsize;
2177         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2178
2179         loadmodel->brushq1.vertexes = out;
2180         loadmodel->brushq1.numvertexes = count;
2181
2182         for ( i=0 ; i<count ; i++, out++)
2183         {
2184                 out->position[0] = MSG_ReadLittleFloat(sb);
2185                 out->position[1] = MSG_ReadLittleFloat(sb);
2186                 out->position[2] = MSG_ReadLittleFloat(sb);
2187         }
2188 }
2189
2190 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2191 {
2192         mmodel_t        *out;
2193         int                     i, j, count;
2194         int                     structsize = (48+4*hullinfo->filehulls);
2195
2196         if (sb->cursize % structsize)
2197                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2198
2199         count = sb->cursize / structsize;
2200         out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2201
2202         loadmodel->brushq1.submodels = out;
2203         loadmodel->brush.numsubmodels = count;
2204
2205         for (i = 0; i < count; i++, out++)
2206         {
2207         // spread out the mins / maxs by a pixel
2208                 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2209                 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2210                 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2211                 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2212                 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2213                 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2214                 out->origin[0] = MSG_ReadLittleFloat(sb);
2215                 out->origin[1] = MSG_ReadLittleFloat(sb);
2216                 out->origin[2] = MSG_ReadLittleFloat(sb);
2217                 for (j = 0; j < hullinfo->filehulls; j++)
2218                         out->headnode[j] = MSG_ReadLittleLong(sb);
2219                 out->visleafs  = MSG_ReadLittleLong(sb);
2220                 out->firstface = MSG_ReadLittleLong(sb);
2221                 out->numfaces  = MSG_ReadLittleLong(sb);
2222         }
2223 }
2224
2225 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2226 {
2227         medge_t *out;
2228         int     i, count;
2229         int             structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2230
2231         if (sb->cursize % structsize)
2232                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2233         count = sb->cursize / structsize;
2234         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2235
2236         loadmodel->brushq1.edges = out;
2237         loadmodel->brushq1.numedges = count;
2238
2239         for ( i=0 ; i<count ; i++, out++)
2240         {
2241                 if (loadmodel->brush.isbsp2)
2242                 {
2243                         out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2244                         out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2245                 }
2246                 else
2247                 {
2248                         out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2249                         out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2250                 }
2251                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2252                 {
2253                         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);
2254                         if(!loadmodel->brushq1.numvertexes)
2255                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2256                                 
2257                         out->v[0] = 0;
2258                         out->v[1] = 0;
2259                 }
2260         }
2261 }
2262
2263 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2264 {
2265         mtexinfo_t *out;
2266         int i, j, k, count, miptex;
2267         int structsize = 40;
2268
2269         if (sb->cursize % structsize)
2270                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2271         count = sb->cursize / structsize;
2272         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2273
2274         loadmodel->brushq1.texinfo = out;
2275         loadmodel->brushq1.numtexinfo = count;
2276
2277         for (i = 0;i < count;i++, out++)
2278         {
2279                 for (k = 0;k < 2;k++)
2280                         for (j = 0;j < 4;j++)
2281                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2282
2283                 miptex = MSG_ReadLittleLong(sb);
2284                 out->q1flags = MSG_ReadLittleLong(sb);
2285
2286                 if (out->q1flags & TEX_SPECIAL)
2287                 {
2288                         // if texture chosen is NULL or the shader needs a lightmap,
2289                         // force to notexture water shader
2290                         out->textureindex = loadmodel->num_textures - 1;
2291                 }
2292                 else
2293                 {
2294                         // if texture chosen is NULL, force to notexture
2295                         out->textureindex = loadmodel->num_textures - 2;
2296                 }
2297                 // see if the specified miptex is valid and try to use it instead
2298                 if (loadmodel->data_textures)
2299                 {
2300                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2301                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2302                         else
2303                                 out->textureindex = miptex;
2304                 }
2305         }
2306 }
2307
2308 #if 0
2309 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2310 {
2311         int             i, j;
2312         float   *v;
2313
2314         mins[0] = mins[1] = mins[2] = 9999;
2315         maxs[0] = maxs[1] = maxs[2] = -9999;
2316         v = verts;
2317         for (i = 0;i < numverts;i++)
2318         {
2319                 for (j = 0;j < 3;j++, v++)
2320                 {
2321                         if (*v < mins[j])
2322                                 mins[j] = *v;
2323                         if (*v > maxs[j])
2324                                 maxs[j] = *v;
2325                 }
2326         }
2327 }
2328
2329 #define MAX_SUBDIVPOLYTRIANGLES 4096
2330 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2331
2332 static int subdivpolyverts, subdivpolytriangles;
2333 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2334 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2335
2336 static int subdivpolylookupvert(vec3_t v)
2337 {
2338         int i;
2339         for (i = 0;i < subdivpolyverts;i++)
2340                 if (subdivpolyvert[i][0] == v[0]
2341                  && subdivpolyvert[i][1] == v[1]
2342                  && subdivpolyvert[i][2] == v[2])
2343                         return i;
2344         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2345                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2346         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2347         return subdivpolyverts++;
2348 }
2349
2350 static void SubdividePolygon(int numverts, float *verts)
2351 {
2352         int             i, i1, i2, i3, f, b, c, p;
2353         vec3_t  mins, maxs, front[256], back[256];
2354         float   m, *pv, *cv, dist[256], frac;
2355
2356         if (numverts > 250)
2357                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2358
2359         BoundPoly(numverts, verts, mins, maxs);
2360
2361         for (i = 0;i < 3;i++)
2362         {
2363                 m = (mins[i] + maxs[i]) * 0.5;
2364                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2365                 if (maxs[i] - m < 8)
2366                         continue;
2367                 if (m - mins[i] < 8)
2368                         continue;
2369
2370                 // cut it
2371                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2372                         dist[c] = cv[i] - m;
2373
2374                 f = b = 0;
2375                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2376                 {
2377                         if (dist[p] >= 0)
2378                         {
2379                                 VectorCopy(pv, front[f]);
2380                                 f++;
2381                         }
2382                         if (dist[p] <= 0)
2383                         {
2384                                 VectorCopy(pv, back[b]);
2385                                 b++;
2386                         }
2387                         if (dist[p] == 0 || dist[c] == 0)
2388                                 continue;
2389                         if ((dist[p] > 0) != (dist[c] > 0) )
2390                         {
2391                                 // clip point
2392                                 frac = dist[p] / (dist[p] - dist[c]);
2393                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2394                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2395                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2396                                 f++;
2397                                 b++;
2398                         }
2399                 }
2400
2401                 SubdividePolygon(f, front[0]);
2402                 SubdividePolygon(b, back[0]);
2403                 return;
2404         }
2405
2406         i1 = subdivpolylookupvert(verts);
2407         i2 = subdivpolylookupvert(verts + 3);
2408         for (i = 2;i < numverts;i++)
2409         {
2410                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2411                 {
2412                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2413                         return;
2414                 }
2415
2416                 i3 = subdivpolylookupvert(verts + i * 3);
2417                 subdivpolyindex[subdivpolytriangles][0] = i1;
2418                 subdivpolyindex[subdivpolytriangles][1] = i2;
2419                 subdivpolyindex[subdivpolytriangles][2] = i3;
2420                 i2 = i3;
2421                 subdivpolytriangles++;
2422         }
2423 }
2424
2425 //Breaks a polygon up along axial 64 unit
2426 //boundaries so that turbulent and sky warps
2427 //can be done reasonably.
2428 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2429 {
2430         int i, j;
2431         surfvertex_t *v;
2432         surfmesh_t *mesh;
2433
2434         subdivpolytriangles = 0;
2435         subdivpolyverts = 0;
2436         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2437         if (subdivpolytriangles < 1)
2438                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2439
2440         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2441         mesh->num_vertices = subdivpolyverts;
2442         mesh->num_triangles = subdivpolytriangles;
2443         mesh->vertex = (surfvertex_t *)(mesh + 1);
2444         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2445         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2446
2447         for (i = 0;i < mesh->num_triangles;i++)
2448                 for (j = 0;j < 3;j++)
2449                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2450
2451         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2452         {
2453                 VectorCopy(subdivpolyvert[i], v->v);
2454                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2455                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2456         }
2457 }
2458 #endif
2459
2460 extern cvar_t gl_max_lightmapsize;
2461 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2462 {
2463         msurface_t *surface;
2464         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2465         float texmins[2], texmaxs[2], val;
2466         rtexture_t *lightmaptexture, *deluxemaptexture;
2467         char vabuf[1024];
2468         int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2469
2470         if (sb->cursize % structsize)
2471                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2472         count = sb->cursize / structsize;
2473         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2474         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2475
2476         loadmodel->num_surfaces = count;
2477
2478         loadmodel->brushq1.firstrender = true;
2479         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2480
2481         totalverts = 0;
2482         totaltris = 0;
2483         for (surfacenum = 0;surfacenum < count;surfacenum++)
2484         {
2485                 if (loadmodel->brush.isbsp2)
2486                         numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2487                 else
2488                         numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2489                 totalverts += numedges;
2490                 totaltris += numedges - 2;
2491         }
2492
2493         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2494
2495         lightmaptexture = NULL;
2496         deluxemaptexture = r_texture_blanknormalmap;
2497         lightmapnumber = 0;
2498         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2499         totallightmapsamples = 0;
2500
2501         totalverts = 0;
2502         totaltris = 0;
2503         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2504         {
2505                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2506                 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2507                 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2508                 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2509                 firstedge = MSG_ReadLittleLong(sb);
2510                 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2511                 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2512                 for (i = 0;i < MAXLIGHTMAPS;i++)
2513                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2514                 lightmapoffset = MSG_ReadLittleLong(sb);
2515
2516                 // FIXME: validate edges, texinfo, etc?
2517                 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)
2518                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2519                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2520                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2521                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2522                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2523
2524                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2525                 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2526
2527                 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2528                 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2529                         lightmapoffset = -1;
2530
2531                 //surface->flags = surface->texture->flags;
2532                 //if (LittleShort(in->side))
2533                 //      surface->flags |= SURF_PLANEBACK;
2534                 //surface->plane = loadmodel->brush.data_planes + planenum;
2535
2536                 surface->num_firstvertex = totalverts;
2537                 surface->num_vertices = numedges;
2538                 surface->num_firsttriangle = totaltris;
2539                 surface->num_triangles = numedges - 2;
2540                 totalverts += numedges;
2541                 totaltris += numedges - 2;
2542
2543                 // convert edges back to a normal polygon
2544                 for (i = 0;i < surface->num_vertices;i++)
2545                 {
2546                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2547                         float s, t;
2548                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2549                         if (lindex >= 0)
2550                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2551                         else
2552                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2553                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2554                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2555                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2556                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2557                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2558                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2559                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2560                 }
2561
2562                 for (i = 0;i < surface->num_triangles;i++)
2563                 {
2564                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2565                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2566                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2567                 }
2568
2569                 // compile additional data about the surface geometry
2570                 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);
2571                 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);
2572                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2573
2574                 // generate surface extents information
2575                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2576                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2577                 for (i = 1;i < surface->num_vertices;i++)
2578                 {
2579                         for (j = 0;j < 2;j++)
2580                         {
2581                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2582                                 texmins[j] = min(texmins[j], val);
2583                                 texmaxs[j] = max(texmaxs[j], val);
2584                         }
2585                 }
2586                 for (i = 0;i < 2;i++)
2587                 {
2588                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2589                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2590                 }
2591
2592                 smax = surface->lightmapinfo->extents[0] >> 4;
2593                 tmax = surface->lightmapinfo->extents[1] >> 4;
2594                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2595                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2596
2597                 // lighting info
2598                 surface->lightmaptexture = NULL;
2599                 surface->deluxemaptexture = r_texture_blanknormalmap;
2600                 if (lightmapoffset == -1)
2601                 {
2602                         surface->lightmapinfo->samples = NULL;
2603 #if 1
2604                         // give non-lightmapped water a 1x white lightmap
2605                         if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2606                         {
2607                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2608                                 surface->lightmapinfo->styles[0] = 0;
2609                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2610                         }
2611 #endif
2612                 }
2613                 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
2614                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2615                 else // LordHavoc: white lighting (bsp version 29)
2616                 {
2617                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2618                         if (loadmodel->brushq1.nmaplightdata)
2619                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2620                 }
2621
2622                 // check if we should apply a lightmap to this
2623                 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2624                 {
2625                         if (ssize > 256 || tsize > 256)
2626                                 Host_Error("Bad surface extents");
2627
2628                         if (lightmapsize < ssize)
2629                                 lightmapsize = ssize;
2630                         if (lightmapsize < tsize)
2631                                 lightmapsize = tsize;
2632
2633                         totallightmapsamples += ssize*tsize;
2634
2635                         // force lightmap upload on first time seeing the surface
2636                         //
2637                         // additionally this is used by the later code to see if a
2638                         // lightmap is needed on this surface (rather than duplicating the
2639                         // logic above)
2640                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2641                         loadmodel->lit = true;
2642                 }
2643         }
2644
2645         // small maps (such as ammo boxes especially) don't need big lightmap
2646         // textures, so this code tries to guess a good size based on
2647         // totallightmapsamples (size of the lightmaps lump basically), as well as
2648         // trying to max out the size if there is a lot of lightmap data to store
2649         // additionally, never choose a lightmapsize that is smaller than the
2650         // largest surface encountered (as it would fail)
2651         i = lightmapsize;
2652         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2653                 ;
2654
2655         // now that we've decided the lightmap texture size, we can do the rest
2656         if (cls.state != ca_dedicated)
2657         {
2658                 int stainmapsize = 0;
2659                 mod_alloclightmap_state_t allocState;
2660
2661                 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2662                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2663                 {
2664                         int i, iu, iv, lightmapx = 0, lightmapy = 0;
2665                         float u, v, ubase, vbase, uscale, vscale;
2666
2667                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2668                                 continue;
2669
2670                         smax = surface->lightmapinfo->extents[0] >> 4;
2671                         tmax = surface->lightmapinfo->extents[1] >> 4;
2672                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2673                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2674                         stainmapsize += ssize * tsize * 3;
2675
2676                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2677                         {
2678                                 // allocate a texture pool if we need it
2679                                 if (loadmodel->texturepool == NULL)
2680                                         loadmodel->texturepool = R_AllocTexturePool();
2681                                 // could not find room, make a new lightmap
2682                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2683                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2684                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2685                                 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);
2686                                 if (loadmodel->brushq1.nmaplightdata)
2687                                         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);
2688                                 lightmapnumber++;
2689                                 Mod_AllocLightmap_Reset(&allocState);
2690                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2691                         }
2692                         surface->lightmaptexture = lightmaptexture;
2693                         surface->deluxemaptexture = deluxemaptexture;
2694                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2695                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2696
2697                         uscale = 1.0f / (float)lightmapsize;
2698                         vscale = 1.0f / (float)lightmapsize;
2699                         ubase = lightmapx * uscale;
2700                         vbase = lightmapy * vscale;
2701
2702                         for (i = 0;i < surface->num_vertices;i++)
2703                         {
2704                                 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);
2705                                 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);
2706                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2707                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2708                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2709                                 iu = (int) u;
2710                                 iv = (int) v;
2711                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2712                         }
2713                 }
2714
2715                 if (cl_stainmaps.integer)
2716                 {
2717                         // allocate stainmaps for permanent marks on walls and clear white
2718                         unsigned char *stainsamples = NULL;
2719                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2720                         memset(stainsamples, 255, stainmapsize);
2721                         // assign pointers
2722                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2723                         {
2724                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2725                                         continue;
2726                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2727                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2728                                 surface->lightmapinfo->stainsamples = stainsamples;
2729                                 stainsamples += ssize * tsize * 3;
2730                         }
2731                 }
2732         }
2733
2734         // generate ushort elements array if possible
2735         if (loadmodel->surfmesh.data_element3s)
2736                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2737                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2738 }
2739
2740 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2741 {
2742         //if (node->parent)
2743         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2744         node->parent = parent;
2745         if (node->plane)
2746         {
2747                 // this is a node, recurse to children
2748                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2749                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2750                 // combine supercontents of children
2751                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2752         }
2753         else
2754         {
2755                 int j;
2756                 mleaf_t *leaf = (mleaf_t *)node;
2757                 // if this is a leaf, calculate supercontents mask from all collidable
2758                 // primitives in the leaf (brushes and collision surfaces)
2759                 // also flag if the leaf contains any collision surfaces
2760                 leaf->combinedsupercontents = 0;
2761                 // combine the supercontents values of all brushes in this leaf
2762                 for (j = 0;j < leaf->numleafbrushes;j++)
2763                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2764                 // check if this leaf contains any collision surfaces (q3 patches)
2765                 for (j = 0;j < leaf->numleafsurfaces;j++)
2766                 {
2767                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2768                         if (surface->num_collisiontriangles)
2769                         {
2770                                 leaf->containscollisionsurfaces = true;
2771                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2772                         }
2773                 }
2774         }
2775 }
2776
2777 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2778 {
2779         int                     i, j, count, p, child[2];
2780         mnode_t         *out;
2781         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2782
2783         if (sb->cursize % structsize)
2784                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2785         count = sb->cursize / structsize;
2786         if (count == 0)
2787                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2788         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2789
2790         loadmodel->brush.data_nodes = out;
2791         loadmodel->brush.num_nodes = count;
2792
2793         for ( i=0 ; i<count ; i++, out++)
2794         {
2795                 p = MSG_ReadLittleLong(sb);
2796                 out->plane = loadmodel->brush.data_planes + p;
2797
2798                 if (loadmodel->brush.isbsp2rmqe)
2799                 {
2800                         child[0] = MSG_ReadLittleLong(sb);
2801                         child[1] = MSG_ReadLittleLong(sb);
2802                         out->mins[0] = MSG_ReadLittleShort(sb);
2803                         out->mins[1] = MSG_ReadLittleShort(sb);
2804                         out->mins[2] = MSG_ReadLittleShort(sb);
2805                         out->maxs[0] = MSG_ReadLittleShort(sb);
2806                         out->maxs[1] = MSG_ReadLittleShort(sb);
2807                         out->maxs[2] = MSG_ReadLittleShort(sb);
2808                         out->firstsurface = MSG_ReadLittleLong(sb);
2809                         out->numsurfaces = MSG_ReadLittleLong(sb);
2810                 }
2811                 else if (loadmodel->brush.isbsp2)
2812                 {
2813                         child[0] = MSG_ReadLittleLong(sb);
2814                         child[1] = MSG_ReadLittleLong(sb);
2815                         out->mins[0] = MSG_ReadLittleFloat(sb);
2816                         out->mins[1] = MSG_ReadLittleFloat(sb);
2817                         out->mins[2] = MSG_ReadLittleFloat(sb);
2818                         out->maxs[0] = MSG_ReadLittleFloat(sb);
2819                         out->maxs[1] = MSG_ReadLittleFloat(sb);
2820                         out->maxs[2] = MSG_ReadLittleFloat(sb);
2821                         out->firstsurface = MSG_ReadLittleLong(sb);
2822                         out->numsurfaces = MSG_ReadLittleLong(sb);
2823                 }
2824                 else
2825                 {
2826                         child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2827                         child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2828                         if (child[0] >= count)
2829                                 child[0] -= 65536;
2830                         if (child[1] >= count)
2831                                 child[1] -= 65536;
2832
2833                         out->mins[0] = MSG_ReadLittleShort(sb);
2834                         out->mins[1] = MSG_ReadLittleShort(sb);
2835                         out->mins[2] = MSG_ReadLittleShort(sb);
2836                         out->maxs[0] = MSG_ReadLittleShort(sb);
2837                         out->maxs[1] = MSG_ReadLittleShort(sb);
2838                         out->maxs[2] = MSG_ReadLittleShort(sb);
2839
2840                         out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2841                         out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2842                 }
2843
2844                 for (j=0 ; j<2 ; j++)
2845                 {
2846                         // LordHavoc: this code supports broken bsp files produced by
2847                         // arguire qbsp which can produce more than 32768 nodes, any value
2848                         // below count is assumed to be a node number, any other value is
2849                         // assumed to be a leaf number
2850                         p = child[j];
2851                         if (p >= 0)
2852                         {
2853                                 if (p < loadmodel->brush.num_nodes)
2854                                         out->children[j] = loadmodel->brush.data_nodes + p;
2855                                 else
2856                                 {
2857                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2858                                         // map it to the solid leaf
2859                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2860                                 }
2861                         }
2862                         else
2863                         {
2864                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2865                                 p = -(p+1);
2866                                 if (p < loadmodel->brush.num_leafs)
2867                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2868                                 else
2869                                 {
2870                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2871                                         // map it to the solid leaf
2872                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2873                                 }
2874                         }
2875                 }
2876         }
2877
2878         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2879 }
2880
2881 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2882 {
2883         mleaf_t *out;
2884         int i, j, count, p, firstmarksurface, nummarksurfaces;
2885         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2886
2887         if (sb->cursize % structsize)
2888                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2889         count = sb->cursize / structsize;
2890         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2891
2892         loadmodel->brush.data_leafs = out;
2893         loadmodel->brush.num_leafs = count;
2894         // get visleafs from the submodel data
2895         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2896         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2897         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2898         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2899
2900         // FIXME: this function could really benefit from some error checking
2901         for ( i=0 ; i<count ; i++, out++)
2902         {
2903                 out->contents = MSG_ReadLittleLong(sb);
2904
2905                 out->clusterindex = i - 1;
2906                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2907                         out->clusterindex = -1;
2908
2909                 p = MSG_ReadLittleLong(sb);
2910                 // ignore visofs errors on leaf 0 (solid)
2911                 if (p >= 0 && out->clusterindex >= 0)
2912                 {
2913                         if (p >= loadmodel->brushq1.num_compressedpvs)
2914                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2915                         else
2916                                 Mod_Q1BSP_DecompressVis(loadmodel->brushq1.data_compressedpvs + p, loadmodel->brushq1.data_compressedpvs + loadmodel->brushq1.num_compressedpvs, loadmodel->brush.data_pvsclusters + out->clusterindex * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (out->clusterindex + 1) * loadmodel->brush.num_pvsclusterbytes);
2917                 }
2918
2919                 if (loadmodel->brush.isbsp2rmqe)
2920                 {
2921                         out->mins[0] = MSG_ReadLittleShort(sb);
2922                         out->mins[1] = MSG_ReadLittleShort(sb);
2923                         out->mins[2] = MSG_ReadLittleShort(sb);
2924                         out->maxs[0] = MSG_ReadLittleShort(sb);
2925                         out->maxs[1] = MSG_ReadLittleShort(sb);
2926                         out->maxs[2] = MSG_ReadLittleShort(sb);
2927         
2928                         firstmarksurface = MSG_ReadLittleLong(sb);
2929                         nummarksurfaces = MSG_ReadLittleLong(sb);
2930                 }
2931                 else if (loadmodel->brush.isbsp2)
2932                 {
2933                         out->mins[0] = MSG_ReadLittleFloat(sb);
2934                         out->mins[1] = MSG_ReadLittleFloat(sb);
2935                         out->mins[2] = MSG_ReadLittleFloat(sb);
2936                         out->maxs[0] = MSG_ReadLittleFloat(sb);
2937                         out->maxs[1] = MSG_ReadLittleFloat(sb);
2938                         out->maxs[2] = MSG_ReadLittleFloat(sb);
2939         
2940                         firstmarksurface = MSG_ReadLittleLong(sb);
2941                         nummarksurfaces = MSG_ReadLittleLong(sb);
2942                 }
2943                 else
2944                 {
2945                         out->mins[0] = MSG_ReadLittleShort(sb);
2946                         out->mins[1] = MSG_ReadLittleShort(sb);
2947                         out->mins[2] = MSG_ReadLittleShort(sb);
2948                         out->maxs[0] = MSG_ReadLittleShort(sb);
2949                         out->maxs[1] = MSG_ReadLittleShort(sb);
2950                         out->maxs[2] = MSG_ReadLittleShort(sb);
2951         
2952                         firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2953                         nummarksurfaces  = (unsigned short)MSG_ReadLittleShort(sb);
2954                 }
2955
2956                 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2957                 {
2958                         out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2959                         out->numleafsurfaces = nummarksurfaces;
2960                 }
2961                 else
2962                 {
2963                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2964                         out->firstleafsurface = NULL;
2965                         out->numleafsurfaces = 0;
2966                 }
2967
2968                 for (j = 0;j < 4;j++)
2969                         out->ambient_sound_level[j] = MSG_ReadByte(sb);
2970         }
2971 }
2972
2973 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2974 {
2975         int i, j;
2976         mleaf_t *leaf;
2977         const unsigned char *pvs;
2978         // if there's no vis data, assume supported (because everything is visible all the time)
2979         if (!loadmodel->brush.data_pvsclusters)
2980                 return true;
2981         // check all liquid leafs to see if they can see into empty leafs, if any
2982         // can we can assume this map supports r_wateralpha
2983         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2984         {
2985                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2986                 {
2987                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2988                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
2989                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2990                                         return true;
2991                 }
2992         }
2993         return false;
2994 }
2995
2996 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
2997 {
2998         mclipnode_t *out;
2999         int                     i, count;
3000         hull_t          *hull;
3001         int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3002
3003         if (sb->cursize % structsize)
3004                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3005         count = sb->cursize / structsize;
3006         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3007
3008         loadmodel->brushq1.clipnodes = out;
3009         loadmodel->brushq1.numclipnodes = count;
3010
3011         for (i = 1; i < MAX_MAP_HULLS; i++)
3012         {
3013                 hull = &loadmodel->brushq1.hulls[i];
3014                 hull->clipnodes = out;
3015                 hull->firstclipnode = 0;
3016                 hull->lastclipnode = count-1;
3017                 hull->planes = loadmodel->brush.data_planes;
3018                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3019                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3020                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3021                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3022                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3023                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3024                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3025         }
3026
3027         for (i=0 ; i<count ; i++, out++)
3028         {
3029                 out->planenum = MSG_ReadLittleLong(sb);
3030                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3031                         Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3032                 if (loadmodel->brush.isbsp2)
3033                 {
3034                         out->children[0] = MSG_ReadLittleLong(sb);
3035                         out->children[1] = MSG_ReadLittleLong(sb);
3036                         if (out->children[0] >= count)
3037                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3038                         if (out->children[1] >= count)
3039                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3040                 }
3041                 else
3042                 {
3043                         // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3044                         out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3045                         out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3046                         if (out->children[0] >= count)
3047                                 out->children[0] -= 65536;
3048                         if (out->children[1] >= count)
3049                                 out->children[1] -= 65536;
3050                 }
3051         }
3052 }
3053
3054 //Duplicate the drawing hull structure as a clipping hull
3055 static void Mod_Q1BSP_MakeHull0(void)
3056 {
3057         mnode_t         *in;
3058         mclipnode_t *out;
3059         int                     i;
3060         hull_t          *hull;
3061
3062         hull = &loadmodel->brushq1.hulls[0];
3063
3064         in = loadmodel->brush.data_nodes;
3065         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3066
3067         hull->clipnodes = out;
3068         hull->firstclipnode = 0;
3069         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3070         hull->planes = loadmodel->brush.data_planes;
3071
3072         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3073         {
3074                 out->planenum = in->plane - loadmodel->brush.data_planes;
3075                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3076                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3077         }
3078 }
3079
3080 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3081 {
3082         int i, j;
3083         int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3084
3085         if (sb->cursize % structsize)
3086                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3087         loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3088         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3089
3090         if (loadmodel->brush.isbsp2)
3091         {
3092                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3093                 {
3094                         j = MSG_ReadLittleLong(sb);
3095                         if (j < 0 || j >= loadmodel->num_surfaces)
3096                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3097                         loadmodel->brush.data_leafsurfaces[i] = j;
3098                 }
3099         }
3100         else
3101         {
3102                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3103                 {
3104                         j = (unsigned short) MSG_ReadLittleShort(sb);
3105                         if (j >= loadmodel->num_surfaces)
3106                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3107                         loadmodel->brush.data_leafsurfaces[i] = j;
3108                 }
3109         }
3110 }
3111
3112 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3113 {
3114         int             i;
3115         int structsize = 4;
3116
3117         if (sb->cursize % structsize)
3118                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3119         loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3120         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3121
3122         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3123                 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3124 }
3125
3126
3127 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3128 {
3129         int                     i;
3130         mplane_t        *out;
3131         int structsize = 20;
3132
3133         if (sb->cursize % structsize)
3134                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3135         loadmodel->brush.num_planes = sb->cursize / structsize;
3136         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3137
3138         for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3139         {
3140                 out->normal[0] = MSG_ReadLittleFloat(sb);
3141                 out->normal[1] = MSG_ReadLittleFloat(sb);
3142                 out->normal[2] = MSG_ReadLittleFloat(sb);
3143                 out->dist = MSG_ReadLittleFloat(sb);
3144                 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3145                 PlaneClassify(out);
3146         }
3147 }
3148
3149 static void Mod_Q1BSP_LoadMapBrushes(void)
3150 {
3151 #if 0
3152 // unfinished
3153         int submodel, numbrushes;
3154         qboolean firstbrush;
3155         char *text, *maptext;
3156         char mapfilename[MAX_QPATH];
3157         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3158         strlcat (mapfilename, ".map", sizeof (mapfilename));
3159         maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3160         if (!maptext)
3161                 return;
3162         text = maptext;
3163         if (!COM_ParseToken_Simple(&data, false, false, true))
3164                 return; // error
3165         submodel = 0;
3166         for (;;)
3167         {
3168                 if (!COM_ParseToken_Simple(&data, false, false, true))
3169                         break;
3170                 if (com_token[0] != '{')
3171                         return; // error
3172                 // entity
3173                 firstbrush = true;
3174                 numbrushes = 0;
3175                 maxbrushes = 256;
3176                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3177                 for (;;)
3178                 {
3179                         if (!COM_ParseToken_Simple(&data, false, false, true))
3180                                 return; // error
3181                         if (com_token[0] == '}')
3182                                 break; // end of entity
3183                         if (com_token[0] == '{')
3184                         {
3185                                 // brush
3186                                 if (firstbrush)
3187                                 {
3188                                         if (submodel)
3189                                         {
3190                                                 if (submodel > loadmodel->brush.numsubmodels)
3191                                                 {
3192                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3193                                                         model = NULL;
3194                                                 }
3195                                                 else
3196                                                         model = loadmodel->brush.submodels[submodel];
3197                                         }
3198                                         else
3199                                                 model = loadmodel;
3200                                 }
3201                                 for (;;)
3202                                 {
3203                                         if (!COM_ParseToken_Simple(&data, false, false, true))
3204                                                 return; // error
3205                                         if (com_token[0] == '}')
3206                                                 break; // end of brush
3207                                         // each brush face should be this format:
3208                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3209                                         // FIXME: support hl .map format
3210                                         for (pointnum = 0;pointnum < 3;pointnum++)
3211                                         {
3212                                                 COM_ParseToken_Simple(&data, false, false, true);
3213                                                 for (componentnum = 0;componentnum < 3;componentnum++)
3214                                                 {
3215                                                         COM_ParseToken_Simple(&data, false, false, true);
3216                                                         point[pointnum][componentnum] = atof(com_token);
3217                                                 }
3218                                                 COM_ParseToken_Simple(&data, false, false, true);
3219                                         }
3220                                         COM_ParseToken_Simple(&data, false, false, true);
3221                                         strlcpy(facetexture, com_token, sizeof(facetexture));
3222                                         COM_ParseToken_Simple(&data, false, false, true);
3223                                         //scroll_s = atof(com_token);
3224                                         COM_ParseToken_Simple(&data, false, false, true);
3225                                         //scroll_t = atof(com_token);
3226                                         COM_ParseToken_Simple(&data, false, false, true);
3227                                         //rotate = atof(com_token);
3228                                         COM_ParseToken_Simple(&data, false, false, true);
3229                                         //scale_s = atof(com_token);
3230                                         COM_ParseToken_Simple(&data, false, false, true);
3231                                         //scale_t = atof(com_token);
3232                                         TriangleNormal(point[0], point[1], point[2], planenormal);
3233                                         VectorNormalizeDouble(planenormal);
3234                                         planedist = DotProduct(point[0], planenormal);
3235                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3236                                 }
3237                                 continue;
3238                         }
3239                 }
3240         }
3241 #endif
3242 }
3243
3244
3245 #define MAX_PORTALPOINTS 64
3246
3247 typedef struct portal_s
3248 {
3249         mplane_t plane;
3250         mnode_t *nodes[2];              // [0] = front side of plane
3251         struct portal_s *next[2];
3252         int numpoints;
3253         double points[3*MAX_PORTALPOINTS];
3254         struct portal_s *chain; // all portals are linked into a list
3255 }
3256 portal_t;
3257
3258 static memexpandablearray_t portalarray;
3259
3260 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3261 {
3262         // process only nodes (leafs already had their box calculated)
3263         if (!node->plane)
3264                 return;
3265
3266         // calculate children first
3267         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3268         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3269
3270         // make combined bounding box from children
3271         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3272         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3273         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3274         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3275         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3276         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3277 }
3278
3279 static void Mod_Q1BSP_FinalizePortals(void)
3280 {
3281         int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3282         portal_t *p;
3283         mportal_t *portal;
3284         mvertex_t *point;
3285         mleaf_t *leaf, *endleaf;
3286
3287         // tally up portal and point counts and recalculate bounding boxes for all
3288         // leafs (because qbsp is very sloppy)
3289         leaf = loadmodel->brush.data_leafs;
3290         endleaf = leaf + loadmodel->brush.num_leafs;
3291         if (mod_recalculatenodeboxes.integer)
3292         {
3293                 for (;leaf < endleaf;leaf++)
3294                 {
3295                         VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
3296                         VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3297                 }
3298         }
3299         numportals = 0;
3300         numpoints = 0;
3301         for (portalindex = 0;portalindex < portalrange;portalindex++)
3302         {
3303                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3304                 if (!p)
3305                         continue;
3306                 // note: this check must match the one below or it will usually corrupt memory
3307                 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3308                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3309                 {
3310                         numportals += 2;
3311                         numpoints += p->numpoints * 2;
3312                 }
3313         }
3314         loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3315         loadmodel->brush.num_portals = numportals;
3316         loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3317         loadmodel->brush.num_portalpoints = numpoints;
3318         // clear all leaf portal chains
3319         for (i = 0;i < loadmodel->brush.num_leafs;i++)