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