]> git.xonotic.org Git - xonotic/darkplaces.git/blob - model_brush.c
deduplicate Sys_ConsoleInput()
[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_trippy = {CF_CLIENT, "r_trippy", "0", "easter egg"};
30 //cvar_t r_subdivide_size = {CF_CLIENT | CF_ARCHIVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
31 cvar_t r_novis = {CF_CLIENT, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {CF_CLIENT, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33
34 cvar_t r_subdivisions_tolerance = {CF_CLIENT, "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)"};
35 cvar_t r_subdivisions_mintess = {CF_CLIENT, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
36 cvar_t r_subdivisions_maxtess = {CF_CLIENT, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
37 cvar_t r_subdivisions_maxvertices = {CF_CLIENT, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
38 cvar_t mod_q3bsp_curves_subdivisions_tolerance = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_subdivisions_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
39 cvar_t mod_q3bsp_curves_subdivisions_mintess = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_subdivisions_mintess", "0", "minimum number of subdivisions for collision purposes (values above 0 will smooth curves that don't need it)"};
40 cvar_t mod_q3bsp_curves_subdivisions_maxtess = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_subdivisions_maxtess", "1024", "maximum number of subdivisions for collision purposes (prevents curves beyond a certain detail level, limits smoothing)"};
41 cvar_t mod_q3bsp_curves_subdivisions_maxvertices = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_subdivisions_maxvertices", "4225", "maximum vertices allowed per subdivided curve for collision purposes"};
42 cvar_t mod_q3bsp_curves_collisions = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
43 cvar_t mod_q3bsp_optimizedtraceline = {CF_CLIENT | CF_SERVER, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
44 cvar_t mod_q3bsp_lightmapmergepower = {CF_CLIENT | CF_ARCHIVE, "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, ..."};
45 cvar_t mod_q3bsp_nolightmaps = {CF_CLIENT | CF_ARCHIVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
46 cvar_t mod_q3bsp_tracelineofsight_brushes = {CF_CLIENT | CF_SERVER, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
47 cvar_t mod_q3bsp_sRGBlightmaps = {CF_CLIENT, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
48 cvar_t mod_q3bsp_lightgrid_texture = {CF_CLIENT, "mod_q3bsp_lightgrid_texture", "1", "directly apply the lightgrid as a global texture rather than only reading it at the entity origin"};
49 cvar_t mod_q3bsp_lightgrid_world_surfaces = {CF_CLIENT, "mod_q3bsp_lightgrid_world_surfaces", "0", "apply lightgrid lighting to the world bsp geometry rather than using lightmaps (experimental/debug tool)"};
50 cvar_t mod_q3bsp_lightgrid_bsp_surfaces = {CF_CLIENT, "mod_q3bsp_lightgrid_bsp_surfaces", "0", "apply lightgrid lighting to bsp models other than the world rather than using their lightmaps (experimental/debug tool)"};
51 cvar_t mod_noshader_default_offsetmapping = {CF_CLIENT | CF_ARCHIVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
52 cvar_t mod_q3shader_default_offsetmapping = {CF_CLIENT | CF_ARCHIVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
53 cvar_t mod_q3shader_default_offsetmapping_scale = {CF_CLIENT | CF_ARCHIVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
54 cvar_t mod_q3shader_default_offsetmapping_bias = {CF_CLIENT | CF_ARCHIVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
55 cvar_t mod_q3shader_default_polygonfactor = {CF_CLIENT, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
56 cvar_t mod_q3shader_default_polygonoffset = {CF_CLIENT, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
57 cvar_t mod_q3shader_default_refractive_index = {CF_CLIENT, "mod_q3shader_default_refractive_index", "1.33", "angle of refraction specified as n to apply when a photon is refracted, example values are: 1.0003 = air, water = 1.333, crown glass = 1.517, flint glass = 1.655, diamond = 2.417"};
58 cvar_t mod_q3shader_force_addalpha = {CF_CLIENT, "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"};
59 cvar_t mod_q3shader_force_terrain_alphaflag = {CF_CLIENT, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
60
61 cvar_t mod_q2bsp_littransparentsurfaces = {CF_CLIENT, "mod_q2bsp_littransparentsurfaces", "0", "allows lighting on rain in 3v3gloom3 and other cases of transparent surfaces that have lightmaps that were ignored by quake2"};
62
63 cvar_t mod_q1bsp_polygoncollisions = {CF_CLIENT | CF_SERVER, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
64 cvar_t mod_q1bsp_zero_hullsize_cutoff = {CF_CLIENT | CF_SERVER, "mod_q1bsp_zero_hullsize_cutoff", "3", "bboxes with an X dimension smaller than this will use the smallest cliphull (0x0x0) instead of being rounded up to the player cliphull (32x32x56) in Q1BSP, or crouching player (32x32x36) in HLBSP"};
65
66 cvar_t mod_bsp_portalize = {CF_CLIENT, "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_dlight_portalculling, r_shadow_realtime_world_compileportalculling"};
67 cvar_t mod_recalculatenodeboxes = {CF_CLIENT | CF_SERVER, "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"};
68
69 cvar_t mod_obj_orientation = {CF_CLIENT | CF_SERVER, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
70
71 static texture_t mod_q1bsp_texture_solid;
72 static texture_t mod_q1bsp_texture_sky;
73 static texture_t mod_q1bsp_texture_lava;
74 static texture_t mod_q1bsp_texture_slime;
75 static texture_t mod_q1bsp_texture_water;
76
77 static qbool Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs);
78
79 void Mod_BrushInit(void)
80 {
81 //      Cvar_RegisterVariable(&r_subdivide_size);
82         Cvar_RegisterVariable(&mod_bsp_portalize);
83         Cvar_RegisterVariable(&r_novis);
84         Cvar_RegisterVariable(&r_nosurftextures);
85         Cvar_RegisterVariable(&r_subdivisions_tolerance);
86         Cvar_RegisterVariable(&r_subdivisions_mintess);
87         Cvar_RegisterVariable(&r_subdivisions_maxtess);
88         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
89         Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_tolerance);
90         Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_mintess);
91         Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_maxtess);
92         Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_maxvertices);
93         Cvar_RegisterVariable(&r_trippy);
94         Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
95         Cvar_RegisterVariable(&mod_obj_orientation);
96         Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
97         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
98         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
99         Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
100         Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
101         Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
102         Cvar_RegisterVariable(&mod_q3bsp_lightgrid_texture);
103         Cvar_RegisterVariable(&mod_q3bsp_lightgrid_world_surfaces);
104         Cvar_RegisterVariable(&mod_q3bsp_lightgrid_bsp_surfaces);
105         Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
106         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
107         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
108         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
109         Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
110         Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
111         Cvar_RegisterVariable(&mod_q3shader_default_refractive_index);
112         Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
113         Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
114         Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
115         Cvar_RegisterVariable(&mod_q1bsp_zero_hullsize_cutoff);
116         Cvar_RegisterVariable(&mod_recalculatenodeboxes);
117
118         // these games were made for older DP engines and are no longer
119         // maintained; use this hack to show their textures properly
120         if(gamemode == GAME_NEXUIZ)
121                 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
122
123         memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
124         strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
125         mod_q1bsp_texture_solid.surfaceflags = 0;
126         mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
127
128         mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
129         strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
130         mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
131         mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
132
133         mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
134         strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
135         mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
136         mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
137
138         mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
139         strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
140         mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
141         mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
142
143         mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
144         strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
145         mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
146         mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
147 }
148
149 static mleaf_t *Mod_BSP_PointInLeaf(model_t *model, const vec3_t p)
150 {
151         mnode_t *node;
152
153         if (model == NULL)
154                 return NULL;
155
156         // LadyHavoc: modified to start at first clip node,
157         // in other words: first node of the (sub)model
158         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
159         while (node->plane)
160                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
161
162         return (mleaf_t *)node;
163 }
164
165 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(model_t *model, const vec3_t p, unsigned char *out, int outsize)
166 {
167         int i;
168         mleaf_t *leaf;
169         leaf = Mod_BSP_PointInLeaf(model, p);
170         if (leaf)
171         {
172                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
173                 if (i)
174                 {
175                         memcpy(out, leaf->ambient_sound_level, i);
176                         out += i;
177                         outsize -= i;
178                 }
179         }
180         if (outsize)
181                 memset(out, 0, outsize);
182 }
183
184 static int Mod_BSP_FindBoxClusters(model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
185 {
186         int numclusters = 0;
187         int nodestackindex = 0;
188         mnode_t *node, *nodestack[1024];
189         if (!model->brush.num_pvsclusters)
190                 return -1;
191         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
192         for (;;)
193         {
194 #if 1
195                 if (node->plane)
196                 {
197                         // node - recurse down the BSP tree
198                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
199                         if (sides < 3)
200                         {
201                                 if (sides == 0)
202                                         return -1; // ERROR: NAN bounding box!
203                                 // box is on one side of plane, take that path
204                                 node = node->children[sides-1];
205                         }
206                         else
207                         {
208                                 // box crosses plane, take one path and remember the other
209                                 if (nodestackindex < 1024)
210                                         nodestack[nodestackindex++] = node->children[0];
211                                 node = node->children[1];
212                         }
213                         continue;
214                 }
215                 else
216                 {
217                         // leaf - add clusterindex to list
218                         if (numclusters < maxclusters)
219                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
220                         numclusters++;
221                 }
222 #else
223                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
224                 {
225                         if (node->plane)
226                         {
227                                 if (nodestackindex < 1024)
228                                         nodestack[nodestackindex++] = node->children[0];
229                                 node = node->children[1];
230                                 continue;
231                         }
232                         else
233                         {
234                                 // leaf - add clusterindex to list
235                                 if (numclusters < maxclusters)
236                                         clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
237                                 numclusters++;
238                         }
239                 }
240 #endif
241                 // try another path we didn't take earlier
242                 if (nodestackindex == 0)
243                         break;
244                 node = nodestack[--nodestackindex];
245         }
246         // return number of clusters found (even if more than the maxclusters)
247         return numclusters;
248 }
249
250 static int Mod_BSP_BoxTouchingPVS(model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
251 {
252         int nodestackindex = 0;
253         mnode_t *node, *nodestack[1024];
254         if (!model->brush.num_pvsclusters)
255                 return true;
256         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
257         for (;;)
258         {
259 #if 1
260                 if (node->plane)
261                 {
262                         // node - recurse down the BSP tree
263                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
264                         if (sides < 3)
265                         {
266                                 if (sides == 0)
267                                         return -1; // ERROR: NAN bounding box!
268                                 // box is on one side of plane, take that path
269                                 node = node->children[sides-1];
270                         }
271                         else
272                         {
273                                 // box crosses plane, take one path and remember the other
274                                 if (nodestackindex < 1024)
275                                         nodestack[nodestackindex++] = node->children[0];
276                                 node = node->children[1];
277                         }
278                         continue;
279                 }
280                 else
281                 {
282                         // leaf - check cluster bit
283                         int clusterindex = ((mleaf_t *)node)->clusterindex;
284                         if (CHECKPVSBIT(pvs, clusterindex))
285                         {
286                                 // it is visible, return immediately with the news
287                                 return true;
288                         }
289                 }
290 #else
291                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
292                 {
293                         if (node->plane)
294                         {
295                                 if (nodestackindex < 1024)
296                                         nodestack[nodestackindex++] = node->children[0];
297                                 node = node->children[1];
298                                 continue;
299                         }
300                         else
301                         {
302                                 // leaf - check cluster bit
303                                 int clusterindex = ((mleaf_t *)node)->clusterindex;
304                                 if (CHECKPVSBIT(pvs, clusterindex))
305                                 {
306                                         // it is visible, return immediately with the news
307                                         return true;
308                                 }
309                         }
310                 }
311 #endif
312                 // nothing to see here, try another path we didn't take earlier
313                 if (nodestackindex == 0)
314                         break;
315                 node = nodestack[--nodestackindex];
316         }
317         // it is not visible
318         return false;
319 }
320
321 static int Mod_BSP_BoxTouchingLeafPVS(model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
322 {
323         int nodestackindex = 0;
324         mnode_t *node, *nodestack[1024];
325         if (!model->brush.num_leafs)
326                 return true;
327         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
328         for (;;)
329         {
330 #if 1
331                 if (node->plane)
332                 {
333                         // node - recurse down the BSP tree
334                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
335                         if (sides < 3)
336                         {
337                                 if (sides == 0)
338                                         return -1; // ERROR: NAN bounding box!
339                                 // box is on one side of plane, take that path
340                                 node = node->children[sides-1];
341                         }
342                         else
343                         {
344                                 // box crosses plane, take one path and remember the other
345                                 if (nodestackindex < 1024)
346                                         nodestack[nodestackindex++] = node->children[0];
347                                 node = node->children[1];
348                         }
349                         continue;
350                 }
351                 else
352                 {
353                         // leaf - check cluster bit
354                         int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
355                         if (CHECKPVSBIT(pvs, clusterindex))
356                         {
357                                 // it is visible, return immediately with the news
358                                 return true;
359                         }
360                 }
361 #else
362                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
363                 {
364                         if (node->plane)
365                         {
366                                 if (nodestackindex < 1024)
367                                         nodestack[nodestackindex++] = node->children[0];
368                                 node = node->children[1];
369                                 continue;
370                         }
371                         else
372                         {
373                                 // leaf - check cluster bit
374                                 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
375                                 if (CHECKPVSBIT(pvs, clusterindex))
376                                 {
377                                         // it is visible, return immediately with the news
378                                         return true;
379                                 }
380                         }
381                 }
382 #endif
383                 // nothing to see here, try another path we didn't take earlier
384                 if (nodestackindex == 0)
385                         break;
386                 node = nodestack[--nodestackindex];
387         }
388         // it is not visible
389         return false;
390 }
391
392 static int Mod_BSP_BoxTouchingVisibleLeafs(model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
393 {
394         int nodestackindex = 0;
395         mnode_t *node, *nodestack[1024];
396         if (!model->brush.num_leafs)
397                 return true;
398         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
399         for (;;)
400         {
401 #if 1
402                 if (node->plane)
403                 {
404                         // node - recurse down the BSP tree
405                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
406                         if (sides < 3)
407                         {
408                                 if (sides == 0)
409                                         return -1; // ERROR: NAN bounding box!
410                                 // box is on one side of plane, take that path
411                                 node = node->children[sides-1];
412                         }
413                         else
414                         {
415                                 // box crosses plane, take one path and remember the other
416                                 if (nodestackindex < 1024)
417                                         nodestack[nodestackindex++] = node->children[0];
418                                 node = node->children[1];
419                         }
420                         continue;
421                 }
422                 else
423                 {
424                         // leaf - check if it is visible
425                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
426                         {
427                                 // it is visible, return immediately with the news
428                                 return true;
429                         }
430                 }
431 #else
432                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
433                 {
434                         if (node->plane)
435                         {
436                                 if (nodestackindex < 1024)
437                                         nodestack[nodestackindex++] = node->children[0];
438                                 node = node->children[1];
439                                 continue;
440                         }
441                         else
442                         {
443                                 // leaf - check if it is visible
444                                 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
445                                 {
446                                         // it is visible, return immediately with the news
447                                         return true;
448                                 }
449                         }
450                 }
451 #endif
452                 // nothing to see here, try another path we didn't take earlier
453                 if (nodestackindex == 0)
454                         break;
455                 node = nodestack[--nodestackindex];
456         }
457         // it is not visible
458         return false;
459 }
460
461 typedef struct findnonsolidlocationinfo_s
462 {
463         vec3_t center;
464         vec3_t absmin, absmax;
465         vec_t radius;
466         vec3_t nudge;
467         vec_t bestdist;
468         model_t *model;
469 }
470 findnonsolidlocationinfo_t;
471
472 static void Mod_BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
473 {
474         int i, *tri;
475         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
476
477         tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
478         VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
479         VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
480         VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
481         VectorSubtract(vert[1], vert[0], edge[0]);
482         VectorSubtract(vert[2], vert[1], edge[1]);
483         CrossProduct(edge[1], edge[0], facenormal);
484         if (facenormal[0] || facenormal[1] || facenormal[2])
485         {
486                 VectorNormalize(facenormal);
487                 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
488                 if (f <= info->bestdist && f >= -info->bestdist)
489                 {
490                         VectorSubtract(vert[0], vert[2], edge[2]);
491                         VectorNormalize(edge[0]);
492                         VectorNormalize(edge[1]);
493                         VectorNormalize(edge[2]);
494                         CrossProduct(facenormal, edge[0], edgenormal[0]);
495                         CrossProduct(facenormal, edge[1], edgenormal[1]);
496                         CrossProduct(facenormal, edge[2], edgenormal[2]);
497                         // face distance
498                         if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
499                                         && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
500                                         && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
501                         {
502                                 // we got lucky, the center is within the face
503                                 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
504                                 if (dist < 0)
505                                 {
506                                         dist = -dist;
507                                         if (info->bestdist > dist)
508                                         {
509                                                 info->bestdist = dist;
510                                                 VectorScale(facenormal, (info->radius - -dist), info->nudge);
511                                         }
512                                 }
513                                 else
514                                 {
515                                         if (info->bestdist > dist)
516                                         {
517                                                 info->bestdist = dist;
518                                                 VectorScale(facenormal, (info->radius - dist), info->nudge);
519                                         }
520                                 }
521                         }
522                         else
523                         {
524                                 // check which edge or vertex the center is nearest
525                                 for (i = 0;i < 3;i++)
526                                 {
527                                         f = DotProduct(info->center, edge[i]);
528                                         if (f >= DotProduct(vert[0], edge[i])
529                                                         && f <= DotProduct(vert[1], edge[i]))
530                                         {
531                                                 // on edge
532                                                 VectorMA(info->center, -f, edge[i], point);
533                                                 dist = sqrt(DotProduct(point, point));
534                                                 if (info->bestdist > dist)
535                                                 {
536                                                         info->bestdist = dist;
537                                                         VectorScale(point, (info->radius / dist), info->nudge);
538                                                 }
539                                                 // skip both vertex checks
540                                                 // (both are further away than this edge)
541                                                 i++;
542                                         }
543                                         else
544                                         {
545                                                 // not on edge, check first vertex of edge
546                                                 VectorSubtract(info->center, vert[i], point);
547                                                 dist = sqrt(DotProduct(point, point));
548                                                 if (info->bestdist > dist)
549                                                 {
550                                                         info->bestdist = dist;
551                                                         VectorScale(point, (info->radius / dist), info->nudge);
552                                                 }
553                                         }
554                                 }
555                         }
556                 }
557         }
558 }
559
560 static void Mod_BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
561 {
562         int surfacenum, k, *mark;
563         msurface_t *surface;
564         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
565         {
566                 surface = info->model->data_surfaces + *mark;
567                 if(!surface->texture)
568                         continue;
569                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
570                 {
571                         for (k = 0;k < surface->num_triangles;k++)
572                         {
573                                 Mod_BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
574                         }
575                 }
576         }
577 }
578
579 static void Mod_BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
580 {
581         if (node->plane)
582         {
583                 float f = PlaneDiff(info->center, node->plane);
584                 if (f >= -info->bestdist)
585                         Mod_BSP_FindNonSolidLocation_r(info, node->children[0]);
586                 if (f <= info->bestdist)
587                         Mod_BSP_FindNonSolidLocation_r(info, node->children[1]);
588         }
589         else
590         {
591                 if (((mleaf_t *)node)->numleafsurfaces)
592                         Mod_BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
593         }
594 }
595
596 static void Mod_BSP_FindNonSolidLocation(model_t *model, const vec3_t in, vec3_t out, float radius)
597 {
598         int i;
599         findnonsolidlocationinfo_t info;
600         if (model == NULL)
601         {
602                 VectorCopy(in, out);
603                 return;
604         }
605         VectorCopy(in, info.center);
606         info.radius = radius;
607         info.model = model;
608         i = 0;
609         do
610         {
611                 VectorClear(info.nudge);
612                 info.bestdist = radius;
613                 VectorCopy(info.center, info.absmin);
614                 VectorCopy(info.center, info.absmax);
615                 info.absmin[0] -= info.radius + 1;
616                 info.absmin[1] -= info.radius + 1;
617                 info.absmin[2] -= info.radius + 1;
618                 info.absmax[0] += info.radius + 1;
619                 info.absmax[1] += info.radius + 1;
620                 info.absmax[2] += info.radius + 1;
621                 Mod_BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
622                 VectorAdd(info.center, info.nudge, info.center);
623         }
624         while (info.bestdist < radius && ++i < 10);
625         VectorCopy(info.center, out);
626 }
627
628 int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
629 {
630         switch(nativecontents)
631         {
632                 case CONTENTS_EMPTY:
633                         return 0;
634                 case CONTENTS_SOLID:
635                         return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
636                 case CONTENTS_WATER:
637                         return SUPERCONTENTS_WATER;
638                 case CONTENTS_SLIME:
639                         return SUPERCONTENTS_SLIME;
640                 case CONTENTS_LAVA:
641                         return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
642                 case CONTENTS_SKY:
643                         return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
644         }
645         return 0;
646 }
647
648 int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
649 {
650         if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
651                 return CONTENTS_SOLID;
652         if (supercontents & SUPERCONTENTS_SKY)
653                 return CONTENTS_SKY;
654         if (supercontents & SUPERCONTENTS_LAVA)
655                 return CONTENTS_LAVA;
656         if (supercontents & SUPERCONTENTS_SLIME)
657                 return CONTENTS_SLIME;
658         if (supercontents & SUPERCONTENTS_WATER)
659                 return CONTENTS_WATER;
660         return CONTENTS_EMPTY;
661 }
662
663 typedef struct RecursiveHullCheckTraceInfo_s
664 {
665         // the hull we're tracing through
666         const hull_t *hull;
667
668         // the trace structure to fill in
669         trace_t *trace;
670
671         // start, end, and end - start (in model space)
672         double start[3];
673         double end[3];
674         double dist[3];
675 }
676 RecursiveHullCheckTraceInfo_t;
677
678 // 1/32 epsilon to keep floating point happy
679 #define DIST_EPSILON (0.03125)
680
681 #define HULLCHECKSTATE_EMPTY 0
682 #define HULLCHECKSTATE_SOLID 1
683 #define HULLCHECKSTATE_DONE 2
684
685 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
686 {
687         // status variables, these don't need to be saved on the stack when
688         // recursing...  but are because this should be thread-safe
689         // (note: tracing against a bbox is not thread-safe, yet)
690         int ret;
691         mplane_t *plane;
692         double t1, t2;
693
694         // variables that need to be stored on the stack when recursing
695         mclipnode_t *node;
696         int p1side, p2side;
697         double midf, mid[3];
698
699         // keep looping until we hit a leaf
700         while (num >= 0)
701         {
702                 // find the point distances
703                 node = t->hull->clipnodes + num;
704                 plane = t->hull->planes + node->planenum;
705
706                 // axial planes can be calculated more quickly without the DotProduct
707                 if (plane->type < 3)
708                 {
709                         t1 = p1[plane->type] - plane->dist;
710                         t2 = p2[plane->type] - plane->dist;
711                 }
712                 else
713                 {
714                         t1 = DotProduct (plane->normal, p1) - plane->dist;
715                         t2 = DotProduct (plane->normal, p2) - plane->dist;
716                 }
717
718                 // negative plane distances indicate children[1] (behind plane)
719                 p1side = t1 < 0;
720                 p2side = t2 < 0;
721
722                 // if the line starts and ends on the same side of the plane, recurse
723                 // into that child instantly
724                 if (p1side == p2side)
725                 {
726 #if COLLISIONPARANOID >= 3
727                         if (p1side)
728                                 Con_Print("<");
729                         else
730                                 Con_Print(">");
731 #endif
732                         // loop back and process the start child
733                         num = node->children[p1side];
734                 }
735                 else
736                 {
737                         // find the midpoint where the line crosses the plane, use the
738                         // original line for best accuracy
739 #if COLLISIONPARANOID >= 3
740                         Con_Print("M");
741 #endif
742                         if (plane->type < 3)
743                         {
744                                 t1 = t->start[plane->type] - plane->dist;
745                                 t2 = t->end[plane->type] - plane->dist;
746                         }
747                         else
748                         {
749                                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
750                                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
751                         }
752                         midf = t1 / (t1 - t2);
753                         midf = bound(p1f, midf, p2f);
754                         VectorMA(t->start, midf, t->dist, mid);
755
756                         // we now have a mid point, essentially splitting the line into
757                         // the segments in the near child and the far child, we can now
758                         // recurse those in order and get their results
759
760                         // recurse both sides, front side first
761                         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
762                         // if this side is not empty, return what it is (solid or done)
763                         if (ret != HULLCHECKSTATE_EMPTY && !t->trace->allsolid)
764                                 return ret;
765
766                         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
767                         // if other side is not solid, return what it is (empty or done)
768                         if (ret != HULLCHECKSTATE_SOLID)
769                                 return ret;
770
771                         // front is air and back is solid, this is the impact point...
772
773                         // copy the plane information, flipping it if needed
774                         if (p1side)
775                         {
776                                 t->trace->plane.dist = -plane->dist;
777                                 VectorNegate (plane->normal, t->trace->plane.normal);
778                         }
779                         else
780                         {
781                                 t->trace->plane.dist = plane->dist;
782                                 VectorCopy (plane->normal, t->trace->plane.normal);
783                         }
784
785                         // calculate the return fraction which is nudged off the surface a bit
786                         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
787                         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
788                         midf = (t1 - collision_impactnudge.value) / (t1 - t2);
789                         t->trace->fraction = bound(0, midf, 1);
790
791 #if COLLISIONPARANOID >= 3
792                         Con_Print("D");
793 #endif
794                         return HULLCHECKSTATE_DONE;
795                 }
796         }
797
798         // we reached a leaf contents
799
800         // check for empty
801         num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
802         if (!t->trace->startfound)
803         {
804                 t->trace->startfound = true;
805                 t->trace->startsupercontents |= num;
806         }
807         if (num & SUPERCONTENTS_LIQUIDSMASK)
808                 t->trace->inwater = true;
809         if (num == 0)
810                 t->trace->inopen = true;
811         if (num & SUPERCONTENTS_SOLID)
812                 t->trace->hittexture = &mod_q1bsp_texture_solid;
813         else if (num & SUPERCONTENTS_SKY)
814                 t->trace->hittexture = &mod_q1bsp_texture_sky;
815         else if (num & SUPERCONTENTS_LAVA)
816                 t->trace->hittexture = &mod_q1bsp_texture_lava;
817         else if (num & SUPERCONTENTS_SLIME)
818                 t->trace->hittexture = &mod_q1bsp_texture_slime;
819         else
820                 t->trace->hittexture = &mod_q1bsp_texture_water;
821         t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
822         t->trace->hitsupercontents = num;
823         if (num & t->trace->hitsupercontentsmask)
824         {
825                 // if the first leaf is solid, set startsolid
826                 if (t->trace->allsolid)
827                         t->trace->startsolid = true;
828 #if COLLISIONPARANOID >= 3
829                 Con_Print("S");
830 #endif
831                 return HULLCHECKSTATE_SOLID;
832         }
833         else
834         {
835                 t->trace->allsolid = false;
836 #if COLLISIONPARANOID >= 3
837                 Con_Print("E");
838 #endif
839                 return HULLCHECKSTATE_EMPTY;
840         }
841 }
842
843 //#if COLLISIONPARANOID < 2
844 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
845 {
846         mplane_t *plane;
847         mclipnode_t *nodes = t->hull->clipnodes;
848         mplane_t *planes = t->hull->planes;
849         vec3_t point;
850         VectorCopy(t->start, point);
851         while (num >= 0)
852         {
853                 plane = planes + nodes[num].planenum;
854                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
855         }
856         num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
857         t->trace->startsupercontents |= num;
858         if (num & SUPERCONTENTS_LIQUIDSMASK)
859                 t->trace->inwater = true;
860         if (num == 0)
861                 t->trace->inopen = true;
862         if (num & t->trace->hitsupercontentsmask)
863         {
864                 t->trace->allsolid = t->trace->startsolid = true;
865                 return HULLCHECKSTATE_SOLID;
866         }
867         else
868         {
869                 t->trace->allsolid = t->trace->startsolid = false;
870                 return HULLCHECKSTATE_EMPTY;
871         }
872 }
873 //#endif
874
875 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, int skipmaterialflagsmask)
876 {
877         RecursiveHullCheckTraceInfo_t rhc;
878
879         memset(&rhc, 0, sizeof(rhc));
880         memset(trace, 0, sizeof(trace_t));
881         rhc.trace = trace;
882         rhc.trace->fraction = 1;
883         rhc.trace->allsolid = true;
884         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
885         VectorCopy(start, rhc.start);
886         VectorCopy(start, rhc.end);
887         Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
888 }
889
890 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, int skipmaterialflagsmask);
891
892 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, int skipmaterialflagsmask)
893 {
894         RecursiveHullCheckTraceInfo_t rhc;
895
896         if (VectorCompare(start, end))
897         {
898                 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
899                 return;
900         }
901
902         // 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...
903         if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
904         {
905                 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
906                 return;
907         }
908
909         memset(&rhc, 0, sizeof(rhc));
910         memset(trace, 0, sizeof(trace_t));
911         rhc.trace = trace;
912         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
913         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
914         rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
915         rhc.trace->fraction = 1;
916         rhc.trace->allsolid = true;
917         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
918         VectorCopy(start, rhc.start);
919         VectorCopy(end, rhc.end);
920         VectorSubtract(rhc.end, rhc.start, rhc.dist);
921 #if COLLISIONPARANOID >= 2
922         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]);
923         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
924         {
925
926                 double test[3];
927                 trace_t testtrace;
928                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
929                 memset(&testtrace, 0, sizeof(trace_t));
930                 rhc.trace = &testtrace;
931                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
932                 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
933                 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
934                 rhc.trace->fraction = 1;
935                 rhc.trace->allsolid = true;
936                 VectorCopy(test, rhc.start);
937                 VectorCopy(test, rhc.end);
938                 VectorClear(rhc.dist);
939                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
940                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
941                 if (!trace->startsolid && testtrace.startsolid)
942                         Con_Printf(" - ended in solid!\n");
943         }
944         Con_Print("\n");
945 #else
946         if (VectorLength2(rhc.dist))
947                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
948         else
949                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
950 #endif
951 }
952
953 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, int skipmaterialflagsmask)
954 {
955         // this function currently only supports same size start and end
956         double boxsize[3];
957         RecursiveHullCheckTraceInfo_t rhc;
958
959         if (VectorCompare(boxmins, boxmaxs))
960         {
961                 if (VectorCompare(start, end))
962                         Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
963                 else
964                         Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
965                 return;
966         }
967
968         memset(&rhc, 0, sizeof(rhc));
969         memset(trace, 0, sizeof(trace_t));
970         rhc.trace = trace;
971         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
972         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
973         rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
974         rhc.trace->fraction = 1;
975         rhc.trace->allsolid = true;
976         VectorSubtract(boxmaxs, boxmins, boxsize);
977         if (boxsize[0] < mod_q1bsp_zero_hullsize_cutoff.value)
978                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
979         else if (model->brush.ishlbsp)
980         {
981                 // LadyHavoc: this has to have a minor tolerance (the .1) because of
982                 // minor float precision errors from the box being transformed around
983                 if (boxsize[0] < 32.1)
984                 {
985                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
986                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
987                         else
988                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
989                 }
990                 else
991                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
992         }
993         else
994         {
995                 // LadyHavoc: this has to have a minor tolerance (the .1) because of
996                 // minor float precision errors from the box being transformed around
997                 if (boxsize[0] < 32.1)
998                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
999                 else
1000                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1001         }
1002         VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1003         VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1004         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1005 #if COLLISIONPARANOID >= 2
1006         Con_Printf("t(%f %f %f,%f %f %f,%li %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]);
1007         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1008         {
1009
1010                 double test[3];
1011                 trace_t testtrace;
1012                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1013                 memset(&testtrace, 0, sizeof(trace_t));
1014                 rhc.trace = &testtrace;
1015                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1016                 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1017                 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1018                 rhc.trace->fraction = 1;
1019                 rhc.trace->allsolid = true;
1020                 VectorCopy(test, rhc.start);
1021                 VectorCopy(test, rhc.end);
1022                 VectorClear(rhc.dist);
1023                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1024                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1025                 if (!trace->startsolid && testtrace.startsolid)
1026                         Con_Printf(" - ended in solid!\n");
1027         }
1028         Con_Print("\n");
1029 #else
1030         if (VectorLength2(rhc.dist))
1031                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1032         else
1033                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1034 #endif
1035 }
1036
1037 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1038 {
1039         int num = model->brushq1.hulls[0].firstclipnode;
1040         mplane_t *plane;
1041         mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1042         mplane_t *planes = model->brushq1.hulls[0].planes;
1043         while (num >= 0)
1044         {
1045                 plane = planes + nodes[num].planenum;
1046                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1047         }
1048         return Mod_Q1BSP_SuperContentsFromNativeContents(num);
1049 }
1050
1051 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 skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1052 {
1053 #if 1
1054         colbrushf_t cbox;
1055         colplanef_t cbox_planes[6];
1056         cbox.isaabb = true;
1057         cbox.hasaabbplanes = true;
1058         cbox.supercontents = boxsupercontents;
1059         cbox.numplanes = 6;
1060         cbox.numpoints = 0;
1061         cbox.numtriangles = 0;
1062         cbox.planes = cbox_planes;
1063         cbox.points = NULL;
1064         cbox.elements = NULL;
1065         cbox.markframe = 0;
1066         cbox.mins[0] = 0;
1067         cbox.mins[1] = 0;
1068         cbox.mins[2] = 0;
1069         cbox.maxs[0] = 0;
1070         cbox.maxs[1] = 0;
1071         cbox.maxs[2] = 0;
1072         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];
1073         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];
1074         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];
1075         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];
1076         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];
1077         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];
1078         cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1079         cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1080         cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1081         cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1082         cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1083         cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1084         memset(trace, 0, sizeof(trace_t));
1085         trace->hitsupercontentsmask = hitsupercontentsmask;
1086         trace->skipsupercontentsmask = skipsupercontentsmask;
1087         trace->skipmaterialflagsmask = skipmaterialflagsmask;
1088         trace->fraction = 1;
1089         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1090 #else
1091         RecursiveHullCheckTraceInfo_t rhc;
1092         static hull_t box_hull;
1093         static mclipnode_t box_clipnodes[6];
1094         static mplane_t box_planes[6];
1095         // fill in a default trace
1096         memset(&rhc, 0, sizeof(rhc));
1097         memset(trace, 0, sizeof(trace_t));
1098         //To keep everything totally uniform, bounding boxes are turned into small
1099         //BSP trees instead of being compared directly.
1100         // create a temp hull from bounding box sizes
1101         box_planes[0].dist = cmaxs[0] - mins[0];
1102         box_planes[1].dist = cmins[0] - maxs[0];
1103         box_planes[2].dist = cmaxs[1] - mins[1];
1104         box_planes[3].dist = cmins[1] - maxs[1];
1105         box_planes[4].dist = cmaxs[2] - mins[2];
1106         box_planes[5].dist = cmins[2] - maxs[2];
1107 #if COLLISIONPARANOID >= 3
1108         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]);
1109 #endif
1110
1111         if (box_hull.clipnodes == NULL)
1112         {
1113                 int i, side;
1114
1115                 //Set up the planes and clipnodes so that the six floats of a bounding box
1116                 //can just be stored out and get a proper hull_t structure.
1117
1118                 box_hull.clipnodes = box_clipnodes;
1119                 box_hull.planes = box_planes;
1120                 box_hull.firstclipnode = 0;
1121                 box_hull.lastclipnode = 5;
1122
1123                 for (i = 0;i < 6;i++)
1124                 {
1125                         box_clipnodes[i].planenum = i;
1126
1127                         side = i&1;
1128
1129                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1130                         if (i != 5)
1131                                 box_clipnodes[i].children[side^1] = i + 1;
1132                         else
1133                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1134
1135                         box_planes[i].type = i>>1;
1136                         box_planes[i].normal[i>>1] = 1;
1137                 }
1138         }
1139
1140         // trace a line through the generated clipping hull
1141         //rhc.boxsupercontents = boxsupercontents;
1142         rhc.hull = &box_hull;
1143         rhc.trace = trace;
1144         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1145         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1146         rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1147         rhc.trace->fraction = 1;
1148         rhc.trace->allsolid = true;
1149         VectorCopy(start, rhc.start);
1150         VectorCopy(end, rhc.end);
1151         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1152         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1153         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1154         if (rhc.trace->startsupercontents)
1155                 rhc.trace->startsupercontents = boxsupercontents;
1156 #endif
1157 }
1158
1159 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1160 {
1161         memset(trace, 0, sizeof(trace_t));
1162         trace->fraction = 1;
1163         trace->hitsupercontentsmask = hitsupercontentsmask;
1164         trace->skipsupercontentsmask = skipsupercontentsmask;
1165         trace->skipmaterialflagsmask = skipmaterialflagsmask;
1166         if (BoxesOverlap(start, start, cmins, cmaxs))
1167         {
1168                 trace->startsupercontents |= boxsupercontents;
1169                 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1170                 {
1171                         trace->startsolid = true;
1172                         trace->allsolid = true;
1173                 }
1174         }
1175 }
1176
1177 static qbool Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
1178 {
1179         trace_t trace;
1180         Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
1181         return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
1182 }
1183
1184 static int Mod_BSP_LightPoint_RecursiveBSPNode(model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1185 {
1186         int side;
1187         float front, back;
1188         float mid, distz = endz - startz;
1189
1190         while (node->plane)
1191         {
1192                 switch (node->plane->type)
1193                 {
1194                 case PLANE_X:
1195                         node = node->children[x < node->plane->dist];
1196                         continue; // loop back and process the new node
1197                 case PLANE_Y:
1198                         node = node->children[y < node->plane->dist];
1199                         continue; // loop back and process the new node
1200                 case PLANE_Z:
1201                         side = startz < node->plane->dist;
1202                         if ((endz < node->plane->dist) == side)
1203                         {
1204                                 node = node->children[side];
1205                                 continue; // loop back and process the new node
1206                         }
1207                         // found an intersection
1208                         mid = node->plane->dist;
1209                         break;
1210                 default:
1211                         back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1212                         front += startz * node->plane->normal[2];
1213                         back += endz * node->plane->normal[2];
1214                         side = front < node->plane->dist;
1215                         if ((back < node->plane->dist) == side)
1216                         {
1217                                 node = node->children[side];
1218                                 continue; // loop back and process the new node
1219                         }
1220                         // found an intersection
1221                         mid = startz + distz * (front - node->plane->dist) / (front - back);
1222                         break;
1223                 }
1224
1225                 // go down front side
1226                 if (node->children[side]->plane && Mod_BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1227                         return true;    // hit something
1228
1229                 // check for impact on this node
1230                 if (node->numsurfaces)
1231                 {
1232                         unsigned int i;
1233                         int dsi, dti, lmwidth, lmheight;
1234                         float ds, dt;
1235                         msurface_t *surface;
1236                         unsigned char *lightmap;
1237                         int maps, line3, size3;
1238                         float dsfrac;
1239                         float dtfrac;
1240                         float scale, w, w00, w01, w10, w11;
1241
1242                         surface = model->data_surfaces + node->firstsurface;
1243                         for (i = 0;i < node->numsurfaces;i++, surface++)
1244                         {
1245                                 if(!surface->texture)
1246                                         continue;
1247                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1248                                         continue;       // no lightmaps
1249
1250                                 // location we want to sample in the lightmap
1251                                 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;
1252                                 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;
1253
1254                                 // check the bounds
1255                                 // thanks to jitspoe for pointing out that this int cast was
1256                                 // rounding toward zero, so we floor it
1257                                 dsi = (int)floor(ds);
1258                                 dti = (int)floor(dt);
1259                                 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1260                                 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1261
1262                                 // is it in bounds?
1263                                 // we have to tolerate a position of lmwidth-1 for some rare
1264                                 // cases - in which case the sampling position still gets
1265                                 // clamped but the color gets interpolated to that edge.
1266                                 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1267                                 {
1268                                         // in the rare cases where we're sampling slightly off
1269                                         // the polygon, clamp the sampling position (we can still
1270                                         // interpolate outside it, where it becomes extrapolation)
1271                                         if (dsi < 0)
1272                                                 dsi = 0;
1273                                         if (dti < 0)
1274                                                 dti = 0;
1275                                         if (dsi > lmwidth-2)
1276                                                 dsi = lmwidth-2;
1277                                         if (dti > lmheight-2)
1278                                                 dti = lmheight-2;
1279                                         
1280                                         // calculate bilinear interpolation factors
1281                                         // and also multiply by fixedpoint conversion factors to
1282                                         // compensate for lightmaps being 0-255 (as 0-2), we use
1283                                         // r_refdef.scene.rtlightstylevalue here which is already
1284                                         // 0.000-2.148 range
1285                                         // (if we used r_refdef.scene.lightstylevalue this
1286                                         //  divisor would be 32768 rather than 128)
1287                                         dsfrac = ds - dsi;
1288                                         dtfrac = dt - dti;
1289                                         w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1290                                         w01 = (    dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1291                                         w10 = (1 - dsfrac) * (    dtfrac) * (1.0f / 128.0f);
1292                                         w11 = (    dsfrac) * (    dtfrac) * (1.0f / 128.0f);
1293
1294                                         // values for pointer math
1295                                         line3 = lmwidth * 3; // LadyHavoc: *3 for colored lighting
1296                                         size3 = lmwidth * lmheight * 3; // LadyHavoc: *3 for colored lighting
1297
1298                                         // look up the pixel
1299                                         lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LadyHavoc: *3 for colored lighting
1300
1301                                         // bilinear filter each lightmap style, and sum them
1302                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1303                                         {
1304                                                 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1305                                                 w = w00 * scale;VectorMA(ambientcolor, w, lightmap            , ambientcolor);
1306                                                 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3        , ambientcolor);
1307                                                 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3    , ambientcolor);
1308                                                 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1309                                                 lightmap += size3;
1310                                         }
1311
1312                                         return true; // success
1313                                 }
1314                         }
1315                 }
1316
1317                 // go down back side
1318                 node = node->children[side ^ 1];
1319                 startz = mid;
1320                 distz = endz - startz;
1321                 // loop back and process the new node
1322         }
1323
1324         // did not hit anything
1325         return false;
1326 }
1327
1328 static void Mod_BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1329 {
1330         // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1331         VectorSet(diffusenormal, 0, 0, 1);
1332
1333         if (!model->brushq1.lightdata)
1334         {
1335                 VectorSet(ambientcolor, 1, 1, 1);
1336                 VectorSet(diffusecolor, 0, 0, 0);
1337                 return;
1338         }
1339
1340         Mod_BSP_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);
1341 }
1342
1343 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const model_t *model, const mnode_t *node, double mid[3])
1344 {
1345         unsigned int i;
1346         int j;
1347         int k;
1348         const msurface_t *surface;
1349         float normal[3];
1350         float v0[3];
1351         float v1[3];
1352         float edgedir[3];
1353         float edgenormal[3];
1354         float p[4];
1355         float midf;
1356         float t1;
1357         float t2;
1358         VectorCopy(mid, p);
1359         p[3] = 1;
1360         surface = model->data_surfaces + node->firstsurface;
1361         for (i = 0;i < node->numsurfaces;i++, surface++)
1362         {
1363                 if(!surface->texture)
1364                         continue;
1365                 // skip surfaces whose bounding box does not include the point
1366 //              if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1367 //                      continue;
1368                 // skip faces with contents we don't care about
1369                 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1370                         continue;
1371                 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1372                 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1373                         continue;
1374                 // skip surfaces matching the skipmaterialflagsmask (e.g. MATERIALFLAG_NOSHADOW)
1375                 if (t->trace->skipmaterialflagsmask & surface->texture->currentmaterialflags)
1376                         continue;
1377                 // get the surface normal - since it is flat we know any vertex normal will suffice
1378                 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1379                 // skip backfaces
1380                 if (DotProduct(t->dist, normal) > 0)
1381                         continue;
1382                 // iterate edges and see if the point is outside one of them
1383                 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1384                 {
1385                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1386                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1387                         VectorSubtract(v0, v1, edgedir);
1388                         CrossProduct(edgedir, normal, edgenormal);
1389                         if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1390                                 break;
1391                 }
1392                 // if the point is outside one of the edges, it is not within the surface
1393                 if (j < surface->num_vertices)
1394                         continue;
1395
1396                 // we hit a surface, this is the impact point...
1397                 VectorCopy(normal, t->trace->plane.normal);
1398                 t->trace->plane.dist = DotProduct(normal, p);
1399
1400                 // calculate the return fraction which is nudged off the surface a bit
1401                 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1402                 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1403                 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1404                 t->trace->fraction = bound(0, midf, 1);
1405
1406                 t->trace->hittexture = surface->texture->currentframe;
1407                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1408                 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1409                 return surface->texture->currentframe;
1410         }
1411         return NULL;
1412 }
1413
1414 static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
1415 {
1416         const mplane_t *plane;
1417         double t1, t2;
1418         int side;
1419         double midf, mid[3];
1420         const mleaf_t *leaf;
1421
1422         while (node->plane)
1423         {
1424                 plane = node->plane;
1425                 if (plane->type < 3)
1426                 {
1427                         t1 = p1[plane->type] - plane->dist;
1428                         t2 = p2[plane->type] - plane->dist;
1429                 }
1430                 else
1431                 {
1432                         t1 = DotProduct (plane->normal, p1) - plane->dist;
1433                         t2 = DotProduct (plane->normal, p2) - plane->dist;
1434                 }
1435                 if (t1 < 0)
1436                 {
1437                         if (t2 < 0)
1438                         {
1439                                 node = node->children[1];
1440                                 continue;
1441                         }
1442                         side = 1;
1443                 }
1444                 else
1445                 {
1446                         if (t2 >= 0)
1447                         {
1448                                 node = node->children[0];
1449                                 continue;
1450                         }
1451                         side = 0;
1452                 }
1453
1454                 // the line intersects, find intersection point
1455                 // LadyHavoc: this uses the original trace for maximum accuracy
1456                 if (plane->type < 3)
1457                 {
1458                         t1 = t->start[plane->type] - plane->dist;
1459                         t2 = t->end[plane->type] - plane->dist;
1460                 }
1461                 else
1462                 {
1463                         t1 = DotProduct (plane->normal, t->start) - plane->dist;
1464                         t2 = DotProduct (plane->normal, t->end) - plane->dist;
1465                 }
1466         
1467                 midf = t1 / (t1 - t2);
1468                 VectorMA(t->start, midf, t->dist, mid);
1469
1470                 // recurse both sides, front side first, return if we hit a surface
1471                 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1472                         return HULLCHECKSTATE_DONE;
1473
1474                 // test each surface on the node
1475                 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1476                 if (t->trace->hittexture)
1477                         return HULLCHECKSTATE_DONE;
1478
1479                 // recurse back side
1480                 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1481         }
1482         leaf = (const mleaf_t *)node;
1483         side = Mod_Q1BSP_SuperContentsFromNativeContents(leaf->contents);
1484         if (!t->trace->startfound)
1485         {
1486                 t->trace->startfound = true;
1487                 t->trace->startsupercontents |= side;
1488         }
1489         if (side & SUPERCONTENTS_LIQUIDSMASK)
1490                 t->trace->inwater = true;
1491         if (side == 0)
1492                 t->trace->inopen = true;
1493         if (side & t->trace->hitsupercontentsmask)
1494         {
1495                 // if the first leaf is solid, set startsolid
1496                 if (t->trace->allsolid)
1497                         t->trace->startsolid = true;
1498                 return HULLCHECKSTATE_SOLID;
1499         }
1500         else
1501         {
1502                 t->trace->allsolid = false;
1503                 return HULLCHECKSTATE_EMPTY;
1504         }
1505 }
1506
1507 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, int skipmaterialflagsmask)
1508 {
1509         RecursiveHullCheckTraceInfo_t rhc;
1510
1511         memset(&rhc, 0, sizeof(rhc));
1512         memset(trace, 0, sizeof(trace_t));
1513         rhc.trace = trace;
1514         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1515         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1516         rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
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_BSP_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_BSP_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_BSP_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_BSP_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 Mod_Q1BSP_LoadSplitSky
1564
1565 A sky texture is 256*128, with the right side being a masked overlay
1566 ==============
1567 */
1568 static void Mod_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, 0, 0, 0, vid.sRGB3D);
1629         loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, 0, 0, 0, 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 = (int)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(loadmodel->mempool, 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->refractive_index = mod_q3shader_default_refractive_index.value;
1738                 tx->refractfactor = 1;
1739                 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1740                 tx->reflectfactor = 1;
1741                 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1742                 tx->r_water_wateralpha = 1;
1743                 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1744                 tx->offsetscale = 1;
1745                 tx->offsetbias = 0;
1746                 tx->specularscalemod = 1;
1747                 tx->specularpowermod = 1;
1748                 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1749                 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1750                 // JUST GREP FOR "specularscalemod = 1".
1751         }
1752
1753         if (!sb->cursize)
1754         {
1755                 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1756                 return;
1757         }
1758
1759         s = loadmodel->name;
1760         if (!strncasecmp(s, "maps/", 5))
1761                 s += 5;
1762         FS_StripExtension(s, mapname, sizeof(mapname));
1763
1764         // LadyHavoc: mostly rewritten map texture loader
1765         for (i = 0;i < nummiptex;i++)
1766         {
1767                 doffset = MSG_ReadLittleLong(sb);
1768                 if (r_nosurftextures.integer)
1769                         continue;
1770                 if (doffset == -1)
1771                 {
1772                         Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1773                         continue;
1774                 }
1775
1776                 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1777
1778                 // copy name, but only up to 16 characters
1779                 // (the output buffer can hold more than this, but the input buffer is
1780                 //  only 16)
1781                 for (j = 0;j < 16;j++)
1782                         name[j] = MSG_ReadByte(&miptexsb);
1783                 name[j] = 0;
1784                 // pretty up the buffer (replacing any trailing garbage with 0)
1785                 for (j = (int)strlen(name);j < 16;j++)
1786                         name[j] = 0;
1787
1788                 if (!name[0])
1789                 {
1790                         dpsnprintf(name, sizeof(name), "unnamed%i", i);
1791                         Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1792                 }
1793
1794                 mtwidth = MSG_ReadLittleLong(&miptexsb);
1795                 mtheight = MSG_ReadLittleLong(&miptexsb);
1796                 mtdata = NULL;
1797                 j = MSG_ReadLittleLong(&miptexsb);
1798                 if (j)
1799                 {
1800                         // texture included
1801                         if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1802                         {
1803                                 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1804                                 continue;
1805                         }
1806                         mtdata = miptexsb.data + j;
1807                 }
1808
1809                 if ((mtwidth & 15) || (mtheight & 15))
1810                         Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1811
1812                 // LadyHavoc: force all names to lowercase
1813                 for (j = 0;name[j];j++)
1814                         if (name[j] >= 'A' && name[j] <= 'Z')
1815                                 name[j] += 'a' - 'A';
1816
1817                 tx = loadmodel->data_textures + i;
1818                 // try to load shader or external textures, but first we have to backup the texture_t because shader loading overwrites it even if it fails
1819                 backuptex = loadmodel->data_textures[i];
1820                 if (name[0] && /* HACK */ strncmp(name, "sky", 3) /* END HACK */ && (Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, va(vabuf, sizeof(vabuf), "%s/%s", mapname, name), false, false, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL) ||
1821                                 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, va(vabuf, sizeof(vabuf), "%s"   , name), false, false, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL)))
1822                 {
1823                         // set the width/height fields which are used for parsing texcoords in this bsp format
1824                         tx->width = mtwidth;
1825                         tx->height = mtheight;
1826                         continue;
1827                 }
1828                 // no luck with loading shaders or external textures - restore the in-progress texture loading
1829                 loadmodel->data_textures[i] = backuptex;
1830
1831                 strlcpy(tx->name, name, sizeof(tx->name));
1832                 tx->width = mtwidth;
1833                 tx->height = mtheight;
1834                 tx->basealpha = 1.0f;
1835
1836                 // start out with no animation
1837                 tx->currentframe = tx;
1838                 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1839
1840                 if (tx->name[0] == '*')
1841                 {
1842                         if (!strncmp(tx->name, "*lava", 5))
1843                         {
1844                                 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1845                                 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1846                         }
1847                         else if (!strncmp(tx->name, "*slime", 6))
1848                         {
1849                                 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1850                                 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1851                         }
1852                         else
1853                         {
1854                                 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1855                                 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1856                         }
1857                 }
1858                 else if (!strncmp(tx->name, "sky", 3))
1859                 {
1860                         tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1861                         tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1862                         // for the surface traceline we need to hit this surface as a solid...
1863                         tx->supercontents |= SUPERCONTENTS_SOLID;
1864                 }
1865                 else
1866                 {
1867                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1868                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1869                 }
1870
1871                 if (cls.state != ca_dedicated)
1872                 {
1873                         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, false);
1874                         if ((!skinframe &&
1875                             !(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, false)))
1876                                 // HACK: It loads custom skybox textures as a wall if loaded as a skinframe.
1877                                 || !strncmp(tx->name, "sky", 3))
1878                         {
1879                                 // did not find external texture via shader loading, load it from the bsp or wad3
1880                                 if (loadmodel->brush.ishlbsp)
1881                                 {
1882                                         // internal texture overrides wad
1883                                         unsigned char* pixels, * freepixels;
1884                                         pixels = freepixels = NULL;
1885                                         if (mtdata)
1886                                                 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1887                                         if (pixels == NULL)
1888                                                 pixels = freepixels = W_GetTextureBGRA(tx->name);
1889                                         if (pixels != NULL)
1890                                         {
1891                                                 tx->width = image_width;
1892                                                 tx->height = image_height;
1893                                                 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, image_width, image_height, CRC_Block(pixels, image_width * image_height * 4), true);
1894                                         }
1895                                         if (freepixels)
1896                                                 Mem_Free(freepixels);
1897                                 }
1898                                 else if (!strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1899                                 {
1900                                         data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1901                                         if (!data)
1902                                                 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1903                                         if (data && image_width == image_height * 2)
1904                                         {
1905                                                 Mod_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1906                                                 Mem_Free(data);
1907                                         }
1908                                         else if (mtdata != NULL)
1909                                                 Mod_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1910                                 }
1911                                 else if (mtdata) // texture included
1912                                         tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1913                                 // if mtdata is NULL, the "missing" texture has already been assigned to this
1914                                 // LadyHavoc: 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, 0, 0, 0, false);
1917                                 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1918                                         tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, 0, 0, 0, false);
1919                         }
1920                         else
1921                                 tx->materialshaderpass->skinframes[0] = skinframe;
1922                         tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1923                 }
1924
1925                 tx->basematerialflags = MATERIALFLAG_WALL;
1926                 if (tx->name[0] == '*')
1927                 {
1928                         // LadyHavoc: some turbulent textures should not be affected by wateralpha
1929                         if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1930                                 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1931                         else if (!strncmp(tx->name,"*lava",5)
1932                          || !strncmp(tx->name,"*teleport",9)
1933                          || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1934                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1935                         else
1936                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1937                         if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1938                                 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1939                 }
1940                 else if (tx->name[0] == '{') // fence textures
1941                 {
1942                         tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1943                 }
1944                 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1945                 {
1946                         // replace the texture with black
1947                         tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1948                 }
1949                 else if (!strncmp(tx->name, "sky", 3))
1950                         tx->basematerialflags = MATERIALFLAG_SKY;
1951                 else if (!strcmp(tx->name, "caulk"))
1952                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1953                 else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1954                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1955                 tx->currentmaterialflags = tx->basematerialflags;
1956
1957                 // duplicate of sky with NOSHADOW
1958                 if (tx->basematerialflags & MATERIALFLAG_SKY)
1959                 {
1960                         *currentskynoshadowtexture = *tx;
1961                         currentskynoshadowtexture->basematerialflags |= MATERIALFLAG_NOSHADOW;
1962                         tx->skynoshadowtexture = currentskynoshadowtexture;
1963                         currentskynoshadowtexture++;
1964                 }
1965         }
1966
1967         // sequence the animations
1968         for (i = 0;i < nummiptex;i++)
1969         {
1970                 tx = loadmodel->data_textures + i;
1971                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1972                         continue;
1973                 num = tx->name[1];
1974                 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1975                 {
1976                         Con_Printf("Bad animating texture %s\n", tx->name);
1977                         continue;
1978                 }
1979                 if (tx->anim_total[0] || tx->anim_total[1])
1980                         continue;       // already sequenced
1981
1982                 // find the number of frames in the animation
1983                 memset(anims, 0, sizeof(anims));
1984                 memset(altanims, 0, sizeof(altanims));
1985
1986                 for (j = i;j < nummiptex;j++)
1987                 {
1988                         tx2 = loadmodel->data_textures + j;
1989                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1990                                 continue;
1991
1992                         num = tx2->name[1];
1993                         if (num >= '0' && num <= '9')
1994                                 anims[num - '0'] = tx2;
1995                         else if (num >= 'a' && num <= 'j')
1996                                 altanims[num - 'a'] = tx2;
1997                         // No need to warn otherwise - we already did above.
1998                 }
1999
2000                 max = altmax = 0;
2001                 for (j = 0;j < 10;j++)
2002                 {
2003                         if (anims[j])
2004                                 max = j + 1;
2005                         if (altanims[j])
2006                                 altmax = j + 1;
2007                 }
2008                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
2009
2010                 incomplete = false;
2011                 for (j = 0;j < max;j++)
2012                 {
2013                         if (!anims[j])
2014                         {
2015                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
2016                                 incomplete = true;
2017                         }
2018                 }
2019                 for (j = 0;j < altmax;j++)
2020                 {
2021                         if (!altanims[j])
2022                         {
2023                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
2024                                 incomplete = true;
2025                         }
2026                 }
2027                 if (incomplete)
2028                         continue;
2029
2030                 // If we have exactly one frame, something's wrong.
2031                 if (max + altmax <= 1)
2032                 {
2033                         Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
2034                 }
2035
2036                 if (altmax < 1)
2037                 {
2038                         // if there is no alternate animation, duplicate the primary
2039                         // animation into the alternate
2040                         altmax = max;
2041                         for (k = 0;k < 10;k++)
2042                                 altanims[k] = anims[k];
2043                 }
2044
2045                 if (max < 1)
2046                 {
2047                         // Warn.
2048                         Con_Printf("Missing frame 0 of %s\n", tx->name);
2049
2050                         // however, we can handle this by duplicating the alternate animation into the primary
2051                         max = altmax;
2052                         for (k = 0;k < 10;k++)
2053                                 anims[k] = altanims[k];
2054                 }
2055
2056
2057                 // link together the primary animation
2058                 for (j = 0;j < max;j++)
2059                 {
2060                         tx2 = anims[j];
2061                         tx2->animated = 1; // q1bsp
2062                         tx2->anim_total[0] = max;
2063                         tx2->anim_total[1] = altmax;
2064                         for (k = 0;k < 10;k++)
2065                         {
2066                                 tx2->anim_frames[0][k] = anims[k];
2067                                 tx2->anim_frames[1][k] = altanims[k];
2068                         }
2069                 }
2070
2071                 // if there really is an alternate anim...
2072                 if (anims[0] != altanims[0])
2073                 {
2074                         // link together the alternate animation
2075                         for (j = 0;j < altmax;j++)
2076                         {
2077                                 tx2 = altanims[j];
2078                                 tx2->animated = 1; // q1bsp
2079                                 // the primary/alternate are reversed here
2080                                 tx2->anim_total[0] = altmax;
2081                                 tx2->anim_total[1] = max;
2082                                 for (k = 0;k < 10;k++)
2083                                 {
2084                                         tx2->anim_frames[0][k] = altanims[k];
2085                                         tx2->anim_frames[1][k] = anims[k];
2086                                 }
2087                         }
2088                 }
2089         }
2090 }
2091
2092 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2093 {
2094         int i;
2095         unsigned char *in, *out, *data, d;
2096         char litfilename[MAX_QPATH];
2097         char dlitfilename[MAX_QPATH];
2098         fs_offset_t filesize;
2099         if (loadmodel->brush.ishlbsp) // LadyHavoc: load the colored lighting data straight
2100         {
2101                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2102                 for (i = 0;i < sb->cursize;i++)
2103                         loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2104         }
2105         else // LadyHavoc: bsp version 29 (normal white lighting)
2106         {
2107                 // LadyHavoc: hope is not lost yet, check for a .lit file to load
2108                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2109                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2110                 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2111                 strlcat (litfilename, ".lit", sizeof (litfilename));
2112                 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2113                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2114                 if (data)
2115                 {
2116                         if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2117                         {
2118                                 i = LittleLong(((int *)data)[1]);
2119                                 if (i == 1)
2120                                 {
2121                                         if (developer_loading.integer)
2122                                                 Con_Printf("loaded %s\n", litfilename);
2123                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2124                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2125                                         Mem_Free(data);
2126                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2127                                         if (data)
2128                                         {
2129                                                 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2130                                                 {
2131                                                         i = LittleLong(((int *)data)[1]);
2132                                                         if (i == 1)
2133                                                         {
2134                                                                 if (developer_loading.integer)
2135                                                                         Con_Printf("loaded %s\n", dlitfilename);
2136                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2137                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2138                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
2139                                                                 loadmodel->brushq3.deluxemapping = true;
2140                                                         }
2141                                                 }
2142                                                 Mem_Free(data);
2143                                                 data = NULL;
2144                                         }
2145                                         return;
2146                                 }
2147                                 else
2148                                         Con_Printf("Unknown .lit file version (%d)\n", i);
2149                         }
2150                         else if (filesize == 8)
2151                                 Con_Print("Empty .lit file, ignoring\n");
2152                         else
2153                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2154                         if (data)
2155                         {
2156                                 Mem_Free(data);
2157                                 data = NULL;
2158                         }
2159                 }
2160                 // LadyHavoc: oh well, expand the white lighting data
2161                 if (!sb->cursize)
2162                         return;
2163                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2164                 in = sb->data;
2165                 out = loadmodel->brushq1.lightdata;
2166                 for (i = 0;i < sb->cursize;i++)
2167                 {
2168                         d = *in++;
2169                         *out++ = d;
2170                         *out++ = d;
2171                         *out++ = d;
2172                 }
2173         }
2174 }
2175
2176 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2177 {
2178         loadmodel->brushq1.num_compressedpvs = 0;
2179         loadmodel->brushq1.data_compressedpvs = NULL;
2180         if (!sb->cursize)
2181                 return;
2182         loadmodel->brushq1.num_compressedpvs = sb->cursize;
2183         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2184         MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2185 }
2186
2187 // used only for HalfLife maps
2188 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2189 {
2190         char key[128], value[4096];
2191         int i, j, k;
2192         if (!data)
2193                 return;
2194         if (!COM_ParseToken_Simple(&data, false, false, true))
2195                 return; // error
2196         if (com_token[0] != '{')
2197                 return; // error
2198         while (1)
2199         {
2200                 if (!COM_ParseToken_Simple(&data, false, false, true))
2201                         return; // error
2202                 if (com_token[0] == '}')
2203                         break; // end of worldspawn
2204                 if (com_token[0] == '_')
2205                         strlcpy(key, com_token + 1, sizeof(key));
2206                 else
2207                         strlcpy(key, com_token, sizeof(key));
2208                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2209                         key[strlen(key)-1] = 0;
2210                 if (!COM_ParseToken_Simple(&data, false, false, true))
2211                         return; // error
2212                 dpsnprintf(value, sizeof(value), "%s", com_token);
2213                 if (!strcmp("wad", key)) // for HalfLife maps
2214                 {
2215                         if (loadmodel->brush.ishlbsp)
2216                         {
2217                                 j = 0;
2218                                 for (i = 0;i < (int)sizeof(value);i++)
2219                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2220                                                 break;
2221                                 if (i < (int)sizeof(value) && value[i])
2222                                 {
2223                                         for (;i < (int)sizeof(value);i++)
2224                                         {
2225                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2226                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2227                                                         j = i+1;
2228                                                 else if (value[i] == ';' || value[i] == 0)
2229                                                 {
2230                                                         k = value[i];
2231                                                         value[i] = 0;
2232                                                         W_LoadTextureWadFile(&value[j], false);
2233                                                         j = i+1;
2234                                                         if (!k)
2235                                                                 break;
2236                                                 }
2237                                         }
2238                                 }
2239                         }
2240                 }
2241         }
2242 }
2243
2244 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2245 {
2246         loadmodel->brush.entities = NULL;
2247         if (!sb->cursize)
2248                 return;
2249         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2250         MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2251         loadmodel->brush.entities[sb->cursize] = 0;
2252         if (loadmodel->brush.ishlbsp)
2253                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2254 }
2255
2256
2257 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2258 {
2259         mvertex_t       *out;
2260         int                     i, count;
2261         int                     structsize = 12;
2262
2263         if (sb->cursize % structsize)
2264                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2265         count = sb->cursize / structsize;
2266         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2267
2268         loadmodel->brushq1.vertexes = out;
2269         loadmodel->brushq1.numvertexes = count;
2270
2271         for ( i=0 ; i<count ; i++, out++)
2272         {
2273                 out->position[0] = MSG_ReadLittleFloat(sb);
2274                 out->position[1] = MSG_ReadLittleFloat(sb);
2275                 out->position[2] = MSG_ReadLittleFloat(sb);
2276         }
2277 }
2278
2279 static void Mod_BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2280 {
2281         mmodel_t        *out;
2282         int                     i, j, count;
2283         int                     structsize = hullinfo ? (48+4*hullinfo->filehulls) : 48;
2284
2285         if (sb->cursize % structsize)
2286                 Host_Error ("Mod_BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2287
2288         count = sb->cursize / structsize;
2289         out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2290
2291         loadmodel->brushq1.submodels = out;
2292         loadmodel->brush.numsubmodels = count;
2293
2294         for (i = 0; i < count; i++, out++)
2295         {
2296         // spread out the mins / maxs by a pixel
2297                 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2298                 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2299                 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2300                 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2301                 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2302                 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2303                 out->origin[0] = MSG_ReadLittleFloat(sb);
2304                 out->origin[1] = MSG_ReadLittleFloat(sb);
2305                 out->origin[2] = MSG_ReadLittleFloat(sb);
2306                 if(hullinfo)
2307                 {
2308                         for (j = 0; j < hullinfo->filehulls; j++)
2309                                 out->headnode[j] = MSG_ReadLittleLong(sb);
2310                         out->visleafs  = MSG_ReadLittleLong(sb);
2311                 }
2312                 else // Quake 2 has only one hull
2313                         out->headnode[0] = MSG_ReadLittleLong(sb);
2314
2315                 out->firstface = MSG_ReadLittleLong(sb);
2316                 out->numfaces  = MSG_ReadLittleLong(sb);
2317         }
2318 }
2319
2320 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2321 {
2322         medge_t *out;
2323         int     i, count;
2324         int             structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2325
2326         if (sb->cursize % structsize)
2327                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2328         count = sb->cursize / structsize;
2329         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2330
2331         loadmodel->brushq1.edges = out;
2332         loadmodel->brushq1.numedges = count;
2333
2334         for ( i=0 ; i<count ; i++, out++)
2335         {
2336                 if (loadmodel->brush.isbsp2)
2337                 {
2338                         out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2339                         out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2340                 }
2341                 else
2342                 {
2343                         out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2344                         out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2345                 }
2346                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2347                 {
2348                         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);
2349                         if(!loadmodel->brushq1.numvertexes)
2350                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2351                                 
2352                         out->v[0] = 0;
2353                         out->v[1] = 0;
2354                 }
2355         }
2356 }
2357
2358 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2359 {
2360         mtexinfo_t *out;
2361         int i, j, k, count, miptex;
2362         int structsize = 40;
2363
2364         if (sb->cursize % structsize)
2365                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2366         count = sb->cursize / structsize;
2367         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2368
2369         loadmodel->brushq1.texinfo = out;
2370         loadmodel->brushq1.numtexinfo = count;
2371
2372         for (i = 0;i < count;i++, out++)
2373         {
2374                 for (k = 0;k < 2;k++)
2375                         for (j = 0;j < 4;j++)
2376                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2377
2378                 miptex = MSG_ReadLittleLong(sb);
2379                 out->q1flags = MSG_ReadLittleLong(sb);
2380
2381                 if (out->q1flags & TEX_SPECIAL)
2382                 {
2383                         // if texture chosen is NULL or the shader needs a lightmap,
2384                         // force to notexture water shader
2385                         out->textureindex = loadmodel->num_textures - 1;
2386                 }
2387                 else
2388                 {
2389                         // if texture chosen is NULL, force to notexture
2390                         out->textureindex = loadmodel->num_textures - 2;
2391                 }
2392                 // see if the specified miptex is valid and try to use it instead
2393                 if (loadmodel->data_textures)
2394                 {
2395                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2396                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2397                         else
2398                                 out->textureindex = miptex;
2399                 }
2400         }
2401 }
2402
2403 #if 0
2404 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2405 {
2406         int             i, j;
2407         float   *v;
2408
2409         mins[0] = mins[1] = mins[2] = 9999;
2410         maxs[0] = maxs[1] = maxs[2] = -9999;
2411         v = verts;
2412         for (i = 0;i < numverts;i++)
2413         {
2414                 for (j = 0;j < 3;j++, v++)
2415                 {
2416                         if (*v < mins[j])
2417                                 mins[j] = *v;
2418                         if (*v > maxs[j])
2419                                 maxs[j] = *v;
2420                 }
2421         }
2422 }
2423
2424 #define MAX_SUBDIVPOLYTRIANGLES 4096
2425 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2426
2427 static int subdivpolyverts, subdivpolytriangles;
2428 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2429 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2430
2431 static int subdivpolylookupvert(vec3_t v)
2432 {
2433         int i;
2434         for (i = 0;i < subdivpolyverts;i++)
2435                 if (subdivpolyvert[i][0] == v[0]
2436                  && subdivpolyvert[i][1] == v[1]
2437                  && subdivpolyvert[i][2] == v[2])
2438                         return i;
2439         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2440                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2441         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2442         return subdivpolyverts++;
2443 }
2444
2445 static void SubdividePolygon(int numverts, float *verts)
2446 {
2447         int             i, i1, i2, i3, f, b, c, p;
2448         vec3_t  mins, maxs, front[256], back[256];
2449         float   m, *pv, *cv, dist[256], frac;
2450
2451         if (numverts > 250)
2452                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2453
2454         BoundPoly(numverts, verts, mins, maxs);
2455
2456         for (i = 0;i < 3;i++)
2457         {
2458                 m = (mins[i] + maxs[i]) * 0.5;
2459                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2460                 if (maxs[i] - m < 8)
2461                         continue;
2462                 if (m - mins[i] < 8)
2463                         continue;
2464
2465                 // cut it
2466                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2467                         dist[c] = cv[i] - m;
2468
2469                 f = b = 0;
2470                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2471                 {
2472                         if (dist[p] >= 0)
2473                         {
2474                                 VectorCopy(pv, front[f]);
2475                                 f++;
2476                         }
2477                         if (dist[p] <= 0)
2478                         {
2479                                 VectorCopy(pv, back[b]);
2480                                 b++;
2481                         }
2482                         if (dist[p] == 0 || dist[c] == 0)
2483                                 continue;
2484                         if ((dist[p] > 0) != (dist[c] > 0) )
2485                         {
2486                                 // clip point
2487                                 frac = dist[p] / (dist[p] - dist[c]);
2488                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2489                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2490                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2491                                 f++;
2492                                 b++;
2493                         }
2494                 }
2495
2496                 SubdividePolygon(f, front[0]);
2497                 SubdividePolygon(b, back[0]);
2498                 return;
2499         }
2500
2501         i1 = subdivpolylookupvert(verts);
2502         i2 = subdivpolylookupvert(verts + 3);
2503         for (i = 2;i < numverts;i++)
2504         {
2505                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2506                 {
2507                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2508                         return;
2509                 }
2510
2511                 i3 = subdivpolylookupvert(verts + i * 3);
2512                 subdivpolyindex[subdivpolytriangles][0] = i1;
2513                 subdivpolyindex[subdivpolytriangles][1] = i2;
2514                 subdivpolyindex[subdivpolytriangles][2] = i3;
2515                 i2 = i3;
2516                 subdivpolytriangles++;
2517         }
2518 }
2519
2520 //Breaks a polygon up along axial 64 unit
2521 //boundaries so that turbulent and sky warps
2522 //can be done reasonably.
2523 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2524 {
2525         int i, j;
2526         surfvertex_t *v;
2527         surfmesh_t *mesh;
2528
2529         subdivpolytriangles = 0;
2530         subdivpolyverts = 0;
2531         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2532         if (subdivpolytriangles < 1)
2533                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2534
2535         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2536         mesh->num_vertices = subdivpolyverts;
2537         mesh->num_triangles = subdivpolytriangles;
2538         mesh->vertex = (surfvertex_t *)(mesh + 1);
2539         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2540         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2541
2542         for (i = 0;i < mesh->num_triangles;i++)
2543                 for (j = 0;j < 3;j++)
2544                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2545
2546         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2547         {
2548                 VectorCopy(subdivpolyvert[i], v->v);
2549                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2550                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2551         }
2552 }
2553 #endif
2554
2555 extern cvar_t gl_max_lightmapsize;
2556 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2557 {
2558         msurface_t *surface;
2559         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2560         float texmins[2], texmaxs[2], val;
2561         rtexture_t *lightmaptexture, *deluxemaptexture;
2562         char vabuf[1024];
2563         int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2564
2565         if (sb->cursize % structsize)
2566                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2567         count = sb->cursize / structsize;
2568         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2569         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2570
2571         loadmodel->num_surfaces = count;
2572
2573         loadmodel->brushq1.firstrender = true;
2574         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2575
2576         totalverts = 0;
2577         totaltris = 0;
2578         for (surfacenum = 0;surfacenum < count;surfacenum++)
2579         {
2580                 if (loadmodel->brush.isbsp2)
2581                         numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2582                 else
2583                         numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2584                 totalverts += numedges;
2585                 totaltris += numedges - 2;
2586         }
2587
2588         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
2589
2590         lightmaptexture = NULL;
2591         deluxemaptexture = r_texture_blanknormalmap;
2592         lightmapnumber = 0;
2593         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2594         totallightmapsamples = 0;
2595
2596         totalverts = 0;
2597         totaltris = 0;
2598         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2599         {
2600                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2601                 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2602                 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2603                 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2604                 firstedge = MSG_ReadLittleLong(sb);
2605                 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2606                 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2607                 for (i = 0;i < MAXLIGHTMAPS;i++)
2608                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2609                 lightmapoffset = MSG_ReadLittleLong(sb);
2610
2611                 // FIXME: validate edges, texinfo, etc?
2612                 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)
2613                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2614                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2615                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2616                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2617                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2618
2619                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2620                 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2621
2622                 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2623                 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2624                         lightmapoffset = -1;
2625
2626                 //surface->flags = surface->texture->flags;
2627                 //if (LittleShort(in->side))
2628                 //      surface->flags |= SURF_PLANEBACK;
2629                 //surface->plane = loadmodel->brush.data_planes + planenum;
2630
2631                 surface->num_firstvertex = totalverts;
2632                 surface->num_vertices = numedges;
2633                 surface->num_firsttriangle = totaltris;
2634                 surface->num_triangles = numedges - 2;
2635                 totalverts += numedges;
2636                 totaltris += numedges - 2;
2637
2638                 // convert edges back to a normal polygon
2639                 for (i = 0;i < surface->num_vertices;i++)
2640                 {
2641                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2642                         float s, t;
2643                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2644                         if (lindex >= 0)
2645                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2646                         else
2647                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2648                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2649                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2650                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2651                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2652                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2653                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2654                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2655                 }
2656
2657                 for (i = 0;i < surface->num_triangles;i++)
2658                 {
2659                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2660                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2661                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2662                 }
2663
2664                 // compile additional data about the surface geometry
2665                 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);
2666                 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);
2667                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2668
2669                 // generate surface extents information
2670                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2671                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2672                 for (i = 1;i < surface->num_vertices;i++)
2673                 {
2674                         for (j = 0;j < 2;j++)
2675                         {
2676                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2677                                 texmins[j] = min(texmins[j], val);
2678                                 texmaxs[j] = max(texmaxs[j], val);
2679                         }
2680                 }
2681                 for (i = 0;i < 2;i++)
2682                 {
2683                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2684                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2685                 }
2686
2687                 smax = surface->lightmapinfo->extents[0] >> 4;
2688                 tmax = surface->lightmapinfo->extents[1] >> 4;
2689                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2690                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2691
2692                 // lighting info
2693                 surface->lightmaptexture = NULL;
2694                 surface->deluxemaptexture = r_texture_blanknormalmap;
2695                 if (lightmapoffset == -1)
2696                 {
2697                         surface->lightmapinfo->samples = NULL;
2698 #if 1
2699                         // give non-lightmapped water a 1x white lightmap
2700                         if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2701                         {
2702                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2703                                 surface->lightmapinfo->styles[0] = 0;
2704                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2705                         }
2706 #endif
2707                 }
2708                 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LadyHavoc: HalfLife map (bsp version 30)
2709                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2710                 else // LadyHavoc: white lighting (bsp version 29)
2711                 {
2712                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2713                         if (loadmodel->brushq1.nmaplightdata)
2714                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2715                 }
2716
2717                 // check if we should apply a lightmap to this
2718                 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2719                 {
2720                         if (ssize > 256 || tsize > 256)
2721                                 Host_Error("Bad surface extents");
2722
2723                         if (lightmapsize < ssize)
2724                                 lightmapsize = ssize;
2725                         if (lightmapsize < tsize)
2726                                 lightmapsize = tsize;
2727
2728                         totallightmapsamples += ssize*tsize;
2729
2730                         // force lightmap upload on first time seeing the surface
2731                         //
2732                         // additionally this is used by the later code to see if a
2733                         // lightmap is needed on this surface (rather than duplicating the
2734                         // logic above)
2735                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2736                         loadmodel->lit = true;
2737                 }
2738         }
2739
2740         // small maps (such as ammo boxes especially) don't need big lightmap
2741         // textures, so this code tries to guess a good size based on
2742         // totallightmapsamples (size of the lightmaps lump basically), as well as
2743         // trying to max out the size if there is a lot of lightmap data to store
2744         // additionally, never choose a lightmapsize that is smaller than the
2745         // largest surface encountered (as it would fail)
2746         i = lightmapsize;
2747         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2748                 ;
2749
2750         // now that we've decided the lightmap texture size, we can do the rest
2751         if (cls.state != ca_dedicated)
2752         {
2753                 int stainmapsize = 0;
2754                 mod_alloclightmap_state_t allocState;
2755
2756                 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2757                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2758                 {
2759                         int iu, iv, lightmapx = 0, lightmapy = 0;
2760                         float u, v, ubase, vbase, uscale, vscale;
2761
2762                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2763                                 continue;
2764
2765                         smax = surface->lightmapinfo->extents[0] >> 4;
2766                         tmax = surface->lightmapinfo->extents[1] >> 4;
2767                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2768                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2769                         stainmapsize += ssize * tsize * 3;
2770
2771                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2772                         {
2773                                 // allocate a texture pool if we need it
2774                                 if (loadmodel->texturepool == NULL)
2775                                         loadmodel->texturepool = R_AllocTexturePool();
2776                                 // could not find room, make a new lightmap
2777                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2778                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2779                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2780                                 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);
2781                                 if (loadmodel->brushq1.nmaplightdata)
2782                                         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);
2783                                 lightmapnumber++;
2784                                 Mod_AllocLightmap_Reset(&allocState);
2785                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2786                         }
2787                         surface->lightmaptexture = lightmaptexture;
2788                         surface->deluxemaptexture = deluxemaptexture;
2789                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2790                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2791
2792                         uscale = 1.0f / (float)lightmapsize;
2793                         vscale = 1.0f / (float)lightmapsize;
2794                         ubase = lightmapx * uscale;
2795                         vbase = lightmapy * vscale;
2796
2797                         for (i = 0;i < surface->num_vertices;i++)
2798                         {
2799                                 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);
2800                                 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);
2801                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2802                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2803                                 // LadyHavoc: calc lightmap data offset for vertex lighting to use
2804                                 iu = (int) u;
2805                                 iv = (int) v;
2806                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2807                         }
2808                 }
2809
2810                 if (cl_stainmaps.integer)
2811                 {
2812                         // allocate stainmaps for permanent marks on walls and clear white
2813                         unsigned char *stainsamples = NULL;
2814                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2815                         memset(stainsamples, 255, stainmapsize);
2816                         // assign pointers
2817                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2818                         {
2819                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2820                                         continue;
2821                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2822                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2823                                 surface->lightmapinfo->stainsamples = stainsamples;
2824                                 stainsamples += ssize * tsize * 3;
2825                         }
2826                 }
2827         }
2828
2829         // generate ushort elements array if possible
2830         if (loadmodel->surfmesh.data_element3s)
2831                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2832                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2833 }
2834
2835 static void Mod_BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2836 {
2837         //if (node->parent)
2838         //      Host_Error("Mod_BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2839         node->parent = parent;
2840         if (node->plane)
2841         {
2842                 // this is a node, recurse to children
2843                 Mod_BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2844                 Mod_BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2845                 // combine supercontents of children
2846                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2847         }
2848         else
2849         {
2850                 int j;
2851                 mleaf_t *leaf = (mleaf_t *)node;
2852                 // if this is a leaf, calculate supercontents mask from all collidable
2853                 // primitives in the leaf (brushes and collision surfaces)
2854                 // also flag if the leaf contains any collision surfaces
2855                 leaf->combinedsupercontents = 0;
2856                 // combine the supercontents values of all brushes in this leaf
2857                 for (j = 0;j < leaf->numleafbrushes;j++)
2858                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2859                 // check if this leaf contains any collision surfaces (q3 patches)
2860                 for (j = 0;j < leaf->numleafsurfaces;j++)
2861                 {
2862                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2863                         if (surface->num_collisiontriangles)
2864                         {
2865                                 leaf->containscollisionsurfaces = true;
2866                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2867                         }
2868                 }
2869         }
2870 }
2871
2872 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2873 {
2874         int                     i, j, count, p, child[2];
2875         mnode_t         *out;
2876         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2877
2878         if (sb->cursize % structsize)
2879                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2880         count = sb->cursize / structsize;
2881         if (count == 0)
2882                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2883         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2884
2885         loadmodel->brush.data_nodes = out;
2886         loadmodel->brush.num_nodes = count;
2887
2888         for ( i=0 ; i<count ; i++, out++)
2889         {
2890                 p = MSG_ReadLittleLong(sb);
2891                 out->plane = loadmodel->brush.data_planes + p;
2892
2893                 if (loadmodel->brush.isbsp2rmqe)
2894                 {
2895                         child[0] = MSG_ReadLittleLong(sb);
2896                         child[1] = MSG_ReadLittleLong(sb);
2897                         out->mins[0] = MSG_ReadLittleShort(sb);
2898                         out->mins[1] = MSG_ReadLittleShort(sb);
2899                         out->mins[2] = MSG_ReadLittleShort(sb);
2900                         out->maxs[0] = MSG_ReadLittleShort(sb);
2901                         out->maxs[1] = MSG_ReadLittleShort(sb);
2902                         out->maxs[2] = MSG_ReadLittleShort(sb);
2903                         out->firstsurface = MSG_ReadLittleLong(sb);
2904                         out->numsurfaces = MSG_ReadLittleLong(sb);
2905                 }
2906                 else if (loadmodel->brush.isbsp2)
2907                 {
2908                         child[0] = MSG_ReadLittleLong(sb);
2909                         child[1] = MSG_ReadLittleLong(sb);
2910                         out->mins[0] = MSG_ReadLittleFloat(sb);
2911                         out->mins[1] = MSG_ReadLittleFloat(sb);
2912                         out->mins[2] = MSG_ReadLittleFloat(sb);
2913                         out->maxs[0] = MSG_ReadLittleFloat(sb);
2914                         out->maxs[1] = MSG_ReadLittleFloat(sb);
2915                         out->maxs[2] = MSG_ReadLittleFloat(sb);
2916                         out->firstsurface = MSG_ReadLittleLong(sb);
2917                         out->numsurfaces = MSG_ReadLittleLong(sb);
2918                 }
2919                 else
2920                 {
2921                         child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2922                         child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2923                         if (child[0] >= count)
2924                                 child[0] -= 65536;
2925                         if (child[1] >= count)
2926                                 child[1] -= 65536;
2927
2928                         out->mins[0] = MSG_ReadLittleShort(sb);
2929                         out->mins[1] = MSG_ReadLittleShort(sb);
2930                         out->mins[2] = MSG_ReadLittleShort(sb);
2931                         out->maxs[0] = MSG_ReadLittleShort(sb);
2932                         out->maxs[1] = MSG_ReadLittleShort(sb);
2933                         out->maxs[2] = MSG_ReadLittleShort(sb);
2934
2935                         out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2936                         out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2937                 }
2938
2939                 for (j=0 ; j<2 ; j++)
2940                 {
2941                         // LadyHavoc: this code supports broken bsp files produced by
2942                         // arguire qbsp which can produce more than 32768 nodes, any value
2943                         // below count is assumed to be a node number, any other value is
2944                         // assumed to be a leaf number
2945                         p = child[j];
2946                         if (p >= 0)
2947                         {
2948                                 if (p < loadmodel->brush.num_nodes)
2949                                         out->children[j] = loadmodel->brush.data_nodes + p;
2950                                 else
2951                                 {
2952                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2953                                         // map it to the solid leaf
2954                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2955                                 }
2956                         }
2957                         else
2958                         {
2959                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2960                                 p = -(p+1);
2961                                 if (p < loadmodel->brush.num_leafs)
2962                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2963                                 else
2964                                 {
2965                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2966                                         // map it to the solid leaf
2967                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2968                                 }
2969                         }
2970                 }
2971         }
2972
2973         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);        // sets nodes and leafs
2974 }
2975
2976 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2977 {
2978         mleaf_t *out;
2979         int i, j, count, p, firstmarksurface, nummarksurfaces;
2980         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2981
2982         if (sb->cursize % structsize)
2983                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2984         count = sb->cursize / structsize;
2985         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2986
2987         loadmodel->brush.data_leafs = out;
2988         loadmodel->brush.num_leafs = count;
2989         // get visleafs from the submodel data
2990         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2991         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2992         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2993         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2994
2995         // FIXME: this function could really benefit from some error checking
2996         for ( i=0 ; i<count ; i++, out++)
2997         {
2998                 out->contents = MSG_ReadLittleLong(sb);
2999
3000                 out->clusterindex = i - 1;
3001                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
3002                         out->clusterindex = -1;
3003
3004                 p = MSG_ReadLittleLong(sb);
3005                 // ignore visofs errors on leaf 0 (solid)
3006                 if (p >= 0 && out->clusterindex >= 0)
3007                 {
3008                         if (p >= loadmodel->brushq1.num_compressedpvs)
3009                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
3010                         else
3011                                 Mod_BSP_DecompressVis(loadmodel->brushq1.data_compressedpvs + p, loadmodel->brushq1.data_compressedpvs + loadmodel->brushq1.num_compressedpvs, loadmodel->brush.data_pvsclusters + out->clusterindex * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (out->clusterindex + 1) * loadmodel->brush.num_pvsclusterbytes);
3012                 }
3013
3014                 if (loadmodel->brush.isbsp2rmqe)
3015                 {
3016                         out->mins[0] = MSG_ReadLittleShort(sb);
3017                         out->mins[1] = MSG_ReadLittleShort(sb);
3018                         out->mins[2] = MSG_ReadLittleShort(sb);
3019                         out->maxs[0] = MSG_ReadLittleShort(sb);
3020                         out->maxs[1] = MSG_ReadLittleShort(sb);
3021                         out->maxs[2] = MSG_ReadLittleShort(sb);
3022         
3023                         firstmarksurface = MSG_ReadLittleLong(sb);
3024                         nummarksurfaces = MSG_ReadLittleLong(sb);
3025                 }
3026                 else if (loadmodel->brush.isbsp2)
3027                 {
3028                         out->mins[0] = MSG_ReadLittleFloat(sb);
3029                         out->mins[1] = MSG_ReadLittleFloat(sb);
3030                         out->mins[2] = MSG_ReadLittleFloat(sb);
3031                         out->maxs[0] = MSG_ReadLittleFloat(sb);
3032                         out->maxs[1] = MSG_ReadLittleFloat(sb);
3033                         out->maxs[2] = MSG_ReadLittleFloat(sb);
3034         
3035                         firstmarksurface = MSG_ReadLittleLong(sb);
3036                         nummarksurfaces = MSG_ReadLittleLong(sb);
3037                 }
3038                 else
3039                 {
3040                         out->mins[0] = MSG_ReadLittleShort(sb);
3041                         out->mins[1] = MSG_ReadLittleShort(sb);
3042                         out->mins[2] = MSG_ReadLittleShort(sb);
3043                         out->maxs[0] = MSG_ReadLittleShort(sb);
3044                         out->maxs[1] = MSG_ReadLittleShort(sb);
3045                         out->maxs[2] = MSG_ReadLittleShort(sb);
3046         
3047                         firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
3048                         nummarksurfaces  = (unsigned short)MSG_ReadLittleShort(sb);
3049                 }
3050
3051                 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
3052                 {
3053                         out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3054                         out->numleafsurfaces = nummarksurfaces;
3055                 }
3056                 else
3057                 {
3058                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3059                         out->firstleafsurface = NULL;
3060                         out->numleafsurfaces = 0;
3061                 }
3062
3063                 for (j = 0;j < 4;j++)
3064                         out->ambient_sound_level[j] = MSG_ReadByte(sb);
3065         }
3066 }
3067
3068 static qbool Mod_Q1BSP_CheckWaterAlphaSupport(void)
3069 {
3070         int i, j;
3071         mleaf_t *leaf;
3072         const unsigned char *pvs;
3073         // if there's no vis data, assume supported (because everything is visible all the time)
3074         if (!loadmodel->brush.data_pvsclusters)
3075                 return true;
3076         // check all liquid leafs to see if they can see into empty leafs, if any
3077         // can we can assume this map supports r_wateralpha
3078         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3079         {
3080                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3081                 {
3082                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3083                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
3084                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3085                                         return true;
3086                 }
3087         }
3088         return false;
3089 }
3090
3091 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3092 {
3093         mclipnode_t *out;
3094         int                     i, count;
3095         hull_t          *hull;
3096         int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3097
3098         if (sb->cursize % structsize)
3099                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3100         count = sb->cursize / structsize;
3101         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3102
3103         loadmodel->brushq1.clipnodes = out;
3104         loadmodel->brushq1.numclipnodes = count;
3105
3106         for (i = 1; i < MAX_MAP_HULLS; i++)
3107         {
3108                 hull = &loadmodel->brushq1.hulls[i];
3109                 hull->clipnodes = out;
3110                 hull->firstclipnode = 0;
3111                 hull->lastclipnode = count-1;
3112                 hull->planes = loadmodel->brush.data_planes;
3113                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3114                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3115                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3116                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3117                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3118                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3119                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3120         }
3121
3122         for (i=0 ; i<count ; i++, out++)
3123         {
3124                 out->planenum = MSG_ReadLittleLong(sb);
3125                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3126                         Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3127                 if (loadmodel->brush.isbsp2)
3128                 {
3129                         out->children[0] = MSG_ReadLittleLong(sb);
3130                         out->children[1] = MSG_ReadLittleLong(sb);
3131                         if (out->children[0] >= count)
3132                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3133                         if (out->children[1] >= count)
3134                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3135                 }
3136                 else
3137                 {
3138                         // LadyHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3139                         out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3140                         out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3141                         if (out->children[0] >= count)
3142                                 out->children[0] -= 65536;
3143                         if (out->children[1] >= count)
3144                                 out->children[1] -= 65536;
3145                 }
3146         }
3147 }
3148
3149 //Duplicate the drawing hull structure as a clipping hull
3150 static void Mod_Q1BSP_MakeHull0(void)
3151 {
3152         mnode_t         *in;
3153         mclipnode_t *out;
3154         int                     i;
3155         hull_t          *hull;
3156
3157         hull = &loadmodel->brushq1.hulls[0];
3158
3159         in = loadmodel->brush.data_nodes;
3160         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3161
3162         hull->clipnodes = out;
3163         hull->firstclipnode = 0;
3164         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3165         hull->planes = loadmodel->brush.data_planes;
3166
3167         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3168         {
3169                 out->planenum = in->plane - loadmodel->brush.data_planes;
3170                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3171                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3172         }
3173 }
3174
3175 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3176 {
3177         int i, j;
3178         int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3179
3180         if (sb->cursize % structsize)
3181                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3182         loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3183         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3184
3185         if (loadmodel->brush.isbsp2)
3186         {
3187                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3188                 {
3189                         j = MSG_ReadLittleLong(sb);
3190                         if (j < 0 || j >= loadmodel->num_surfaces)
3191                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3192                         loadmodel->brush.data_leafsurfaces[i] = j;
3193                 }
3194         }
3195         else
3196         {
3197                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3198                 {
3199                         j = (unsigned short) MSG_ReadLittleShort(sb);
3200                         if (j >= loadmodel->num_surfaces)
3201                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3202                         loadmodel->brush.data_leafsurfaces[i] = j;
3203                 }
3204         }
3205 }
3206
3207 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3208 {
3209         int             i;
3210         int structsize = 4;
3211
3212         if (sb->cursize % structsize)
3213                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3214         loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3215         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3216
3217         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3218                 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3219 }
3220
3221
3222 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3223 {
3224         int                     i;
3225         mplane_t        *out;
3226         int structsize = 20;
3227
3228         if (sb->cursize % structsize)
3229                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3230         loadmodel->brush.num_planes = sb->cursize / structsize;
3231         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3232
3233         for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3234         {
3235                 out->normal[0] = MSG_ReadLittleFloat(sb);
3236                 out->normal[1] = MSG_ReadLittleFloat(sb);
3237                 out->normal[2] = MSG_ReadLittleFloat(sb);
3238                 out->dist = MSG_ReadLittleFloat(sb);
3239                 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3240                 PlaneClassify(out);
3241         }
3242 }
3243
3244 // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
3245 static void Mod_Q1BSP_AssignNoShadowSkySurfaces(model_t *mod)
3246 {
3247         int surfaceindex;
3248         msurface_t *surface;
3249         vec3_t center;
3250         int contents;
3251         for (surfaceindex = mod->submodelsurfaces_start; surfaceindex < mod->submodelsurfaces_end;surfaceindex++)
3252         {
3253                 surface = mod->data_surfaces + surfaceindex;
3254                 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3255                 {
3256                         // check if the point behind the surface polygon is SOLID or SKY contents
3257                         VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
3258                         contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
3259                         if (!(contents & SUPERCONTENTS_SOLID))
3260                                 surface->texture = surface->texture->skynoshadowtexture;
3261                 }
3262         }
3263 }
3264
3265 static void Mod_Q1BSP_LoadMapBrushes(void)
3266 {
3267 #if 0
3268 // unfinished
3269         int submodel, numbrushes;
3270         qbool firstbrush;
3271         char *text, *maptext;
3272         char mapfilename[MAX_QPATH];
3273         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3274         strlcat (mapfilename, ".map", sizeof (mapfilename));
3275         maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3276         if (!maptext)
3277                 return;
3278         text = maptext;
3279         if (!COM_ParseToken_Simple(&data, false, false, true))
3280                 return; // error
3281         submodel = 0;
3282         for (;;)
3283         {
3284                 if (!COM_ParseToken_Simple(&data, false, false, true))
3285                         break;
3286                 if (com_token[0] != '{')
3287                         return; // error
3288                 // entity
3289                 firstbrush = true;
3290                 numbrushes = 0;
3291                 maxbrushes = 256;
3292                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3293                 for (;;)
3294                 {
3295                         if (!COM_ParseToken_Simple(&data, false, false, true))
3296                                 return; // error
3297                         if (com_token[0] == '}')
3298                                 break; // end of entity
3299                         if (com_token[0] == '{')
3300                         {
3301                                 // brush
3302                                 if (firstbrush)
3303                                 {
3304                                         if (submodel)
3305                                         {
3306                                                 if (submodel > loadmodel->brush.numsubmodels)
3307                                                 {
3308                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3309                                                         model = NULL;
3310                                                 }
3311                                                 else
3312                                                         model = loadmodel->brush.submodels[submodel];
3313                                         }
3314                                         else
3315                                                 model = loadmodel;
3316                                 }
3317                                 for (;;)
3318                                 {
3319                                         if (!COM_ParseToken_Simple(&data, false, false, true))
3320                                                 return; // error
3321                                         if (com_token[0] == '}')
3322                                                 break; // end of brush
3323                                         // each brush face should be this format:
3324                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3325                                         // FIXME: support hl .map format
3326                                         for (pointnum = 0;pointnum < 3;pointnum++)
3327                                         {
3328                                                 COM_ParseToken_Simple(&data, false, false, true);
3329                                                 for (componentnum = 0;componentnum < 3;componentnum++)
3330                                                 {
3331                                                         COM_ParseToken_Simple(&data, false, false, true);
3332                                                         point[pointnum][componentnum] = atof(com_token);
3333                                                 }
3334                                                 COM_ParseToken_Simple(&data, false, false, true);
3335                                         }
3336                                         COM_ParseToken_Simple(&data, false, false, true);
3337                                         strlcpy(facetexture, com_token, sizeof(facetexture));
3338                                         COM_ParseToken_Simple(&data, false, false, true);
3339                                         //scroll_s = atof(com_token);
3340                                         COM_ParseToken_Simple(&data, false, false, true);
3341                                         //scroll_t = atof(com_token);
3342                                         COM_ParseToken_Simple(&data, false, false, true);
3343                                         //rotate = atof(com_token);
3344                                         COM_ParseToken_Simple(&data, false, false, true);
3345                                         //scale_s = atof(com_token);
3346                                         COM_ParseToken_Simple(&data, false, false, true);
3347                                         //scale_t = atof(com_token);
3348                                         TriangleNormal(point[0], point[1], point[2], planenormal);
3349                                         VectorNormalizeDouble(planenormal);
3350                                         planedist = DotProduct(point[0], planenormal);
3351                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3352                                 }
3353                                 continue;
3354                         }
3355                 }
3356         }
3357 #endif
3358 }
3359
3360
3361 #define MAX_PORTALPOINTS 64
3362
3363 typedef struct portal_s
3364 {
3365         mplane_t plane;
3366         mnode_t *nodes[2];              // [0] = front side of plane
3367         struct portal_s *next[2];
3368         int numpoints;
3369         double points[3*MAX_PORTALPOINTS];
3370         struct portal_s *chain; // all portals are linked into a list
3371 }
3372 portal_t;
3373
3374 static memexpandablearray_t portalarray;
3375
3376 static void Mod_BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3377 {
3378         // process only nodes (leafs already had their box calculated)
3379         if (!node->plane)
3380                 return;
3381
3382         // calculate children first
3383         Mod_BSP_RecursiveRecalcNodeBBox(node->children[0]);
3384         Mod_BSP_RecursiveRecalcNodeBBox(node->children[1]);
3385
3386         // make combined bounding box from children
3387         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3388         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3389         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3390         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3391         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3392         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3393 }
3394
3395 static void Mod_BSP_FinalizePortals(void)
3396 {
3397         int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3398         portal_t *p;
3399         mportal_t *portal;
3400         mvertex_t *point;
3401         mleaf_t *leaf, *endleaf;
3402
3403         // tally up portal and point counts and recalculate bounding boxes for all
3404         // leafs (because qbsp is very sloppy)
3405         leaf = loadmodel->brush.data_leafs;
3406         endleaf = leaf + loadmodel->brush.num_leafs;
3407         if (mod_recalculatenodeboxes.integer)
3408         {
3409                 for (;leaf < endleaf;leaf++)
3410                 {
3411                         VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
3412                         VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3413                 }
3414         }
3415         numportals = 0;
3416         numpoints = 0;
3417         for (portalindex = 0;portalindex < portalrange;portalindex++)
3418         {
3419                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3420                 if (!p)
3421                         continue;
3422                 // note: this check must match the one below or it will usually corrupt memory
3423                 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3424                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3425                 {
3426                         numportals += 2;
3427                         numpoints += p->numpoints * 2;
3428                 }
3429         }
3430         loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3431         loadmodel->brush.num_portals = numportals;
3432         loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3433         loadmodel->brush.num_portalpoints = numpoints;
3434         // clear all leaf portal chains
3435         for (i = 0;i < loadmodel->brush.num_leafs;i++)
3436                 loadmodel->brush.data_leafs[i].portals = NULL;
3437         // process all portals in the global portal chain, while freeing them
3438         portal = loadmodel->brush.data_portals;
3439         point = loadmodel->brush.data_portalpoints;
3440         for (portalindex = 0;portalindex < portalrange;portalindex++)
3441         {
3442                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3443                 if (!p)
3444                         continue;
3445                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3446                 {
3447                         // note: this check must match the one above or it will usually corrupt memory
3448                         // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3449                         if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3450                         {
3451                                 // first make the back to front portal(forward portal)
3452                                 portal->points = point;
3453                                 portal->numpoints = p->numpoints;
3454                                 portal->plane.dist = p->plane.dist;
3455                                 VectorCopy(p->plane.normal, portal->plane.normal);
3456                                 portal->here = (mleaf_t *)p->nodes[1];
3457                                 portal->past = (mleaf_t *)p->nodes[0];
3458                                 // copy points
3459                                 for (j = 0;j < portal->numpoints;j++)
3460                                 {
3461                                         VectorCopy(p->points + j*3, point->position);
3462                                         point++;
3463                                 }
3464                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3465                                 PlaneClassify(&portal->plane);
3466
3467                                 // link into leaf's portal chain
3468                                 portal->next = portal->here->portals;
3469                                 portal->here->portals = portal;
3470
3471                                 // advance to next portal
3472                                 portal++;
3473
3474                                 // then make the front to back portal(backward portal)
3475                                 portal->points = point;
3476                                 portal->numpoints = p->numpoints;
3477                                 portal->plane.dist = -p->plane.dist;
3478                                 VectorNegate(p->plane.normal, portal->plane.normal);
3479                                 portal->here = (mleaf_t *)p->nodes[0];
3480                                 portal->past = (mleaf_t *)p->nodes[1];
3481                                 // copy points
3482                                 for (j = portal->numpoints - 1;j >= 0;j--)
3483                                 {
3484                                         VectorCopy(p->points + j*3, point->position);
3485                                         point++;
3486                                 }
3487                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3488                                 PlaneClassify(&portal->plane);
3489
3490                                 // link into leaf's portal chain
3491                                 portal->next = portal->here->portals;
3492                                 portal->here->portals = portal;
3493
3494                                 // advance to next portal
3495                                 portal++;
3496                         }
3497                         // add the portal's polygon points to the leaf bounding boxes
3498                         if (mod_recalculatenodeboxes.integer)
3499                         {
3500                                 for (i = 0;i < 2;i++)
3501                                 {
3502                                         leaf = (mleaf_t *)p->nodes[i];
3503                                         for (j = 0;j < p->numpoints;j++)
3504                                         {
3505                                                 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3506                                                 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3507                                                 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3508                                                 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3509                                                 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3510                                                 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3511                                         }
3512                                 }
3513                         }
3514                 }
3515         }
3516         // now recalculate the node bounding boxes from the leafs
3517         if (mod_recalculatenodeboxes.integer)
3518                 Mod_BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3519 }
3520
3521 /*
3522 =============
3523 AddPortalToNodes
3524 =============
3525 */
3526 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3527 {
3528         if (!front)
3529                 Host_Error("AddPortalToNodes: NULL front node");
3530         if (!back)
3531                 Host_Error("AddPortalToNodes: NULL back node");
3532         if (p->nodes[0] || p->nodes[1])
3533                 Host_Error("AddPortalToNodes: already included");
3534         // note: front == back is handled gracefully, because leaf 0 is the shared solid leaf, it can often have portals with the same leaf on both sides
3535
3536         p->nodes[0] = front;
3537         p->next[0] = (portal_t *)front->portals;
3538         front->portals = (mportal_t *)p;
3539
3540         p->nodes[1] = back;
3541         p->next[1] = (portal_t *)back->portals;
3542         back->portals = (mportal_t *)p;
3543 }
3544
3545 /*
3546 =============
3547 RemovePortalFromNode
3548 =============
3549 */
3550 static void RemovePortalFromNodes(portal_t *portal)
3551 {
3552         int i;
3553         mnode_t *node;
3554         void **portalpointer;
3555         portal_t *t;
3556         for (i = 0;i < 2;i++)
3557         {
3558                 node = portal->nodes[i];
3559
3560                 portalpointer = (void **) &node->portals;
3561                 while (1)
3562                 {
3563                         t = (portal_t *)*portalpointer;
3564                         if (!t)
3565                                 Host_Error("RemovePortalFromNodes: portal not in leaf");
3566
3567                         if (t == portal)
3568                         {
3569                                 if (portal->nodes[0] == node)
3570                                 {
3571                                         *portalpointer = portal->next[0];
3572                                         portal->nodes[0] = NULL;
3573                                 }
3574                                 else if (portal->nodes[1] == node)
3575                                 {
3576                                         *portalpointer = portal->next[1];
3577                                         portal->nodes[1] = NULL;
3578                                 }
3579                                 else
3580                                         Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3581                                 break;
3582                         }
3583
3584                         if (t->nodes[0] == node)
3585                                 portalpointer = (void **) &t->next[0];
3586                         else if (t->nodes[1] == node)
3587                                 portalpointer = (void **) &t->next[1];
3588                         else
3589                                 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3590                 }
3591         }
3592 }
3593
3594 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3595 static double *portalpointsbuffer;
3596 static int portalpointsbufferoffset;
3597 static int portalpointsbuffersize;
3598 static void Mod_BSP_RecursiveNodePortals(mnode_t *node)
3599 {
3600         int i, side;
3601         mnode_t *front, *back, *other_node;
3602         mplane_t clipplane, *plane;
3603         portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3604         int numfrontpoints, numbackpoints;
3605         double *frontpoints, *backpoints;
3606
3607         // if a leaf, we're done
3608         if (!node->plane)
3609                 return;
3610
3611         // get some space for our clipping operations to use
3612         if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3613         {
3614                 portalpointsbuffersize = portalpointsbufferoffset * 2;
3615                 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3616         }
3617         frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3618         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3619         backpoints = portalpointsbuffer + portalpointsbufferoffset;
3620         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3621
3622         plane = node->plane;
3623
3624         front = node->children[0];
3625         back = node->children[1];
3626         if (front == back)
3627                 Host_Error("Mod_BSP_RecursiveNodePortals: corrupt node hierarchy");
3628
3629         // create the new portal by generating a polygon for the node plane,
3630         // and clipping it by all of the other portals(which came from nodes above this one)
3631         nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3632         nodeportal->plane = *plane;
3633
3634         // TODO: calculate node bounding boxes during recursion and calculate a maximum plane size accordingly to improve precision (as most maps do not need 1 billion unit plane polygons)
3635         PolygonD_QuadForPlane(nodeportal->points, nodeportal->plane.normal[0], nodeportal->plane.normal[1], nodeportal->plane.normal[2], nodeportal->plane.dist, 1024.0*1024.0*1024.0);
3636         nodeportal->numpoints = 4;
3637
3638         for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3639         {
3640                 clipplane = portal->plane;
3641                 if (portal->nodes[0] == portal->nodes[1])
3642                         Host_Error("Mod_BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3643                 if (portal->nodes[0] == node)
3644                         side = 0;
3645                 else if (portal->nodes[1] == node)
3646                 {
3647                         clipplane.dist = -clipplane.dist;
3648                         VectorNegate(clipplane.normal, clipplane.normal);
3649                         side = 1;
3650                 }
3651                 else
3652                 {
3653                         Host_Error("Mod_BSP_RecursiveNodePortals: mislinked portal");
3654                         side = 0; // hush warning
3655                 }
3656
3657                 for (i = 0;i < nodeportal->numpoints*3;i++)
3658                         frontpoints[i] = nodeportal->points[i];
3659                 PolygonD_Divide(nodeportal->numpoints, frontpoints, clipplane.normal[0], clipplane.normal[1], clipplane.normal[2], clipplane.dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, nodeportal->points, &nodeportal->numpoints, 0, NULL, NULL, NULL);
3660                 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3661                         break;
3662         }
3663
3664         if (nodeportal->numpoints < 3)
3665         {
3666                 Con_Print(CON_WARN "Mod_BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3667                 nodeportal->numpoints = 0;
3668         }
3669         else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3670         {
3671                 Con_Print(CON_WARN "Mod_BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3672                 nodeportal->numpoints = 0;
3673         }
3674
3675         AddPortalToNodes(nodeportal, front, back);
3676
3677         // split the portals of this node along this node's plane and assign them to the children of this node
3678         // (migrating the portals downward through the tree)
3679         for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3680         {
3681                 if (portal->nodes[0] == portal->nodes[1])
3682                         Host_Error("Mod_BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3683                 if (portal->nodes[0] == node)
3684                         side = 0;
3685                 else if (portal->nodes[1] == node)
3686                         side = 1;
3687                 else
3688                 {
3689                         Host_Error("Mod_BSP_RecursiveNodePortals: mislinked portal");
3690                         side = 0; // hush warning
3691                 }
3692                 nextportal = portal->next[side];
3693                 if (!portal->numpoints)
3694                         continue;
3695
3696                 other_node = portal->nodes[!side];
3697                 RemovePortalFromNodes(portal);
3698
3699                 // cut the portal into two portals, one on each side of the node plane
3700                 PolygonD_Divide(portal->numpoints, portal->points, plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, frontpoints, &numfrontpoints, MAX_PORTALPOINTS, backpoints, &numbackpoints, NULL);
3701
3702                 if (!numfrontpoints)
3703                 {
3704                         if (side == 0)
3705                                 AddPortalToNodes(portal, back, other_node);
3706                         else
3707                                 AddPortalToNodes(portal, other_node, back);
3708                         continue;
3709                 }
3710                 if (!numbackpoints)
3711                 {
3712                         if (side == 0)
3713                                 AddPortalToNodes(portal, front, other_node);
3714                         else
3715                                 AddPortalToNodes(portal, other_node, front);
3716                         continue;
3717                 }
3718
3719                 // the portal is split
3720                 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3721                 temp = splitportal->chain;
3722                 *splitportal = *portal;
3723                 splitportal->chain = temp;
3724                 for (i = 0;i < numbackpoints*3;i++)
3725                         splitportal->points[i] = backpoints[i];
3726                 splitportal->numpoints = numbackpoints;
3727                 for (i = 0;i < numfrontpoints*3;i++)
3728                         portal->points[i] = frontpoints[i];
3729                 portal->numpoints = numfrontpoints;
3730
3731                 if (side == 0)
3732                 {
3733                         AddPortalToNodes(portal, front, other_node);
3734                         AddPortalToNodes(splitportal, back, other_node);
3735                 }
3736                 else
3737                 {
3738                         AddPortalToNodes(portal, other_node, front);
3739                         AddPortalToNodes(splitportal, other_node, back);
3740                 }
3741         }
3742
3743         Mod_BSP_RecursiveNodePortals(front);
3744         Mod_BSP_RecursiveNodePortals(back);
3745
3746         portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3747 }
3748
3749 static void Mod_BSP_MakePortals(void)
3750 {
3751         Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3752         portalpointsbufferoffset = 0;
3753         portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3754         portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3755         Mod_BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3756         Mem_Free(portalpointsbuffer);
3757         portalpointsbuffer = NULL;
3758         portalpointsbufferoffset = 0;
3759         portalpointsbuffersize = 0;
3760         Mod_BSP_FinalizePortals();
3761         Mem_ExpandableArray_FreeArray(&portalarray);
3762 }
3763
3764 //Returns PVS data for a given point
3765 //(note: can return NULL)
3766 static unsigned char *Mod_BSP_GetPVS(model_t *model, const vec3_t p)
3767 {
3768         mnode_t *node;
3769         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3770         while (node->plane)
3771                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3772         if (((mleaf_t *)node)->clusterindex >= 0)
3773                 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3774         else
3775                 return NULL;
3776 }
3777
3778 static void Mod_BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
3779 {
3780         while (node->plane)
3781         {
3782                 float d = PlaneDiff(org, node->plane);
3783                 if (d > radius)
3784                         node = node->children[0];
3785                 else if (d < -radius)
3786                         node = node->children[1];
3787                 else
3788                 {
3789                         // go down both sides
3790                         Mod_BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3791                         node = node->children[1];
3792                 }
3793         }
3794         // if this leaf is in a cluster, accumulate the pvs bits
3795         if (((mleaf_t *)node)->clusterindex >= 0)
3796         {
3797                 int i;
3798                 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3799                 for (i = 0;i < pvsbytes;i++)
3800                         pvsbuffer[i] |= pvs[i];
3801         }
3802 }
3803
3804 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3805 //of the given point.
3806 static int Mod_BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qbool merge)
3807 {
3808         int bytes = model->brush.num_pvsclusterbytes;
3809         bytes = min(bytes, pvsbufferlength);
3810         if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_BSP_GetPVS(model, org))
3811         {
3812                 memset(pvsbuffer, 0xFF, bytes);
3813                 return bytes;
3814         }
3815         if (!merge)
3816                 memset(pvsbuffer, 0, bytes);
3817         Mod_BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3818         return bytes;
3819 }
3820
3821 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3822 {
3823         vec3_t size;
3824         const hull_t *hull;
3825
3826         VectorSubtract(inmaxs, inmins, size);
3827         if (size[0] < mod_q1bsp_zero_hullsize_cutoff.value)
3828                 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3829         else if (cmodel->brush.ishlbsp)
3830         {
3831                 if (size[0] <= 32)
3832                 {
3833                         if (size[2] < 54) // pick the nearest of 36 or 72
3834                                 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3835                         else
3836                                 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3837                 }
3838                 else
3839                         hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3840         }
3841         else
3842         {
3843                 if (size[0] <= 32)
3844                         hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3845                 else
3846                         hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3847         }
3848         VectorCopy(inmins, outmins);
3849         VectorAdd(inmins, hull->clip_size, outmaxs);
3850 }
3851
3852 void Mod_CollisionBIH_TraceLineAgainstSurfaces(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask);
3853
3854 void Mod_2PSB_Load(model_t *mod, void *buffer, void *bufferend)
3855 {
3856         mod->brush.isbsp2 = true;
3857         mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3858         mod->modeldatatypestring = "Q1BSP2rmqe";
3859         Mod_Q1BSP_Load(mod, buffer, bufferend);
3860 }
3861
3862 void Mod_BSP2_Load(model_t *mod, void *buffer, void *bufferend)
3863 {
3864         mod->brush.isbsp2 = true;
3865         mod->modeldatatypestring = "Q1BSP2";
3866         Mod_Q1BSP_Load(mod, buffer, bufferend);
3867 }
3868
3869 void Mod_HLBSP_Load(model_t *mod, void *buffer, void *bufferend)
3870 {
3871         mod->brush.ishlbsp = true;
3872         mod->modeldatatypestring = "HLBSP";
3873         Mod_Q1BSP_Load(mod, buffer, bufferend);
3874 }
3875
3876 void Mod_Q1BSP_Load(model_t *mod, void *buffer, void *bufferend)
3877 {
3878         int i, j, k;
3879         sizebuf_t lumpsb[HEADER_LUMPS];
3880         mmodel_t *bm;
3881         float dist, modelyawradius, modelradius;
3882         msurface_t *surface;
3883         hullinfo_t hullinfo;
3884         int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3885         model_brush_lightstyleinfo_t styleinfo[256];
3886         unsigned char *datapointer;
3887         sizebuf_t sb;
3888
3889         MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3890
3891         mod->type = mod_brushq1;
3892
3893         mod->brush.skymasking = true;
3894         i = MSG_ReadLittleLong(&sb);
3895
3896         if(!mod->modeldatatypestring)
3897                 mod->modeldatatypestring = "Q1BSP";
3898
3899 // fill in hull info
3900         VectorClear (hullinfo.hullsizes[0][0]);
3901         VectorClear (hullinfo.hullsizes[0][1]);
3902         if (mod->brush.ishlbsp)
3903         {
3904                 hullinfo.filehulls = 4;
3905                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3906                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3907                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3908                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3909                 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3910                 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3911         }
3912         else
3913         {
3914                 hullinfo.filehulls = 4;
3915                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3916                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3917                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3918                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3919         }
3920
3921 // read lumps
3922         for (i = 0; i < HEADER_LUMPS; i++)
3923         {
3924                 int offset = MSG_ReadLittleLong(&sb);
3925                 int size = MSG_ReadLittleLong(&sb);
3926                 if (offset < 0 || offset + size > sb.cursize)
3927                         Host_Error("Mod_Q1BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
3928                 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3929         }
3930
3931         mod->soundfromcenter = true;
3932         mod->TraceBox = Mod_Q1BSP_TraceBox;
3933         mod->TraceLine = Mod_Q1BSP_TraceLine;
3934         mod->TracePoint = Mod_Q1BSP_TracePoint;
3935         mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3936         mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3937         mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3938         mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3939         mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3940         mod->brush.GetPVS = Mod_BSP_GetPVS;
3941         mod->brush.FatPVS = Mod_BSP_FatPVS;
3942         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
3943         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
3944         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
3945         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
3946         mod->brush.LightPoint = Mod_BSP_LightPoint;
3947         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
3948         mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3949         mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3950         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
3951         mod->Draw = R_Mod_Draw;
3952         mod->DrawDepth = R_Mod_DrawDepth;
3953         mod->DrawDebug = R_Mod_DrawDebug;
3954         mod->DrawPrepass = R_Mod_DrawPrepass;
3955         mod->GetLightInfo = R_Mod_GetLightInfo;
3956         mod->CompileShadowMap = R_Mod_CompileShadowMap;
3957         mod->DrawShadowMap = R_Mod_DrawShadowMap;
3958         mod->DrawLight = R_Mod_DrawLight;
3959
3960 // load into heap
3961
3962         mod->brush.qw_md4sum = 0;
3963         mod->brush.qw_md4sum2 = 0;
3964         for (i = 0;i < HEADER_LUMPS;i++)
3965         {
3966                 int temp;
3967                 if (i == LUMP_ENTITIES)
3968                         continue;
3969                 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3970                 mod->brush.qw_md4sum ^= LittleLong(temp);
3971                 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3972                         continue;
3973                 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3974         }
3975
3976         Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3977         Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3978         Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3979         Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3980         Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3981         Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3982         Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3983         Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3984         Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3985         Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3986         Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3987         // load submodels before leafs because they contain the number of vis leafs
3988         Mod_BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3989         Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3990         Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3991         Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3992
3993         for (i = 0; i < HEADER_LUMPS; i++)
3994                 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3995                         Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3996
3997         // check if the map supports transparent water rendering
3998         loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3999
4000         // we don't need the compressed pvs data anymore
4001         if (mod->brushq1.data_compressedpvs)
4002                 Mem_Free(mod->brushq1.data_compressedpvs);
4003         mod->brushq1.data_compressedpvs = NULL;
4004         mod->brushq1.num_compressedpvs = 0;
4005
4006         Mod_Q1BSP_MakeHull0();
4007         if (mod_bsp_portalize.integer)
4008                 Mod_BSP_MakePortals();
4009
4010         mod->numframes = 2;             // regular and alternate animation
4011         mod->numskins = 1;
4012
4013         if (loadmodel->brush.numsubmodels)
4014                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
4015
4016         // LadyHavoc: to clear the fog around the original quake submodel code, I
4017         // will explain:
4018         // first of all, some background info on the submodels:
4019         // model 0 is the map model (the world, named maps/e1m1.bsp for example)
4020         // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
4021         // now the weird for loop itself:
4022         // the loop functions in an odd way, on each iteration it sets up the
4023         // current 'mod' model (which despite the confusing code IS the model of
4024         // the number i), at the end of the loop it duplicates the model to become
4025         // the next submodel, and loops back to set up the new submodel.
4026
4027         // LadyHavoc: now the explanation of my sane way (which works identically):
4028         // set up the world model, then on each submodel copy from the world model
4029         // and set up the submodel with the respective model info.
4030         totalstylesurfaces = 0;
4031         totalstyles = 0;
4032         for (i = 0;i < mod->brush.numsubmodels;i++)
4033         {
4034                 memset(stylecounts, 0, sizeof(stylecounts));
4035                 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4036                 {
4037                         surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4038                         for (j = 0;j < MAXLIGHTMAPS;j++)
4039                                 stylecounts[surface->lightmapinfo->styles[j]]++;
4040                 }
4041                 for (k = 0;k < 255;k++)
4042                 {
4043                         totalstyles++;
4044                         if (stylecounts[k])
4045                                 totalstylesurfaces += stylecounts[k];
4046                 }
4047         }
4048         datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4049         mod->modelsurfaces_sorted = (int*)datapointer;datapointer += mod->num_surfaces * sizeof(int);
4050         for (i = 0;i < mod->brush.numsubmodels;i++)
4051         {
4052                 // LadyHavoc: this code was originally at the end of this loop, but
4053                 // has been transformed to something more readable at the start here.
4054
4055                 if (i > 0)
4056                 {
4057                         char name[10];
4058                         // duplicate the basic information
4059                         dpsnprintf(name, sizeof(name), "*%i", i);
4060                         mod = Mod_FindName(name, loadmodel->name);
4061                         // copy the base model to this one
4062                         *mod = *loadmodel;
4063                         // rename the clone back to its proper name
4064                         strlcpy(mod->name, name, sizeof(mod->name));
4065                         mod->brush.parentmodel = loadmodel;
4066                         // textures and memory belong to the main model
4067                         mod->texturepool = NULL;
4068                         mod->mempool = NULL;
4069                         mod->brush.GetPVS = NULL;
4070                         mod->brush.FatPVS = NULL;
4071                         mod->brush.BoxTouchingPVS = NULL;
4072                         mod->brush.BoxTouchingLeafPVS = NULL;
4073                         mod->brush.BoxTouchingVisibleLeafs = NULL;
4074                         mod->brush.FindBoxClusters = NULL;
4075                         mod->brush.LightPoint = NULL;
4076                         mod->brush.AmbientSoundLevelsForPoint = NULL;
4077                 }
4078
4079                 mod->brush.submodel = i;
4080
4081                 if (loadmodel->brush.submodels)
4082                         loadmodel->brush.submodels[i] = mod;
4083
4084                 bm = &mod->brushq1.submodels[i];
4085
4086                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4087                 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4088                 {
4089                         mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4090                         mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4091                 }
4092
4093                 mod->submodelsurfaces_start = bm->firstface;
4094                 mod->submodelsurfaces_end = bm->firstface + bm->numfaces;
4095
4096                 // set node/leaf parents for this submodel
4097                 Mod_BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4098
4099                 // this has to occur after hull info has been set, as it uses Mod_Q1BSP_PointSuperContents
4100                 Mod_Q1BSP_AssignNoShadowSkySurfaces(mod);
4101
4102                 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4103                 // (previously this code measured the radius of the vertices of surfaces in the submodel, but that broke submodels that contain only CLIP brushes, which do not produce surfaces)
4104                 VectorCopy(bm->mins, mod->normalmins);
4105                 VectorCopy(bm->maxs, mod->normalmaxs);
4106                 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4107                 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4108                 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4109                 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4110                 modelradius = modelyawradius + modelradius * modelradius;
4111                 modelyawradius = sqrt(modelyawradius);
4112                 modelradius = sqrt(modelradius);
4113                 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4114                 mod->yawmins[2] = mod->normalmins[2];
4115                 mod->yawmaxs[0] = mod->yawmaxs[1] =  modelyawradius;
4116                 mod->yawmaxs[2] = mod->normalmaxs[2];
4117                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4118                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] =  modelradius;
4119                 mod->radius = modelradius;
4120                 mod->radius2 = modelradius * modelradius;
4121
4122                 Mod_SetDrawSkyAndWater(mod);
4123
4124                 if (mod->submodelsurfaces_start < mod->submodelsurfaces_end)
4125                 {
4126                         // build lightstyle update chains
4127                         // (used to rapidly mark lightmapupdateflags on many surfaces
4128                         // when d_lightstylevalue changes)
4129                         memset(stylecounts, 0, sizeof(stylecounts));
4130                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
4131                                 for (j = 0;j < MAXLIGHTMAPS;j++)
4132                                         stylecounts[mod->data_surfaces[k].lightmapinfo->styles[j]]++;
4133                         mod->brushq1.num_lightstyles = 0;
4134                         for (k = 0;k < 255;k++)
4135                         {
4136                                 if (stylecounts[k])
4137                                 {
4138                                         styleinfo[mod->brushq1.num_lightstyles].style = k;
4139                                         styleinfo[mod->brushq1.num_lightstyles].value = 0;
4140                                         styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4141                                         styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4142                                         remapstyles[k] = mod->brushq1.num_lightstyles;
4143                                         mod->brushq1.num_lightstyles++;
4144                                 }
4145                         }
4146                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
4147                         {
4148                                 surface = mod->data_surfaces + k;
4149                                 for (j = 0;j < MAXLIGHTMAPS;j++)
4150                                 {
4151                                         if (surface->lightmapinfo->styles[j] != 255)
4152                                         {
4153                                                 int r = remapstyles[surface->lightmapinfo->styles[j]];
4154                                                 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = k;
4155                                         }
4156                                 }
4157                         }
4158                         mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4159                         memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4160                 }
4161                 else
4162                 {
4163                         // LadyHavoc: empty submodel(lacrima.bsp has such a glitch)
4164                         Con_Printf(CON_WARN "warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4165                 }
4166                 //mod->brushq1.num_visleafs = bm->visleafs;
4167
4168                 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4169                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4170
4171                 if (mod_q1bsp_polygoncollisions.integer)
4172                 {
4173                         mod->collision_bih = mod->render_bih;
4174                         // point traces and contents checks still use the bsp tree
4175                         mod->TraceLine = Mod_CollisionBIH_TraceLine;
4176                         mod->TraceBox = Mod_CollisionBIH_TraceBox;
4177                         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4178                         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4179                 }
4180
4181                 // generate VBOs and other shared data before cloning submodels
4182                 if (i == 0)
4183                 {
4184                         Mod_BuildVBOs();
4185                         Mod_Q1BSP_LoadMapBrushes();
4186                         //Mod_Q1BSP_ProcessLightList();
4187                 }
4188         }
4189         mod = loadmodel;
4190
4191         // make the model surface list (used by shadowing/lighting)
4192         Mod_MakeSortedSurfaces(loadmodel);
4193
4194         Con_DPrintf("Stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
4195 }
4196
4197 int Mod_Q2BSP_SuperContentsFromNativeContents(int nativecontents)
4198 {
4199         int supercontents = 0;
4200         if (nativecontents & CONTENTSQ2_SOLID)
4201                 supercontents |= SUPERCONTENTS_SOLID;
4202         if (nativecontents & CONTENTSQ2_WATER)
4203                 supercontents |= SUPERCONTENTS_WATER;
4204         if (nativecontents & CONTENTSQ2_SLIME)
4205                 supercontents |= SUPERCONTENTS_SLIME;
4206         if (nativecontents & CONTENTSQ2_LAVA)
4207                 supercontents |= SUPERCONTENTS_LAVA;
4208         if (nativecontents & CONTENTSQ2_MONSTER)
4209                 supercontents |= SUPERCONTENTS_BODY;
4210         if (nativecontents & CONTENTSQ2_DEADMONSTER)
4211                 supercontents |= SUPERCONTENTS_CORPSE;
4212         if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4213                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4214         if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4215                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4216         if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4217                 supercontents |= SUPERCONTENTS_OPAQUE;
4218         return supercontents;
4219 }
4220
4221 int Mod_Q2BSP_NativeContentsFromSuperContents(int supercontents)
4222 {
4223         int nativecontents = 0;
4224         if (supercontents & SUPERCONTENTS_SOLID)
4225                 nativecontents |= CONTENTSQ2_SOLID;
4226         if (supercontents & SUPERCONTENTS_WATER)
4227                 nativecontents |= CONTENTSQ2_WATER;
4228         if (supercontents & SUPERCONTENTS_SLIME)
4229                 nativecontents |= CONTENTSQ2_SLIME;
4230         if (supercontents & SUPERCONTENTS_LAVA)
4231                 nativecontents |= CONTENTSQ2_LAVA;
4232         if (supercontents & SUPERCONTENTS_BODY)
4233                 nativecontents |= CONTENTSQ2_MONSTER;
4234         if (supercontents & SUPERCONTENTS_CORPSE)
4235                 nativecontents |= CONTENTSQ2_DEADMONSTER;
4236         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4237                 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4238         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4239                 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4240         if (!(supercontents & SUPERCONTENTS_OPAQUE))
4241                 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4242         return nativecontents;
4243 }
4244
4245 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4246 {
4247         int i, count;
4248         loadmodel->brushq1.num_compressedpvs = 0;
4249         loadmodel->brushq1.data_compressedpvs = NULL;
4250         loadmodel->brush.num_pvsclusters = 0;
4251         loadmodel->brush.num_pvsclusterbytes = 0;
4252         loadmodel->brush.data_pvsclusters = NULL;
4253
4254         if (!sb->cursize)
4255                 return;
4256
4257         count = MSG_ReadLittleLong(sb);
4258         loadmodel->brush.num_pvsclusters = count;
4259         loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4260         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4261         for (i = 0;i < count;i++)
4262         {
4263                 int pvsofs = MSG_ReadLittleLong(sb);
4264                 /*int phsofs = */MSG_ReadLittleLong(sb);
4265                 // decompress the vis data for this cluster
4266                 // (note this accesses the underlying data store of sb, which is kind of evil)
4267                 Mod_BSP_DecompressVis(sb->data + pvsofs, sb->data + sb->cursize, loadmodel->brush.data_pvsclusters + i * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (i+1) * loadmodel->brush.num_pvsclusterbytes);
4268         }
4269         // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4270         sb->readcount = sb->cursize;
4271 }
4272
4273 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4274 {
4275         int                     i, j, count, p, child[2];
4276         mnode_t         *out;
4277         int structsize = 28;
4278
4279         if (sb->cursize % structsize)
4280                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4281         count = sb->cursize / structsize;
4282         if (count == 0)
4283                 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4284         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4285
4286         loadmodel->brush.data_nodes = out;
4287         loadmodel->brush.num_nodes = count;
4288
4289         for ( i=0 ; i<count ; i++, out++)
4290         {
4291                 p = MSG_ReadLittleLong(sb);
4292                 out->plane = loadmodel->brush.data_planes + p;
4293                 child[0] = MSG_ReadLittleLong(sb);
4294                 child[1] = MSG_ReadLittleLong(sb);
4295                 out->mins[0] = MSG_ReadLittleShort(sb);
4296                 out->mins[1] = MSG_ReadLittleShort(sb);
4297                 out->mins[2] = MSG_ReadLittleShort(sb);
4298                 out->maxs[0] = MSG_ReadLittleShort(sb);
4299                 out->maxs[1] = MSG_ReadLittleShort(sb);
4300                 out->maxs[2] = MSG_ReadLittleShort(sb);
4301                 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4302                 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4303                 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4304                 {
4305                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4306                         out->firstsurface = 0;
4307                         out->numsurfaces = 0;
4308                 }
4309                 for (j=0 ; j<2 ; j++)
4310                 {
4311                         p = child[j];
4312                         if (p >= 0)
4313                         {
4314                                 if (p < loadmodel->brush.num_nodes)
4315                                         out->children[j] = loadmodel->brush.data_nodes + p;
4316                                 else
4317                                 {
4318                                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4319                                         // map it to the solid leaf
4320                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4321                                 }
4322                         }
4323                         else
4324                         {
4325                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4326                                 p = -(p+1);
4327                                 if (p < loadmodel->brush.num_leafs)
4328                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4329                                 else
4330                                 {
4331                                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4332                                         // map it to the solid leaf
4333                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4334                                 }
4335                         }
4336                 }
4337         }
4338
4339         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);        // sets nodes and leafs
4340 }
4341
4342 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4343 {
4344         mtexinfo_t *out;
4345         int i, l, count;
4346         int structsize = 76;
4347         int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4348         char filename[MAX_QPATH];
4349
4350         if (sb->cursize % structsize)
4351                 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4352         count = sb->cursize / structsize;
4353         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4354         loadmodel->brushq1.texinfo = out;
4355         loadmodel->brushq1.numtexinfo = count;
4356         loadmodel->num_texturesperskin = 0;
4357         loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4358
4359         for (i = 0;i < count;i++, out++)
4360         {
4361                 int j, k;
4362                 for (k = 0;k < 2;k++)
4363                         for (j = 0;j < 4;j++)
4364                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4365
4366                 out->q2flags = MSG_ReadLittleLong(sb);
4367                 out->q2value = MSG_ReadLittleLong(sb);
4368                 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4369                 out->q2texture[31] = 0; // make absolutely sure it is terminated
4370                 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4371
4372                 // find an existing match for the texture if possible
4373                 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4374                 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4375                         if (!strcmp(filename, loadmodel->data_textures[j].name)
4376                          && out->q2flags == loadmodel->data_textures[j].q2flags
4377                          && out->q2value == loadmodel->data_textures[j].q2value)
4378                                 break;
4379                 // if we don't find the texture, store the new texture
4380                 if (j == loadmodel->num_texturesperskin)
4381                 {
4382                         if (loadmodel->num_texturesperskin < maxtextures)
4383                         {
4384                                 texture_t *tx = loadmodel->data_textures + j;
4385                                 int q2flags = out->q2flags;
4386                                 unsigned char *walfile = NULL;
4387                                 fs_offset_t walfilesize = 0;
4388                                 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
4389                                 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4390                                 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4391                                 if (walfile)
4392                                 {
4393                                         int w, h;
4394                                         LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4395                                         tx->width = w;
4396                                         tx->height = h;
4397                                         Mem_Free(walfile);
4398                                 }
4399                                 else
4400                                 {
4401                                         tx->width = 16;
4402                                         tx->height = 16;
4403                                 }
4404                                 tx->q2flags = out->q2flags;
4405                                 tx->q2value = out->q2value;
4406                                 // also modify the texture to have the correct contents and such based on flags
4407                                 // note that we create multiple texture_t structures if q2flags differs
4408                                 if (q2flags & Q2SURF_LIGHT)
4409                                 {
4410                                         // doesn't mean anything to us
4411                                 }
4412                                 if (q2flags & Q2SURF_SLICK)
4413                                 {
4414                                         // would be nice to support...
4415                                 }
4416                                 if (q2flags & Q2SURF_SKY)
4417                                 {
4418                                         // sky is a rather specific thing
4419                                         q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4420                                         tx->basematerialflags = MATERIALFLAG_SKY;
4421                                         tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4422                                         tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4423                                 }
4424                                 if (q2flags & Q2SURF_WARP)
4425                                 {
4426                                         // we use a scroll instead of a warp
4427                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4428                                         // if it's also transparent, we can enable the WATERSHADER
4429                                         // but we do not set the WATERALPHA flag because we don't
4430                                         // want to honor r_wateralpha in q2bsp
4431                                         // (it would go against the artistic intent)
4432                                         if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4433                                                 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4434                                 }
4435                                 if (q2flags & Q2SURF_TRANS33)
4436                                 {
4437                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4438                                         tx->basealpha = 1.0f / 3.0f;
4439                                         tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4440                                         if (tx->q2contents & Q2CONTENTS_SOLID)
4441                                                 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4442                                 }
4443                                 if (q2flags & Q2SURF_TRANS66)
4444                                 {
4445                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4446                                         tx->basealpha = 2.0f / 3.0f;
4447                                         tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4448                                         if (tx->q2contents & Q2CONTENTS_SOLID)
4449                                                 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4450                                 }
4451                                 if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
4452                                 {
4453                                         tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4454                                         if (q2flags & Q2SURF_WARP)
4455                                                 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4456                                         else
4457                                                 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4458                                         tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4459                                 }
4460                                 if (q2flags & Q2SURF_ALPHATEST)
4461                                 {
4462                                         // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4463                                         tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4464                                 }
4465                                 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4466                                 {
4467                                         if (!mod_q2bsp_littransparentsurfaces.integer)
4468                                                 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4469                                 }
4470                                 if (q2flags & Q2SURF_NODRAW)
4471                                 {
4472                                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4473                                 }
4474                                 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4475                                         tx->q2contents |= Q2CONTENTS_DETAIL;
4476                                 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4477                                         tx->q2contents |= Q2CONTENTS_SOLID;
4478                                 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4479                                         tx->q2contents = 0;
4480                                 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(tx->q2contents);
4481                                 // set the current values to the base values
4482                                 tx->currentframe = tx;
4483                                 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
4484                                 tx->currentmaterialflags = tx->basematerialflags;
4485                                 loadmodel->num_texturesperskin++;
4486                                 loadmodel->num_textures = loadmodel->num_texturesperskin;
4487                         }
4488                         else
4489                         {
4490                                 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4491                                 j = 0; // use first texture and give up
4492                         }
4493                 }
4494                 // store the index we found for this texture
4495                 out->textureindex = j;
4496         }
4497
4498         // realloc the textures array now that we know how many we actually need
4499         loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4500
4501         // now assemble the texture chains
4502         // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier 
4503         for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4504         {
4505                 int j, k;
4506                 texture_t *t = loadmodel->data_textures + out->textureindex;
4507                 t->currentframe = t; // fix the reallocated pointer
4508
4509                 // if this is not animated, skip it
4510                 // if this is already processed, skip it (part of an existing sequence)
4511                 if (out->q2nexttexinfo == 0 || t->animated)
4512                         continue;
4513
4514                 // store the array of frames to use
4515                 t->animated = 2; // q2bsp animation
4516                 t->anim_total[0] = 0;
4517                 t->anim_total[1] = 0;
4518                 // gather up to 10 frames (we don't support more)
4519                 for (j = i;j >= 0 && t->anim_total[0] < (int)(sizeof(t->anim_frames[0])/sizeof(t->anim_frames[0][0]));j = loadmodel->brushq1.texinfo[j].q2nexttexinfo)
4520                 {
4521                         // detect looping and stop there
4522                         if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4523                                 break;
4524                         t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4525                 }
4526                 // we could look for the +a sequence here if this is the +0 sequence,
4527                 // but it seems that quake2 did not implement that (even though the
4528                 // files exist in the baseq2 content)
4529
4530                 // write the frame sequence to all the textures involved (just like
4531                 // in the q1bsp loader)
4532                 //
4533                 // note that this can overwrite the rest of the sequence - so if the
4534                 // start of a sequence is found later than the other parts of the
4535                 // sequence, it will go back and rewrite them correctly.
4536                 for (k = 0;k < t->anim_total[0];k++)
4537                 {
4538                         texture_t *txk = t->anim_frames[0][k];
4539                         txk->animated = t->animated;
4540                         txk->anim_total[0] = t->anim_total[0];
4541                         for (l = 0;l < t->anim_total[0];l++)
4542                                 txk->anim_frames[0][l] = t->anim_frames[0][l];
4543                 }
4544         }
4545 }
4546
4547 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4548 {
4549         // LadyHavoc: this fits exactly the same format that we use in .lit files
4550         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4551         MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4552 }
4553
4554 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4555 {
4556         mleaf_t *out;
4557         int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4558         int structsize = 28;
4559
4560         if (sb->cursize % structsize)
4561                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4562         count = sb->cursize / structsize;
4563         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4564
4565         loadmodel->brush.data_leafs = out;
4566         loadmodel->brush.num_leafs = count;
4567
4568         // FIXME: this function could really benefit from some error checking
4569         for ( i=0 ; i<count ; i++, out++)
4570         {
4571                 out->contents = MSG_ReadLittleLong(sb);
4572                 out->clusterindex = MSG_ReadLittleShort(sb);
4573                 out->areaindex = MSG_ReadLittleShort(sb);
4574                 out->mins[0] = MSG_ReadLittleShort(sb);
4575                 out->mins[1] = MSG_ReadLittleShort(sb);
4576                 out->mins[2] = MSG_ReadLittleShort(sb);
4577                 out->maxs[0] = MSG_ReadLittleShort(sb);
4578                 out->maxs[1] = MSG_ReadLittleShort(sb);
4579                 out->maxs[2] = MSG_ReadLittleShort(sb);
4580         
4581                 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4582                 nummarksurfaces  = (unsigned short)MSG_ReadLittleShort(sb);
4583                 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4584                 nummarkbrushes  = (unsigned short)MSG_ReadLittleShort(sb);
4585
4586                 for (j = 0;j < 4;j++)
4587                         out->ambient_sound_level[j] = 0;
4588
4589                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4590                 {
4591                         Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4592                         out->clusterindex = -1;
4593                 }
4594
4595                 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4596                 {
4597                         out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4598                         out->numleafsurfaces = nummarksurfaces;
4599                 }
4600                 else
4601                 {
4602                         Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4603                         out->firstleafsurface = NULL;
4604                         out->numleafsurfaces = 0;
4605                 }
4606
4607                 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4608                 {
4609                         out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4610                         out->numleafbrushes = nummarkbrushes;
4611                 }
4612                 else
4613                 {
4614                         Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4615                         out->firstleafbrush = NULL;
4616                         out->numleafbrushes = 0;
4617                 }
4618         }
4619 }
4620
4621 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4622 {
4623         int i, j;
4624         int structsize = 2;
4625
4626         if (sb->cursize % structsize)
4627                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4628         loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4629         loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4630
4631         for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4632         {
4633                 j = (unsigned short) MSG_ReadLittleShort(sb);
4634                 if (j >= loadmodel->brush.num_brushes)
4635                         Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4636                 loadmodel->brush.data_leafbrushes[i] = j;
4637         }
4638 }
4639
4640 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4641 {
4642         q3mbrushside_t *out;
4643         int i, n, count;
4644         int structsize = 4;
4645
4646         if (sb->cursize % structsize)
4647                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4648         count = sb->cursize / structsize;
4649         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4650
4651         loadmodel->brush.data_brushsides = out;
4652         loadmodel->brush.num_brushsides = count;
4653
4654         for (i = 0;i < count;i++, out++)
4655         {
4656                 n = (unsigned short)MSG_ReadLittleShort(sb);
4657                 if (n < 0 || n >= loadmodel->brush.num_planes)
4658                         Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4659                 out->plane = loadmodel->brush.data_planes + n;
4660                 n = MSG_ReadLittleShort(sb);
4661                 if (n >= 0)
4662                 {
4663                         if (n >= loadmodel->brushq1.numtexinfo)
4664                                 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4665                         out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4666                 }
4667                 else
4668                 {
4669                         //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4670                         out->texture = &mod_q1bsp_texture_solid;
4671                 }
4672         }
4673 }
4674
4675 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4676 {
4677         q3mbrush_t *out;
4678         int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4679         colplanef_t *planes;
4680         int structsize = 12;
4681         qbool brushmissingtextures;
4682         int numbrushesmissingtextures = 0;
4683         int numcreatedtextures = 0;
4684
4685         if (sb->cursize % structsize)
4686                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4687         count = sb->cursize / structsize;
4688         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4689
4690         loadmodel->brush.data_brushes = out;
4691         loadmodel->brush.num_brushes = count;
4692
4693         maxplanes = 0;
4694         planes = NULL;
4695
4696         for (i = 0; i < count; i++, out++)
4697         {
4698                 firstside = MSG_ReadLittleLong(sb);
4699                 numsides = MSG_ReadLittleLong(sb);
4700                 contents = MSG_ReadLittleLong(sb);
4701                 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4702                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4703
4704                 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4705                 out->numbrushsides = numsides;
4706                 // convert the contents to our values
4707                 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(contents);
4708
4709                 // problem: q2bsp brushes have contents but not a texture
4710                 // problem: q2bsp brushsides *may* have a texture or may not
4711                 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4712                 // solution: nasty hacks
4713                 brushmissingtextures = false;
4714                 out->texture = NULL;
4715                 for (j = 0; j < out->numbrushsides; j++)
4716                 {
4717                         if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4718                                 brushmissingtextures = true;
4719                         else
4720                         {
4721                                 // if we can find a matching texture on a brush side we can use it instead of creating one
4722                                 if (out->firstbrushside[j].texture->supercontents == supercontents)
4723                                         out->texture = out->firstbrushside[j].texture;
4724                         }
4725                 }
4726                 if (brushmissingtextures || out->texture == NULL)
4727                 {
4728                         numbrushesmissingtextures++;
4729                         // if we didn't find any appropriate texture (matching contents), we'll have to create one
4730                         // we could search earlier ones for a matching one but that can be slow
4731                         if (out->texture == NULL)
4732                         {
4733                                 texture_t *validtexture;
4734                                 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4735                                 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4736                                 validtexture->surfaceflags = 0;
4737                                 validtexture->supercontents = supercontents;
4738                                 numcreatedtextures++;
4739                                 out->texture = validtexture;
4740                         }
4741                         // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4742                         for (j = 0; j < out->numbrushsides; j++)
4743                                 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4744                                         out->firstbrushside[j].texture = out->texture;
4745                 }
4746
4747                 // make a colbrush from the brush
4748                 q3surfaceflags = 0;
4749                 // make a list of mplane_t structs to construct a colbrush from
4750                 if (maxplanes < out->numbrushsides)
4751                 {
4752                         maxplanes = out->numbrushsides;
4753                         if (planes)
4754                                 Mem_Free(planes);
4755                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4756                 }
4757                 for (j = 0;j < out->numbrushsides;j++)
4758                 {
4759                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4760                         planes[j].dist = out->firstbrushside[j].plane->dist;
4761                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4762                         planes[j].texture = out->firstbrushside[j].texture;
4763                         q3surfaceflags |= planes[j].q3surfaceflags;
4764                 }
4765                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4766
4767                 // this whole loop can take a while (e.g. on redstarrepublic4)
4768                 CL_KeepaliveMessage(false);
4769         }
4770         if (planes)
4771                 Mem_Free(planes);
4772         if (numcreatedtextures)
4773                 Con_DPrintf("Mod_Q2BSP_LoadBrushes: %i brushes own sides that lack textures or have differing contents from the brush, %i textures have been created to describe these contents.\n", numbrushesmissingtextures, numcreatedtextures);
4774 }
4775
4776 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4777 {
4778         // this is probably a "proof of purchase" lump of some sort, it seems to be 0 size in most bsp files (but not q2dm1.bsp for instance)
4779         sb->readcount = sb->cursize;
4780 }
4781
4782 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4783 {
4784         // we currently don't use areas, they represent closable doors as vis blockers
4785         sb->readcount = sb->cursize;
4786 }
4787
4788 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4789 {
4790         // we currently don't use areas, they represent closable doors as vis blockers
4791         sb->readcount = sb->cursize;
4792 }
4793
4794 static void Mod_Q2BSP_FindSubmodelBrushRange_r(model_t *mod, mnode_t *node, int *first, int *last)
4795 {
4796         int i;
4797         mleaf_t *leaf;
4798         while (node->plane)
4799         {
4800                 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4801                 node = node->children[1];
4802         }
4803         leaf = (mleaf_t*)node;
4804         for (i = 0;i < leaf->numleafbrushes;i++)
4805         {
4806                 int brushnum = leaf->firstleafbrush[i];
4807                 if (*first > brushnum)
4808                         *first = brushnum;
4809                 if (*last < brushnum)
4810                         *last = brushnum;
4811         }
4812 }
4813
4814 static void Mod_Q2BSP_Load(model_t *mod, void *buffer, void *bufferend)
4815 {
4816         int i, j, k;
4817         sizebuf_t lumpsb[Q2HEADER_LUMPS];
4818         mmodel_t *bm;
4819         float dist, modelyawradius, modelradius;
4820         msurface_t *surface;
4821         int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4822         model_brush_lightstyleinfo_t styleinfo[256];
4823         unsigned char *datapointer;
4824         sizebuf_t sb;
4825
4826         MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4827
4828         mod->type = mod_brushq2;
4829
4830         mod->brush.ishlbsp = false;
4831         mod->brush.isbsp2rmqe = false;
4832         mod->brush.isbsp2 = false;
4833         mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4834         mod->brush.isq3bsp = false;
4835         mod->brush.skymasking = true;
4836         mod->modeldatatypestring = "Q2BSP";
4837
4838         i = MSG_ReadLittleLong(&sb);
4839         if (i != Q2BSPMAGIC)
4840                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4841
4842         i = MSG_ReadLittleLong(&sb);
4843         if (i != Q2BSPVERSION)
4844                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4845
4846 // read lumps
4847         for (i = 0; i < Q2HEADER_LUMPS; i++)
4848         {
4849                 int offset = MSG_ReadLittleLong(&sb);
4850                 int size = MSG_ReadLittleLong(&sb);
4851                 if (offset < 0 || offset + size > sb.cursize)
4852                         Host_Error("Mod_Q2BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
4853                 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4854         }
4855
4856         mod->soundfromcenter = true;
4857         mod->TracePoint = Mod_CollisionBIH_TracePoint;
4858         mod->TraceLine = Mod_CollisionBIH_TraceLine;
4859         mod->TraceBox = Mod_CollisionBIH_TraceBox;
4860         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4861         mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4862         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4863         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4864         mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4865         mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4866         mod->brush.GetPVS = Mod_BSP_GetPVS;
4867         mod->brush.FatPVS = Mod_BSP_FatPVS;
4868         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
4869         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
4870         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
4871         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
4872         mod->brush.LightPoint = Mod_BSP_LightPoint;
4873         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
4874         mod->brush.AmbientSoundLevelsForPoint = NULL;
4875         mod->brush.RoundUpToHullSize = NULL;
4876         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
4877         mod->Draw = R_Mod_Draw;
4878         mod->DrawDepth = R_Mod_DrawDepth;
4879         mod->DrawDebug = R_Mod_DrawDebug;
4880         mod->DrawPrepass = R_Mod_DrawPrepass;
4881         mod->GetLightInfo = R_Mod_GetLightInfo;
4882         mod->CompileShadowMap = R_Mod_CompileShadowMap;
4883         mod->DrawShadowMap = R_Mod_DrawShadowMap;
4884         mod->DrawLight = R_Mod_DrawLight;
4885
4886 // load into heap
4887
4888         mod->brush.qw_md4sum = 0;
4889         mod->brush.qw_md4sum2 = 0;
4890         for (i = 0;i < Q2HEADER_LUMPS;i++)
4891         {
4892                 int temp;
4893                 if (i == Q2LUMP_ENTITIES)
4894                         continue;
4895                 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4896                 mod->brush.qw_md4sum ^= LittleLong(temp);
4897                 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4898                         continue;
4899                 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4900         }
4901
4902         // many of these functions are identical to Q1 loaders, so we use those where possible
4903         Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4904         Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4905         Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4906         Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4907         Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4908         Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4909         Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4910         Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4911         Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4912         Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4913         Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4914         Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4915         Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4916         Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4917         Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4918         Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4919         Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4920         Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4921         Mod_BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS], NULL);
4922
4923         for (i = 0; i < Q2HEADER_LUMPS; i++)
4924                 if (lumpsb[i].readcount != lumpsb[i].cursize)
4925                         Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4926
4927         // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4928         // doesn't enable the cvar, just indicates that transparent water is OK
4929         loadmodel->brush.supportwateralpha = true;
4930
4931         // we don't need the compressed pvs data anymore
4932         if (mod->brushq1.data_compressedpvs)
4933                 Mem_Free(mod->brushq1.data_compressedpvs);
4934         mod->brushq1.data_compressedpvs = NULL;
4935         mod->brushq1.num_compressedpvs = 0;
4936
4937         // the MakePortals code works fine on the q2bsp data as well
4938         if (mod_bsp_portalize.integer)
4939                 Mod_BSP_MakePortals();
4940
4941         mod->numframes = 0;             // q2bsp animations are kind of special, frame is unbounded...
4942         mod->numskins = 1;
4943
4944         if (loadmodel->brush.numsubmodels)
4945                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
4946
4947         totalstylesurfaces = 0;
4948         totalstyles = 0;
4949         for (i = 0;i < mod->brush.numsubmodels;i++)
4950         {
4951                 memset(stylecounts, 0, sizeof(stylecounts));
4952                 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4953                 {
4954                         surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4955                         for (j = 0;j < MAXLIGHTMAPS;j++)
4956                                 stylecounts[surface->lightmapinfo->styles[j]]++;
4957                 }
4958                 for (k = 0;k < 255;k++)
4959                 {
4960                         totalstyles++;
4961                         if (stylecounts[k])
4962                                 totalstylesurfaces += stylecounts[k];
4963                 }
4964         }
4965         datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4966         mod->modelsurfaces_sorted = (int*)datapointer; datapointer += mod->num_surfaces * sizeof(int);
4967         // set up the world model, then on each submodel copy from the world model
4968         // and set up the submodel with the respective model info.
4969         mod = loadmodel;
4970         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4971         {
4972                 mnode_t *rootnode = NULL;
4973                 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
4974                 if (i > 0)
4975                 {
4976                         char name[10];
4977                         // duplicate the basic information
4978                         dpsnprintf(name, sizeof(name), "*%i", i);
4979                         mod = Mod_FindName(name, loadmodel->name);
4980                         // copy the base model to this one
4981                         *mod = *loadmodel;
4982                         // rename the clone back to its proper name
4983                         strlcpy(mod->name, name, sizeof(mod->name));
4984                         mod->brush.parentmodel = loadmodel;
4985                         // textures and memory belong to the main model
4986                         mod->texturepool = NULL;
4987                         mod->mempool = NULL;
4988                         mod->brush.GetPVS = NULL;
4989                         mod->brush.FatPVS = NULL;
4990                         mod->brush.BoxTouchingPVS = NULL;
4991                         mod->brush.BoxTouchingLeafPVS = NULL;
4992                         mod->brush.BoxTouchingVisibleLeafs = NULL;
4993                         mod->brush.FindBoxClusters = NULL;
4994                         mod->brush.LightPoint = NULL;
4995                         mod->brush.AmbientSoundLevelsForPoint = NULL;
4996                 }
4997                 mod->brush.submodel = i;
4998                 if (loadmodel->brush.submodels)
4999                         loadmodel->brush.submodels[i] = mod;
5000
5001                 bm = &mod->brushq1.submodels[i];
5002
5003                 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5004                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5005
5006                 mod->submodelsurfaces_start = bm->firstface;
5007                 mod->submodelsurfaces_end = bm->firstface + bm->numfaces;
5008
5009                 // set node/leaf parents for this submodel
5010                 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5011                 // (this happens in base3.bsp)
5012                 if (bm->headnode[0] >= 0)
5013                         rootnode = mod->brush.data_nodes + bm->headnode[0];
5014                 else
5015                         rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5016                 Mod_BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5017
5018                 // make the model surface list (used by shadowing/lighting)
5019                 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5020                 if (firstbrush <= lastbrush)
5021                 {
5022                         mod->firstmodelbrush = firstbrush;
5023                         mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5024                 }
5025                 else
5026                 {
5027                         mod->firstmodelbrush = 0;
5028                         mod->nummodelbrushes = 0;
5029                 }
5030
5031                 VectorCopy(bm->mins, mod->normalmins);
5032                 VectorCopy(bm->maxs, mod->normalmaxs);
5033                 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5034                 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5035                 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5036                 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5037                 modelradius = modelyawradius + modelradius * modelradius;
5038                 modelyawradius = sqrt(modelyawradius);
5039                 modelradius = sqrt(modelradius);
5040                 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5041                 mod->yawmins[2] = mod->normalmins[2];
5042                 mod->yawmaxs[0] = mod->yawmaxs[1] =  modelyawradius;
5043                 mod->yawmaxs[2] = mod->normalmaxs[2];
5044                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5045                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] =  modelradius;
5046                 mod->radius = modelradius;
5047                 mod->radius2 = modelradius * modelradius;
5048
5049                 Mod_SetDrawSkyAndWater(mod);
5050
5051                 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5052                 if (mod->submodelsurfaces_start < mod->submodelsurfaces_end)
5053                 {
5054                         // build lightstyle update chains
5055                         // (used to rapidly mark lightmapupdateflags on many surfaces
5056                         // when d_lightstylevalue changes)
5057                         memset(stylecounts, 0, sizeof(stylecounts));
5058                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
5059                                 for (j = 0;j < MAXLIGHTMAPS;j++)
5060                                         stylecounts[mod->data_surfaces[k].lightmapinfo->styles[j]]++;
5061                         mod->brushq1.num_lightstyles = 0;
5062                         for (k = 0;k < 255;k++)
5063                         {
5064                                 if (stylecounts[k])
5065                                 {
5066                                         styleinfo[mod->brushq1.num_lightstyles].style = k;
5067                                         styleinfo[mod->brushq1.num_lightstyles].value = 0;
5068                                         styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5069                                         styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5070                                         remapstyles[k] = mod->brushq1.num_lightstyles;
5071                                         mod->brushq1.num_lightstyles++;
5072                                 }
5073                         }
5074                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
5075                         {
5076                                 surface = mod->data_surfaces + k;
5077                                 for (j = 0;j < MAXLIGHTMAPS;j++)
5078                                 {
5079                                         if (surface->lightmapinfo->styles[j] != 255)
5080                                         {
5081                                                 int r = remapstyles[surface->lightmapinfo->styles[j]];
5082                                                 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = k;
5083                                         }
5084                                 }
5085                         }
5086                         mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5087                         memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5088                 }
5089                 else
5090                 {
5091                         Con_Printf(CON_WARN "warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5092                 }
5093                 //mod->brushq1.num_visleafs = bm->visleafs;
5094
5095                 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5096                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5097
5098                 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5099                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5100
5101                 // generate VBOs and other shared data before cloning submodels
5102                 if (i == 0)
5103                         Mod_BuildVBOs();
5104         }
5105         mod = loadmodel;
5106
5107         // make the model surface list (used by shadowing/lighting)
5108         Mod_MakeSortedSurfaces(loadmodel);
5109
5110         Con_DPrintf("Stats for q2bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
5111 }
5112
5113 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents);
5114 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents);
5115
5116 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5117 {
5118         const char *data;
5119         char key[128], value[MAX_INPUTLINE];
5120         float v[3];
5121         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5122         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5123         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5124         if (!l->filelen)
5125                 return;
5126         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5127         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5128         loadmodel->brush.entities[l->filelen] = 0;
5129         data = loadmodel->brush.entities;
5130         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5131         // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5132         loadmodel->brushq3.deluxemapping = false;
5133         if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5134         {
5135                 while (1)
5136                 {
5137                         if (!COM_ParseToken_Simple(&data, false, false, true))
5138                                 break; // error
5139                         if (com_token[0] == '}')
5140                                 break; // end of worldspawn
5141                         if (com_token[0] == '_')
5142                                 strlcpy(key, com_token + 1, sizeof(key));
5143                         else
5144                                 strlcpy(key, com_token, sizeof(key));
5145                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
5146                                 key[strlen(key)-1] = 0;
5147                         if (!COM_ParseToken_Simple(&data, false, false, true))
5148                                 break; // error
5149                         strlcpy(value, com_token, sizeof(value));
5150                         if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5151                         {
5152 #if _MSC_VER >= 1400
5153 #define sscanf sscanf_s
5154 #endif
5155 #if 0
5156                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5157                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5158 #else
5159                                 VectorSet(v, 64, 64, 128);
5160                                 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5161                                         Con_Printf("Mod_Q3BSP_LoadEntities: funny gridsize \"%s\" in %s, interpreting as \"%f %f %f\" to match q3map2's parsing\n", value, loadmodel->name, v[0], v[1], v[2]);
5162                                 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5163                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5164 #endif
5165                         }
5166                         else if (!strcmp("deluxeMaps", key))
5167                         {
5168                                 if (!strcmp(com_token, "1"))
5169                                 {
5170                                         loadmodel->brushq3.deluxemapping = true;
5171                                         loadmodel->brushq3.deluxemapping_modelspace = true;
5172                                 }
5173                                 else if (!strcmp(com_token, "2"))
5174                                 {
5175                                         loadmodel->brushq3.deluxemapping = true;
5176                                         loadmodel->brushq3.deluxemapping_modelspace = false;
5177                                 }
5178                         }
5179                 }
5180         }
5181 }
5182
5183 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5184 {
5185         q3dtexture_t *in;
5186         texture_t *out;
5187         int i, count;
5188
5189         in = (q3dtexture_t *)(mod_base + l->fileofs);
5190         if (l->filelen % sizeof(*in))
5191                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5192         count = l->filelen / sizeof(*in);
5193         out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5194
5195         loadmodel->data_textures = out;
5196         loadmodel->num_textures = count;
5197         loadmodel->num_texturesperskin = loadmodel->num_textures;
5198
5199         for (i = 0;i < count;i++)
5200         {
5201                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5202                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5203                 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
5204                 // restore the surfaceflags and supercontents
5205                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5206                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5207         }
5208 }
5209
5210 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5211 {
5212         q3dplane_t *in;
5213         mplane_t *out;
5214         int i, count;
5215
5216         in = (q3dplane_t *)(mod_base + l->fileofs);
5217         if (l->filelen % sizeof(*in))
5218                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5219         count = l->filelen / sizeof(*in);
5220         out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5221
5222         loadmodel->brush.data_planes = out;
5223         loadmodel->brush.num_planes = count;
5224
5225         for (i = 0;i < count;i++, in++, out++)
5226         {
5227                 out->normal[0] = LittleFloat(in->normal[0]);
5228                 out->normal[1] = LittleFloat(in->normal[1]);
5229                 out->normal[2] = LittleFloat(in->normal[2]);
5230                 out->dist = LittleFloat(in->dist);
5231                 PlaneClassify(out);
5232         }
5233 }
5234
5235 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5236 {
5237         q3dbrushside_t *in;
5238         q3mbrushside_t *out;
5239         int i, n, count;
5240
5241         in = (q3dbrushside_t *)(mod_base + l->fileofs);
5242         if (l->filelen % sizeof(*in))
5243                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5244         count = l->filelen / sizeof(*in);
5245         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5246
5247         loadmodel->brush.data_brushsides = out;
5248         loadmodel->brush.num_brushsides = count;
5249
5250         for (i = 0;i < count;i++, in++, out++)
5251         {
5252                 n = LittleLong(in->planeindex);
5253                 if (n < 0 || n >= loadmodel->brush.num_planes)
5254                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5255                 out->plane = loadmodel->brush.data_planes + n;
5256                 n = LittleLong(in->textureindex);
5257                 if (n < 0 || n >= loadmodel->num_textures)
5258                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5259                 out->texture = loadmodel->data_textures + n;
5260         }
5261 }
5262
5263 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5264 {
5265         q3dbrushside_ig_t *in;
5266         q3mbrushside_t *out;
5267         int i, n, count;
5268
5269         in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5270         if (l->filelen % sizeof(*in))
5271                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5272         count = l->filelen / sizeof(*in);
5273         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5274
5275         loadmodel->brush.data_brushsides = out;
5276         loadmodel->brush.num_brushsides = count;
5277
5278         for (i = 0;i < count;i++, in++, out++)
5279         {
5280                 n = LittleLong(in->planeindex);
5281                 if (n < 0 || n >= loadmodel->brush.num_planes)
5282                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5283                 out->plane = loadmodel->brush.data_planes + n;
5284                 n = LittleLong(in->textureindex);
5285                 if (n < 0 || n >= loadmodel->num_textures)
5286                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5287                 out->texture = loadmodel->data_textures + n;
5288         }
5289 }
5290
5291 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5292 {
5293         q3dbrush_t *in;
5294         q3mbrush_t *out;
5295         int i, j, n, c, count, maxplanes, q3surfaceflags;
5296         colplanef_t *planes;
5297
5298         in = (q3dbrush_t *)(mod_base + l->fileofs);
5299         if (l->filelen % sizeof(*in))
5300                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5301         count = l->filelen / sizeof(*in);
5302         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5303
5304         loadmodel->brush.data_brushes = out;
5305         loadmodel->brush.num_brushes = count;
5306
5307         maxplanes = 0;
5308         planes = NULL;
5309
5310         for (i = 0;i < count;i++, in++, out++)
5311         {
5312                 n = LittleLong(in->firstbrushside);
5313                 c = LittleLong(in->numbrushsides);
5314                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5315                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5316                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5317                 out->numbrushsides = c;
5318                 n = LittleLong(in->textureindex);
5319                 if (n < 0 || n >= loadmodel->num_textures)
5320                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5321                 out->texture = loadmodel->data_textures + n;
5322
5323                 // make a list of mplane_t structs to construct a colbrush from
5324                 if (maxplanes < out->numbrushsides)
5325                 {
5326                         maxplanes = out->numbrushsides;
5327                         if (planes)
5328                                 Mem_Free(planes);
5329                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5330                 }
5331                 q3surfaceflags = 0;
5332                 for (j = 0;j < out->numbrushsides;j++)
5333                 {
5334                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5335                         planes[j].dist = out->firstbrushside[j].plane->dist;
5336                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5337                         planes[j].texture = out->firstbrushside[j].texture;
5338                         q3surfaceflags |= planes[j].q3surfaceflags;
5339                 }
5340                 // make the colbrush from the planes
5341                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5342
5343                 // this whole loop can take a while (e.g. on redstarrepublic4)
5344                 CL_KeepaliveMessage(false);
5345         }
5346         if (planes)
5347                 Mem_Free(planes);
5348 }
5349
5350 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5351 {
5352         q3deffect_t *in;
5353         q3deffect_t *out;
5354         int i, n, count;
5355
5356         in = (q3deffect_t *)(mod_base + l->fileofs);
5357         if (l->filelen % sizeof(*in))
5358                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5359         count = l->filelen / sizeof(*in);
5360         out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5361
5362         loadmodel->brushq3.data_effects = out;
5363         loadmodel->brushq3.num_effects = count;
5364
5365         for (i = 0;i < count;i++, in++, out++)
5366         {
5367                 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5368                 n = LittleLong(in->brushindex);
5369                 if (n >= loadmodel->brush.num_brushes)
5370                 {
5371                         Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5372                         n = -1;
5373                 }
5374                 out->brushindex = n;
5375                 out->unknown = LittleLong(in->unknown);
5376         }
5377 }
5378
5379 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5380 {
5381         q3dvertex_t *in;
5382         int i, count;
5383
5384         in = (q3dvertex_t *)(mod_base + l->fileofs);
5385         if (l->filelen % sizeof(*in))
5386                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5387         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5388         loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5389         loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5390         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5391         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5392         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5393
5394         for (i = 0;i < count;i++, in++)
5395         {
5396                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5397                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5398                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5399                 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5400                 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5401                 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5402                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5403                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5404                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5405                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5406                 // svector/tvector are calculated later in face loading
5407                 if(mod_q3bsp_sRGBlightmaps.integer)
5408                 {
5409                         // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5410                         // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5411                         // working like this may be odd, but matches q3map2 -gamma 2.2
5412                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5413                         {
5414                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5415                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5416                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5417                                 // we fix the brightness consistently via lightmapscale
5418                         }
5419                         else
5420                         {
5421                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5422                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5423                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5424                         }
5425                 }
5426                 else
5427                 {
5428                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5429                         {
5430                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5431                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5432                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5433                         }
5434                         else
5435                         {
5436                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5437                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5438                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5439                         }
5440                 }
5441                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5442                 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5443                         loadmodel->lit = true;
5444         }
5445 }
5446
5447 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5448 {
5449         int *in;
5450         int *out;
5451         int i, count;
5452
5453         in = (int *)(mod_base + l->fileofs);
5454         if (l->filelen % sizeof(int[3]))
5455                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5456         count = l->filelen / sizeof(*in);
5457
5458         if(!loadmodel->brushq3.num_vertices)
5459         {
5460                 if (count)
5461                         Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5462                 loadmodel->brushq3.num_triangles = 0;
5463                 return;
5464         }
5465
5466         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5467         loadmodel->brushq3.num_triangles = count / 3;
5468         loadmodel->brushq3.data_element3i = out;
5469
5470         for (i = 0;i < count;i++, in++, out++)
5471         {
5472                 *out = LittleLong(*in);
5473                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5474                 {
5475                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5476                         *out = 0;
5477                 }
5478         }
5479 }
5480
5481 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5482 {
5483         q3dlightmap_t *input_pointer;
5484         int i;
5485         int j;
5486         int k;
5487         int count;
5488         int powerx;
5489         int powery;
5490         int powerxy;
5491         int powerdxy;
5492         int endlightmap;
5493         int mergegoal;
5494         int lightmapindex;
5495         int realcount;
5496         int realindex;
5497         int mergedwidth;
5498         int mergedheight;
5499         int mergedcolumns;
5500         int mergedrows;
5501         int mergedrowsxcolumns;
5502         int size;
5503         int bytesperpixel;
5504         int rgbmap[3];
5505         unsigned char *c;
5506         unsigned char *mergedpixels;
5507         unsigned char *mergeddeluxepixels;
5508         unsigned char *mergebuf;
5509         char mapname[MAX_QPATH];
5510         qbool external;
5511         unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5512         char vabuf[1024];
5513
5514         // defaults for q3bsp
5515         size = 128;
5516         bytesperpixel = 3;
5517         rgbmap[0] = 2;
5518         rgbmap[1] = 1;
5519         rgbmap[2] = 0;
5520         external = false;
5521         loadmodel->brushq3.lightmapsize = 128;
5522
5523         if (cls.state == ca_dedicated)
5524                 return;
5525
5526         if(mod_q3bsp_nolightmaps.integer)
5527         {
5528                 return;
5529         }
5530         else if(l->filelen)
5531         {
5532                 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5533                 if (developer_loading.integer)
5534                         Con_Printf("Using internal lightmaps\n");
5535                 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5536                 if (l->filelen % sizeof(*input_pointer))
5537                         Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5538                 count = l->filelen / sizeof(*input_pointer);
5539                 for(i = 0; i < count; ++i)
5540                         inpixels[i] = input_pointer[i].rgb;
5541         }
5542         else
5543         {
5544                 // no internal lightmaps
5545                 // try external lightmaps
5546                 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5547                 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5548                 if(!inpixels[0])
5549                         return;
5550                 else
5551                         Con_Printf("Using external lightmaps\n");
5552
5553                 // using EXTERNAL lightmaps instead
5554                 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5555                         Con_Printf("Mod_Q3BSP_LoadLightmaps: irregularly sized external lightmap in %s",loadmodel->name);
5556
5557                 size = image_width;
5558                 bytesperpixel = 4;
5559                 rgbmap[0] = 0;
5560                 rgbmap[1] = 1;
5561                 rgbmap[2] = 2;
5562                 external = true;
5563
5564                 for(count = 1; ; ++count)
5565                 {
5566                         inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5567                         if(!inpixels[count])
5568                                 break; // we got all of them
5569                         if(image_width != size || image_height != size)
5570                         {
5571                                 Mem_Free(inpixels[count]);
5572                                 inpixels[count] = NULL;
5573                                 Con_Printf("Mod_Q3BSP_LoadLightmaps: mismatched lightmap size in %s - external lightmap %s/lm_%04d does not match earlier ones\n", loadmodel->name, mapname, count);
5574                                 break;
5575                         }
5576                 }
5577         }
5578
5579         loadmodel->brushq3.lightmapsize = size;
5580         loadmodel->brushq3.num_originallightmaps = count;
5581
5582         // now check the surfaces to see if any of them index an odd numbered
5583         // lightmap, if so this is not a deluxemapped bsp file
5584         //
5585         // also check what lightmaps are actually used, because q3map2 sometimes
5586         // (always?) makes an unused one at the end, which
5587         // q3map2 sometimes (or always?) makes a second blank lightmap for no
5588         // reason when only one lightmap is used, which can throw off the
5589         // deluxemapping detection method, so check 2-lightmap bsp's specifically
5590         // to see if the second lightmap is blank, if so it is not deluxemapped.
5591         // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5592         // in Mod_Q3BSP_LoadEntities was failed
5593         if (!loadmodel->brushq3.deluxemapping)
5594         {
5595                 loadmodel->brushq3.deluxemapping = !(count & 1);
5596                 loadmodel->brushq3.deluxemapping_modelspace = true;
5597                 endlightmap = 0;
5598                 if (loadmodel->brushq3.deluxemapping)
5599                 {
5600                         int facecount = faceslump->filelen / sizeof(q3dface_t);
5601                         q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5602                         for (i = 0;i < facecount;i++)
5603                         {
5604                                 j = LittleLong(faces[i].lightmapindex);
5605                                 if (j >= 0)
5606                                 {
5607                                         endlightmap = max(endlightmap, j + 1);
5608                                         if ((j & 1) || j + 1 >= count)
5609                                         {
5610                                                 loadmodel->brushq3.deluxemapping = false;
5611                                                 break;
5612                                         }
5613                                 }
5614                         }
5615                 }
5616
5617                 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5618                 // reason when only one lightmap is used, which can throw off the
5619                 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5620                 // to see if the second lightmap is blank, if so it is not deluxemapped.
5621                 //
5622                 // further research has shown q3map2 sometimes creates a deluxemap and two
5623                 // blank lightmaps, which must be handled properly as well
5624                 if (endlightmap == 1 && count > 1)
5625                 {
5626                         c = inpixels[1];
5627                         for (i = 0;i < size*size;i++)
5628                         {
5629                                 if (c[bytesperpixel*i + rgbmap[0]])
5630                                         break;
5631                                 if (c[bytesperpixel*i + rgbmap[1]])
5632                                         break;
5633                                 if (c[bytesperpixel*i + rgbmap[2]])
5634                                         break;
5635                         }
5636                         if (i == size*size)
5637                         {
5638                                 // all pixels in the unused lightmap were black...
5639                                 loadmodel->brushq3.deluxemapping = false;
5640                         }
5641                 }
5642         }
5643
5644         Con_Printf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5645
5646         // figure out what the most reasonable merge power is within limits
5647
5648         // find the appropriate NxN dimensions to merge to, to avoid wasted space
5649         realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5650
5651         // figure out how big the merged texture has to be
5652         mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5653         mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5654         while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5655                 mergegoal /= 2;
5656         mergedwidth = mergegoal;
5657         mergedheight = mergegoal;
5658         // choose non-square size (2x1 aspect) if only half the space is used;
5659         // this really only happens when the entire set fits in one texture, if
5660         // there are multiple textures, we don't worry about shrinking the last
5661         // one to fit, because the driver prefers the same texture size on
5662         // consecutive draw calls...
5663         if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5664                 mergedheight /= 2;
5665
5666         loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5667         loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5668         while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5669                 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5670         while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5671                 loadmodel->brushq3.num_lightmapmergedheightpower++;
5672         loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5673
5674         powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5675         powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5676         powerxy = powerx+powery;
5677         powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5678
5679         mergedcolumns = 1 << powerx;
5680         mergedrows = 1 << powery;
5681         mergedrowsxcolumns = 1 << powerxy;
5682
5683         loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5684         loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5685         if (loadmodel->brushq3.deluxemapping)
5686                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5687
5688         mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5689         mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5690         for (i = 0;i < count;i++)
5691         {
5692                 // figure out which merged lightmap texture this fits into
5693                 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5694                 lightmapindex = i >> powerdxy;
5695
5696                 // choose the destination address
5697                 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5698                 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5699                 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5700                         Con_DPrintf("copying original lightmap %i (%ix%i) to %i (at %i,%i)\n", i, size, size, lightmapindex, (realindex & (mergedcolumns-1))*size, ((realindex >> powerx) & (mergedrows-1))*size);
5701
5702                 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5703                 for (j = 0;j < size;j++)
5704                 for (k = 0;k < size;k++)
5705                 {
5706                         mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5707                         mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5708                         mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5709                         mergebuf[(j*mergedwidth+k)*4+3] = 255;
5710                 }
5711
5712                 // upload texture if this was the last tile being written to the texture
5713                 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5714                 {
5715                         if (loadmodel->brushq3.deluxemapping && (i & 1))
5716                                 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5717                         else
5718                         {
5719                                 if(mod_q3bsp_sRGBlightmaps.integer)
5720                                 {
5721                                         textype_t t;
5722                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5723                                         {
5724                                                 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5725                                                 // we fix the brightness consistently via lightmapscale
5726                                         }
5727                                         else
5728                                                 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5729                                         loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, t, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5730                                 }
5731                                 else
5732                                 {
5733                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5734                                                 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5735                                         loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5736                                 }
5737                         }
5738                 }
5739         }
5740
5741         if (mergeddeluxepixels)
5742                 Mem_Free(mergeddeluxepixels);
5743         Mem_Free(mergedpixels);
5744         if(external)
5745         {
5746                 for(i = 0; i < count; ++i)
5747                         Mem_Free(inpixels[i]);
5748         }
5749 }
5750
5751 typedef struct patchtess_s
5752 {
5753         patchinfo_t info;
5754
5755         // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5756         int surface_id;
5757         float lodgroup[6];
5758         float *originalvertex3f;
5759 } patchtess_t;
5760
5761 #define PATCHTESS_SAME_LODGROUP(a,b) \
5762         ( \
5763                 (a).lodgroup[0] == (b).lodgroup[0] && \
5764                 (a).lodgroup[1] == (b).lodgroup[1] && \
5765                 (a).lodgroup[2] == (b).lodgroup[2] && \
5766                 (a).lodgroup[3] == (b).lodgroup[3] && \
5767                 (a).lodgroup[4] == (b).lodgroup[4] && \
5768                 (a).lodgroup[5] == (b).lodgroup[5] \
5769         )
5770
5771 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5772 {
5773         q3dface_t *in, *oldin;
5774         msurface_t *out, *oldout;
5775         int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshvertices, meshtriangles, collisionvertices, collisiontriangles, numvertices, numtriangles, cxtess, cytess;
5776         float lightmaptcbase[2], lightmaptcscale[2];
5777         //int *originalelement3i;
5778         float *originalvertex3f;
5779         //float *originalsvector3f;
5780         //float *originaltvector3f;
5781         float *originalnormal3f;
5782         float *originalcolor4f;
5783         float *originaltexcoordtexture2f;
5784         float *originaltexcoordlightmap2f;
5785         float *surfacecollisionvertex3f;
5786         int *surfacecollisionelement3i;
5787         float *v;
5788         patchtess_t *patchtess = NULL;
5789         int patchtesscount = 0;
5790         qbool again;
5791
5792         in = (q3dface_t *)(mod_base + l->fileofs);
5793         if (l->filelen % sizeof(*in))
5794                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5795         count = l->filelen / sizeof(*in);
5796         out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5797
5798         loadmodel->data_surfaces = out;
5799         loadmodel->num_surfaces = count;
5800
5801         if(count > 0)
5802                 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5803
5804         i = 0;
5805         oldi = i;
5806         oldin = in;
5807         oldout = out;
5808         meshvertices = 0;
5809         meshtriangles = 0;
5810         for (;i < count;i++, in++, out++)
5811         {
5812                 // check face type first
5813                 type = LittleLong(in->type);
5814                 if (type != Q3FACETYPE_FLAT
5815                  && type != Q3FACETYPE_PATCH
5816                  && type != Q3FACETYPE_MESH
5817                  && type != Q3FACETYPE_FLARE)
5818                 {
5819                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5820                         continue;
5821                 }
5822
5823                 n = LittleLong(in->textureindex);
5824                 if (n < 0 || n >= loadmodel->num_textures)
5825                 {
5826                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5827                         continue;
5828                 }
5829                 out->texture = loadmodel->data_textures + n;
5830                 n = LittleLong(in->effectindex);
5831                 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5832                 {
5833                         if (developer_extra.integer)
5834                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5835                         n = -1;
5836                 }
5837                 if (n == -1)
5838                         out->effect = NULL;
5839                 else
5840                         out->effect = loadmodel->brushq3.data_effects + n;
5841
5842                 if (cls.state != ca_dedicated)
5843                 {
5844                         out->lightmaptexture = NULL;
5845                         out->deluxemaptexture = r_texture_blanknormalmap;
5846                         n = LittleLong(in->lightmapindex);
5847                         if (n < 0)
5848                                 n = -1;
5849                         else if (n >= loadmodel->brushq3.num_originallightmaps)
5850                         {
5851                                 if(loadmodel->brushq3.num_originallightmaps != 0)
5852                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5853                                 n = -1;
5854                         }
5855                         else
5856                         {
5857                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5858                                 if (loadmodel->brushq3.deluxemapping)
5859                                         out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5860                                 loadmodel->lit = true;
5861                         }
5862                 }
5863
5864                 firstvertex = LittleLong(in->firstvertex);
5865                 numvertices = LittleLong(in->numvertices);
5866                 firstelement = LittleLong(in->firstelement);
5867                 numtriangles = LittleLong(in->numelements) / 3;
5868                 if (numtriangles * 3 != LittleLong(in->numelements))
5869                 {
5870                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): numelements %i is not a multiple of 3\n", i, out->texture->name, LittleLong(in->numelements));
5871                         continue;
5872                 }
5873                 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5874                 {
5875                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid vertex range %i : %i (%i vertices)\n", i, out->texture->name, firstvertex, firstvertex + numvertices, loadmodel->brushq3.num_vertices);
5876                         continue;
5877                 }
5878                 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5879                 {
5880                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid element range %i : %i (%i elements)\n", i, out->texture->name, firstelement, firstelement + numtriangles * 3, loadmodel->brushq3.num_triangles * 3);
5881                         continue;
5882                 }
5883                 switch(type)
5884                 {
5885                 case Q3FACETYPE_FLAT:
5886                 case Q3FACETYPE_MESH:
5887                         // no processing necessary
5888                         break;
5889                 case Q3FACETYPE_PATCH:
5890                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5891                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5892                         if (numvertices != (patchsize[0] * patchsize[1]) || patchsize[0] < 3 || patchsize[1] < 3 || !(patchsize[0] & 1) || !(patchsize[1] & 1) || patchsize[0] * patchsize[1] >= (cls.state == ca_dedicated ? mod_q3bsp_curves_subdivisions_maxvertices.integer : min(r_subdivisions_maxvertices.integer, mod_q3bsp_curves_subdivisions_maxvertices.integer)))
5893                         {
5894                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5895                                 continue;
5896                         }
5897                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5898
5899                         // convert patch to Q3FACETYPE_MESH
5900                         xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5901                         ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5902                         // bound to user settings
5903                         xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5904                         ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5905                         // bound to sanity settings
5906                         xtess = bound(0, xtess, 1024);
5907                         ytess = bound(0, ytess, 1024);
5908
5909                         // lower quality collision patches! Same procedure as before, but different cvars
5910                         // convert patch to Q3FACETYPE_MESH
5911                         cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, mod_q3bsp_curves_subdivisions_tolerance.value);
5912                         cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, mod_q3bsp_curves_subdivisions_tolerance.value);
5913                         // bound to user settings
5914                         cxtess = bound(mod_q3bsp_curves_subdivisions_mintess.integer, cxtess, mod_q3bsp_curves_subdivisions_maxtess.integer);
5915                         cytess = bound(mod_q3bsp_curves_subdivisions_mintess.integer, cytess, mod_q3bsp_curves_subdivisions_maxtess.integer);
5916                         // bound to sanity settings
5917                         cxtess = bound(0, cxtess, 1024);
5918                         cytess = bound(0, cytess, 1024);
5919
5920                         // store it for the LOD grouping step
5921                         patchtess[patchtesscount].info.xsize = patchsize[0];
5922                         patchtess[patchtesscount].info.ysize = patchsize[1];
5923                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5924                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5925                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5926                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5927         
5928                         patchtess[patchtesscount].surface_id = i;
5929                         patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5930                         patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5931                         patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5932                         patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5933                         patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5934                         patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5935                         patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5936                         ++patchtesscount;
5937                         break;
5938                 case Q3FACETYPE_FLARE:
5939                         if (developer_extra.integer)
5940                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5941                         // don't render it
5942                         continue;
5943                 }
5944                 out->num_vertices = numvertices;
5945                 out->num_triangles = numtriangles;
5946                 meshvertices += out->num_vertices;
5947                 meshtriangles += out->num_triangles;
5948         }
5949
5950         // Fix patches tesselations so that they make no seams
5951         do
5952         {
5953                 again = false;
5954                 for(i = 0; i < patchtesscount; ++i)
5955                 {
5956                         for(j = i+1; j < patchtesscount; ++j)
5957                         {
5958                                 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5959                                         continue;
5960
5961                                 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5962                                         again = true;
5963                         }
5964                 }
5965         }
5966         while (again);
5967
5968         // Calculate resulting number of triangles
5969         collisionvertices = 0;
5970         collisiontriangles = 0;
5971         for(i = 0; i < patchtesscount; ++i)
5972         {
5973                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5974                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5975                 numvertices = finalwidth * finalheight;
5976                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5977
5978                 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5979                 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5980                 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5981                 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5982
5983                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5984                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5985                 numvertices = finalwidth * finalheight;
5986                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5987
5988                 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5989                 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5990                 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5991                 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5992         }
5993
5994         i = oldi;
5995         in = oldin;
5996         out = oldout;
5997         Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true);
5998         if (collisiontriangles)
5999         {
6000                 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6001                 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6002         }
6003         meshvertices = 0;
6004         meshtriangles = 0;
6005         collisionvertices = 0;
6006         collisiontriangles = 0;
6007         for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6008         {
6009                 if (out->num_vertices < 3 || out->num_triangles < 1)
6010                         continue;
6011
6012                 type = LittleLong(in->type);
6013                 firstvertex = LittleLong(in->firstvertex);
6014                 firstelement = LittleLong(in->firstelement);
6015                 out->num_firstvertex = meshvertices;
6016                 out->num_firsttriangle = meshtriangles;
6017                 out->num_firstcollisiontriangle = collisiontriangles;
6018                 switch(type)
6019                 {
6020                 case Q3FACETYPE_FLAT:
6021                 case Q3FACETYPE_MESH:
6022                         // no processing necessary, except for lightmap merging
6023                         for (j = 0;j < out->num_vertices;j++)
6024                         {
6025                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6026                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6027                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6028                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6029                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6030                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6031                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6032                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6033                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6034                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6035                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6036                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6037                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6038                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6039                         }
6040                         for (j = 0;j < out->num_triangles*3;j++)
6041                                 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6042                         break;
6043                 case Q3FACETYPE_PATCH:
6044                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6045                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6046                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6047                         originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6048                         originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6049                         originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6050                         originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6051
6052                         xtess = ytess = cxtess = cytess = -1;
6053                         for(j = 0; j < patchtesscount; ++j)
6054                                 if(patchtess[j].surface_id == i)
6055                                 {
6056                                         xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6057                                         ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6058                                         cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6059                                         cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6060                                         break;
6061                                 }
6062                         if(xtess == -1)
6063                         {
6064                                 Con_Printf(CON_ERROR "ERROR: patch %d isn't preprocessed?!?\n", i);
6065                                 xtess = ytess = cxtess = cytess = 0;
6066                         }
6067
6068                         finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6069                         finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6070                         finalvertices = finalwidth * finalheight;
6071                         oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6072                         type = Q3FACETYPE_MESH;
6073                         // generate geometry
6074                         // (note: normals are skipped because they get recalculated)
6075                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6076                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6077                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6078                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6079                         Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6080                         Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6081
6082                         out->num_triangles = Mod_RemoveDegenerateTriangles(out->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), loadmodel->surfmesh.data_vertex3f);
6083
6084                         if (developer_extra.integer)
6085                         {
6086                                 if (out->num_triangles < finaltriangles)
6087                                         Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->num_vertices, finaltriangles, finaltriangles - out->num_triangles, out->num_triangles);
6088                                 else
6089                                         Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->num_vertices, out->num_triangles);
6090                         }
6091                         // q3map does not put in collision brushes for curves... ugh
6092                         // build the lower quality collision geometry
6093                         finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6094                         finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6095                         finalvertices = finalwidth * finalheight;
6096                         oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6097
6098                         // store collision geometry for BIH collision tree
6099                         out->num_collisionvertices = finalvertices;
6100                         out->num_collisiontriangles = finaltriangles;
6101                         surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6102                         surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6103                         Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6104                         Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6105                         Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6106                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6107
6108                         if (developer_extra.integer)
6109                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
6110
6111                         collisionvertices += finalvertices;
6112                         collisiontriangles += out->num_collisiontriangles;
6113                         break;
6114                 default:
6115                         break;
6116                 }
6117                 meshvertices += out->num_vertices;
6118                 meshtriangles += out->num_triangles;
6119                 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6120                         if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
6121                                 invalidelements++;
6122                 if (invalidelements)
6123                 {
6124                         Con_Printf(CON_WARN "Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
6125                         for (j = 0;j < out->num_triangles * 3;j++)
6126                         {
6127                                 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6128                                 if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
6129                                         (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6130                         }
6131                         Con_Print("\n");
6132                 }
6133                 // calculate a bounding box
6134                 VectorClear(out->mins);
6135                 VectorClear(out->maxs);
6136                 if (out->num_vertices)
6137                 {
6138                         if (cls.state != ca_dedicated && out->lightmaptexture)
6139                         {
6140                                 // figure out which part of the merged lightmap this fits into
6141                                 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6142                                 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6143                                 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6144                                 lightmapindex &= mergewidth * mergeheight - 1;
6145                                 lightmaptcscale[0] = 1.0f / mergewidth;
6146                                 lightmaptcscale[1] = 1.0f / mergeheight;
6147                                 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6148                                 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6149                                 // modify the lightmap texcoords to match this region of the merged lightmap
6150                                 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6151                                 {
6152                                         v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6153                                         v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6154                                 }
6155                         }
6156                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6157                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6158                         for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6159                         {
6160                                 out->mins[0] = min(out->mins[0], v[0]);
6161                                 out->maxs[0] = max(out->maxs[0], v[0]);
6162                                 out->mins[1] = min(out->mins[1], v[1]);
6163                                 out->maxs[1] = max(out->maxs[1], v[1]);
6164                                 out->mins[2] = min(out->mins[2], v[2]);
6165                                 out->maxs[2] = max(out->maxs[2], v[2]);
6166                         }
6167                         out->mins[0] -= 1.0f;
6168                         out->mins[1] -= 1.0f;
6169                         out->mins[2] -= 1.0f;
6170                         out->maxs[0] += 1.0f;
6171                         out->maxs[1] += 1.0f;
6172                         out->maxs[2] += 1.0f;
6173                 }
6174                 // set lightmap styles for consistency with q1bsp
6175                 //out->lightmapinfo->styles[0] = 0;
6176                 //out->lightmapinfo->styles[1] = 255;
6177                 //out->lightmapinfo->styles[2] = 255;
6178                 //out->lightmapinfo->styles[3] = 255;
6179         }
6180
6181         i = oldi;
6182         out = oldout;
6183         for (;i < count;i++, out++)
6184         {
6185                 if(out->num_vertices && out->num_triangles)
6186                         continue;
6187                 if(out->num_vertices == 0)
6188                 {
6189                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6190                         if(out->num_triangles == 0)
6191                                 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6192                 }
6193                 else if(out->num_triangles == 0)
6194                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s, near %f %f %f) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)",
6195                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6196                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6197                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6198         }
6199
6200         // for per pixel lighting
6201         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
6202
6203         // generate ushort elements array if possible
6204         if (loadmodel->surfmesh.data_element3s)
6205                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6206                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6207
6208         // free the no longer needed vertex data
6209         loadmodel->brushq3.num_vertices = 0;
6210         if (loadmodel->brushq3.data_vertex3f)
6211                 Mem_Free(loadmodel->brushq3.data_vertex3f);
6212         loadmodel->brushq3.data_vertex3f = NULL;
6213         loadmodel->brushq3.data_normal3f = NULL;
6214         loadmodel->brushq3.data_texcoordtexture2f = NULL;
6215         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6216         loadmodel->brushq3.data_color4f = NULL;
6217         // free the no longer needed triangle data
6218         loadmodel->brushq3.num_triangles = 0;
6219         if (loadmodel->brushq3.data_element3i)
6220                 Mem_Free(loadmodel->brushq3.data_element3i);
6221         loadmodel->brushq3.data_element3i = NULL;
6222
6223         if(patchtess)
6224                 Mem_Free(patchtess);
6225 }
6226
6227 static void Mod_Q3BSP_LoadModels(lump_t *l)
6228 {
6229         q3dmodel_t *in;
6230         q3dmodel_t *out;
6231         int i, j, n, c, count;
6232
6233         in = (q3dmodel_t *)(mod_base + l->fileofs);
6234         if (l->filelen % sizeof(*in))
6235                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6236         count = l->filelen / sizeof(*in);
6237         out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6238
6239         loadmodel->brushq3.data_models = out;
6240         loadmodel->brushq3.num_models = count;
6241
6242         for (i = 0;i < count;i++, in++, out++)
6243         {
6244                 for (j = 0;j < 3;j++)
6245                 {
6246                         out->mins[j] = LittleFloat(in->mins[j]);
6247                         out->maxs[j] = LittleFloat(in->maxs[j]);
6248                 }
6249                 n = LittleLong(in->firstface);
6250                 c = LittleLong(in->numfaces);
6251                 if (n < 0 || n + c > loadmodel->num_surfaces)
6252                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6253                 out->firstface = n;
6254                 out->numfaces = c;
6255                 n = LittleLong(in->firstbrush);
6256                 c = LittleLong(in->numbrushes);
6257                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6258                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6259                 out->firstbrush = n;
6260                 out->numbrushes = c;
6261         }
6262 }
6263
6264 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6265 {
6266         int *in;
6267         int *out;
6268         int i, n, count;
6269
6270         in = (int *)(mod_base + l->fileofs);
6271         if (l->filelen % sizeof(*in))
6272                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6273         count = l->filelen / sizeof(*in);
6274         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6275
6276         loadmodel->brush.data_leafbrushes = out;
6277         loadmodel->brush.num_leafbrushes = count;
6278
6279         for (i = 0;i < count;i++, in++, out++)
6280         {
6281                 n = LittleLong(*in);
6282                 if (n < 0 || n >= loadmodel->brush.num_brushes)
6283                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6284                 *out = n;
6285         }
6286 }
6287
6288 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6289 {
6290         int *in;
6291         int *out;
6292         int i, n, count;
6293
6294         in = (int *)(mod_base + l->fileofs);
6295         if (l->filelen % sizeof(*in))
6296                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6297         count = l->filelen / sizeof(*in);
6298         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6299
6300         loadmodel->brush.data_leafsurfaces = out;
6301         loadmodel->brush.num_leafsurfaces = count;
6302
6303         for (i = 0;i < count;i++, in++, out++)
6304         {
6305                 n = LittleLong(*in);
6306                 if (n < 0 || n >= loadmodel->num_surfaces)
6307                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6308                 *out = n;
6309         }
6310 }
6311
6312 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6313 {
6314         q3dleaf_t *in;
6315         mleaf_t *out;
6316         int i, j, n, c, count;
6317
6318         in = (q3dleaf_t *)(mod_base + l->fileofs);
6319         if (l->filelen % sizeof(*in))
6320                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6321         count = l->filelen / sizeof(*in);
6322         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6323
6324         loadmodel->brush.data_leafs = out;
6325         loadmodel->brush.num_leafs = count;
6326
6327         for (i = 0;i < count;i++, in++, out++)
6328         {
6329                 out->parent = NULL;
6330                 out->plane = NULL;
6331                 out->clusterindex = LittleLong(in->clusterindex);
6332                 out->areaindex = LittleLong(in->areaindex);
6333                 for (j = 0;j < 3;j++)
6334                 {
6335                         // yes the mins/maxs are ints
6336                         out->mins[j] = LittleLong(in->mins[j]) - 1;
6337                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6338                 }
6339                 n = LittleLong(in->firstleafface);
6340                 c = LittleLong(in->numleaffaces);
6341                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6342                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6343                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6344                 out->numleafsurfaces = c;
6345                 n = LittleLong(in->firstleafbrush);
6346                 c = LittleLong(in->numleafbrushes);
6347                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6348                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6349                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6350                 out->numleafbrushes = c;
6351         }
6352 }
6353
6354 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6355 {
6356         q3dnode_t *in;
6357         mnode_t *out;
6358         int i, j, n, count;
6359
6360         in = (q3dnode_t *)(mod_base + l->fileofs);
6361         if (l->filelen % sizeof(*in))
6362                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6363         count = l->filelen / sizeof(*in);
6364         if (count == 0)
6365                 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6366         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6367
6368         loadmodel->brush.data_nodes = out;
6369         loadmodel->brush.num_nodes = count;
6370
6371         for (i = 0;i < count;i++, in++, out++)
6372         {
6373                 out->parent = NULL;
6374                 n = LittleLong(in->planeindex);
6375                 if (n < 0 || n >= loadmodel->brush.num_planes)
6376                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6377                 out->plane = loadmodel->brush.data_planes + n;
6378                 for (j = 0;j < 2;j++)
6379                 {
6380                         n = LittleLong(in->childrenindex[j]);
6381                         if (n >= 0)
6382                         {
6383                                 if (n >= loadmodel->brush.num_nodes)
6384                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6385                                 out->children[j] = loadmodel->brush.data_nodes + n;
6386                         }
6387                         else
6388                         {
6389                                 n = -1 - n;
6390                                 if (n >= loadmodel->brush.num_leafs)
6391                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6392                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6393                         }
6394                 }
6395                 for (j = 0;j < 3;j++)
6396                 {
6397                         // yes the mins/maxs are ints
6398                         out->mins[j] = LittleLong(in->mins[j]) - 1;
6399                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6400                 }
6401         }
6402
6403         // set the parent pointers
6404         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6405 }
6406
6407 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6408 {
6409         q3dlightgrid_t *in;
6410         q3dlightgrid_t *out;
6411         int count;
6412         int i;
6413         int texturesize[3];
6414         unsigned char *texturergba, *texturelayer[3], *texturepadding[2];
6415         double lightgridmatrix[4][4];
6416
6417         in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6418         if (l->filelen % sizeof(*in))
6419                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6420         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6421         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6422         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6423         loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6424         loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6425         loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6426         loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6427         loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6428         loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6429         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6430         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6431         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6432         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6433         Matrix4x4_CreateScale3(&loadmodel->brushq3.num_lightgrid_indexfromworld, loadmodel->brushq3.num_lightgrid_scale[0], loadmodel->brushq3.num_lightgrid_scale[1], loadmodel->brushq3.num_lightgrid_scale[2]);
6434         Matrix4x4_ConcatTranslate(&loadmodel->brushq3.num_lightgrid_indexfromworld, -loadmodel->brushq3.num_lightgrid_imins[0] * loadmodel->brushq3.num_lightgrid_cellsize[0], -loadmodel->brushq3.num_lightgrid_imins[1] * loadmodel->brushq3.num_lightgrid_cellsize[1], -loadmodel->brushq3.num_lightgrid_imins[2] * loadmodel->brushq3.num_lightgrid_cellsize[2]);
6435
6436         // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6437         if (l->filelen)
6438         {
6439                 if (l->filelen < count * (int)sizeof(*in))
6440                 {
6441                         Con_Printf(CON_ERROR "Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)", l->filelen, (int)(count * sizeof(*in)), loadmodel->brushq3.num_lightgrid_isize[0], loadmodel->brushq3.num_lightgrid_isize[1], loadmodel->brushq3.num_lightgrid_isize[2]);
6442                         return; // ignore the grid if we cannot understand it
6443                 }
6444                 if (l->filelen != count * (int)sizeof(*in))
6445                         Con_Printf(CON_WARN "Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6446                 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6447                 loadmodel->brushq3.data_lightgrid = out;
6448                 loadmodel->brushq3.num_lightgrid = count;
6449                 // no swapping or validation necessary
6450                 memcpy(out, in, count * (int)sizeof(*out));
6451
6452                 if(mod_q3bsp_sRGBlightmaps.integer)
6453                 {
6454                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6455                         {
6456                                 // we fix the brightness consistently via lightmapscale
6457                         }
6458                         else
6459                         {
6460                                 for(i = 0; i < count; ++i)
6461                                 {
6462                                         out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6463                                         out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6464                                         out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6465                                         out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6466                                         out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6467                                         out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6468                                 }
6469                         }
6470                 }
6471                 else
6472                 {
6473                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6474                         {
6475                                 for(i = 0; i < count; ++i)
6476                                 {
6477                                         out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6478                                         out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6479                                         out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6480                                         out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6481                                         out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6482                                         out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6483                                 }
6484                         }
6485                         else
6486                         {
6487                                 // all is good
6488                         }
6489                 }
6490
6491                 if (mod_q3bsp_lightgrid_texture.integer)
6492                 {
6493                         // build a texture to hold the data for per-pixel sampling
6494                         // this has 3 different kinds of data stacked in it:
6495                         // ambient color
6496                         // bent-normal light color
6497                         // bent-normal light dir
6498
6499                         texturesize[0] = loadmodel->brushq3.num_lightgrid_isize[0];
6500                         texturesize[1] = loadmodel->brushq3.num_lightgrid_isize[1];
6501                         texturesize[2] = (loadmodel->brushq3.num_lightgrid_isize[2] + 2) * 3;
6502                         texturergba = (unsigned char*)Mem_Alloc(loadmodel->mempool, texturesize[0] * texturesize[1] * texturesize[2] * sizeof(char[4]));
6503                         texturelayer[0] = texturergba + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6504                         texturelayer[1] = texturelayer[0] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6505                         texturelayer[2] = texturelayer[1] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6506                         // the light dir layer needs padding above/below it that is a neutral unsigned normal (127,127,127,255)
6507                         texturepadding[0] = texturelayer[2] - loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6508                         texturepadding[1] = texturelayer[2] + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2] * 4;
6509                         for (i = 0; i < texturesize[0] * texturesize[1]; i++)
6510                         {
6511                                 texturepadding[0][i * 4] = texturepadding[1][i * 4] = 127;
6512                                 texturepadding[0][i * 4 + 1] = texturepadding[1][i * 4 + 1] = 127;
6513                                 texturepadding[0][i * 4 + 2] = texturepadding[1][i * 4 + 2] = 127;
6514                                 texturepadding[0][i * 4 + 3] = texturepadding[1][i * 4 + 3] = 255;
6515                         }
6516                         for (i = 0; i < count; i++)
6517                         {
6518                                 texturelayer[0][i * 4 + 0] = out[i].ambientrgb[0];
6519                                 texturelayer[0][i * 4 + 1] = out[i].ambientrgb[1];
6520                                 texturelayer[0][i * 4 + 2] = out[i].ambientrgb[2];
6521                                 texturelayer[0][i * 4 + 3] = 255;
6522                                 texturelayer[1][i * 4 + 0] = out[i].diffusergb[0];
6523                                 texturelayer[1][i * 4 + 1] = out[i].diffusergb[1];
6524                                 texturelayer[1][i * 4 + 2] = out[i].diffusergb[2];
6525                                 texturelayer[1][i * 4 + 3] = 255;
6526                                 // this uses the mod_md3_sin table because the values are
6527                                 // already in the 0-255 range, the 64+ bias fetches a cosine
6528                                 // instead of a sine value
6529                                 texturelayer[2][i * 4 + 0] = (char)((mod_md3_sin[64 + out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6530                                 texturelayer[2][i * 4 + 1] = (char)((mod_md3_sin[out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6531                                 texturelayer[2][i * 4 + 2] = (char)((mod_md3_sin[64 + out[i].diffusepitch]) * 127 + 127);
6532                                 texturelayer[2][i * 4 + 3] = 255;
6533                         }
6534 #if 0
6535                         // debugging hack
6536                         int x, y, z;
6537                         for (z = 0; z < loadmodel->brushq3.num_lightgrid_isize[2]; z++)
6538                         {
6539                                 for (y = 0; y < loadmodel->brushq3.num_lightgrid_isize[1]; y++)
6540                                 {
6541                                         for (x = 0; x < loadmodel->brushq3.num_lightgrid_isize[0]; x++)
6542                                         {
6543                                                 i = (z * texturesize[1] + y) * texturesize[0] + x;
6544                                                 texturelayer[0][i * 4 + 0] = x * 256 / loadmodel->brushq3.num_lightgrid_isize[0];
6545                                                 texturelayer[0][i * 4 + 1] = y * 256 / loadmodel->brushq3.num_lightgrid_isize[1];
6546                                                 texturelayer[0][i * 4 + 2] = z * 256 / loadmodel->brushq3.num_lightgrid_isize[2];
6547                                         }
6548                                 }
6549                         }
6550 #endif
6551                         loadmodel->brushq3.lightgridtexturesize[0] = texturesize[0];
6552                         loadmodel->brushq3.lightgridtexturesize[1] = texturesize[1];
6553                         loadmodel->brushq3.lightgridtexturesize[2] = texturesize[2];
6554                         memset(lightgridmatrix[0], 0, sizeof(lightgridmatrix));
6555                         lightgridmatrix[0][0] = loadmodel->brushq3.num_lightgrid_scale[0] / texturesize[0];
6556                         lightgridmatrix[1][1] = loadmodel->brushq3.num_lightgrid_scale[1] / texturesize[1];
6557                         lightgridmatrix[2][2] = loadmodel->brushq3.num_lightgrid_scale[2] / texturesize[2];
6558                         lightgridmatrix[0][3] = -(loadmodel->brushq3.num_lightgrid_imins[0] - 0.5f) / texturesize[0];
6559                         lightgridmatrix[1][3] = -(loadmodel->brushq3.num_lightgrid_imins[1] - 0.5f) / texturesize[1];
6560                         lightgridmatrix[2][3] = -(loadmodel->brushq3.num_lightgrid_imins[2] - 1.5f) / texturesize[2];
6561                         lightgridmatrix[3][3] = 1;
6562                         Matrix4x4_FromArrayDoubleD3D(&loadmodel->brushq3.lightgridworldtotexturematrix, lightgridmatrix);
6563                         loadmodel->brushq3.lightgridtexture = R_LoadTexture3D(loadmodel->texturepool, "lightgrid", texturesize[0], texturesize[1], texturesize[2], texturergba, TEXTYPE_RGBA, TEXF_CLAMP, 0, NULL);
6564                         Mem_Free(texturergba);
6565                 }
6566         }
6567 }
6568
6569 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6570 {
6571         q3dpvs_t *in;
6572         int totalchains;
6573
6574         if (l->filelen == 0)
6575         {
6576                 int i;
6577                 // unvised maps often have cluster indices even without pvs, so check
6578                 // leafs to find real number of clusters
6579                 loadmodel->brush.num_pvsclusters = 1;
6580                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6581                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6582
6583                 // create clusters
6584                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6585                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6586                 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6587                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6588                 return;
6589         }
6590
6591         in = (q3dpvs_t *)(mod_base + l->fileofs);
6592         if (l->filelen < 9)
6593                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6594
6595         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6596         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6597         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6598                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6599         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6600         if (l->filelen < totalchains + (int)sizeof(*in))
6601                 Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, (int)(totalchains + sizeof(*in)), l->filelen);
6602
6603         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6604         memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6605 }
6606
6607 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6608 {
6609         int i, j, k, index[3];
6610         float transformed[3], blend1, blend2, blend, stylescale = 1;
6611         q3dlightgrid_t *a, *s;
6612
6613         // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6614         // LadyHavoc: FIXME: is this true?
6615         stylescale = 1; // added while render
6616         //stylescale = r_refdef.scene.rtlightstylevalue[0];
6617
6618         if (!model->brushq3.num_lightgrid)
6619         {
6620                 ambientcolor[0] = stylescale;
6621                 ambientcolor[1] = stylescale;
6622                 ambientcolor[2] = stylescale;
6623                 return;
6624         }
6625
6626         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6627         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6628         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6629         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6630         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6631         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6632         index[0] = (int)floor(transformed[0]);
6633         index[1] = (int)floor(transformed[1]);
6634         index[2] = (int)floor(transformed[2]);
6635         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6636
6637         // now lerp the values
6638         VectorClear(diffusenormal);
6639         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6640         for (k = 0;k < 2;k++)
6641         {
6642                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6643                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6644                         continue;
6645                 for (j = 0;j < 2;j++)
6646                 {
6647                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6648                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6649                                 continue;
6650                         for (i = 0;i < 2;i++)
6651                         {
6652                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6653                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6654                                         continue;
6655                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6656                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6657                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6658                                 // this uses the mod_md3_sin table because the values are
6659                                 // already in the 0-255 range, the 64+ bias fetches a cosine
6660                                 // instead of a sine value
6661                                 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6662                                 diffusenormal[1] += blend * (mod_md3_sin[     s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6663                                 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6664                                 //Con_Printf("blend %f: ambient %i %i %i, diffuse %i %i %i, diffusepitch %i diffuseyaw %i (%f %f, normal %f %f %f)\n", blend, s->ambientrgb[0], s->ambientrgb[1], s->ambientrgb[2], s->diffusergb[0], s->diffusergb[1], s->diffusergb[2], s->diffusepitch, s->diffuseyaw, pitch, yaw, (cos(yaw) * cospitch), (sin(yaw) * cospitch), (-sin(pitch)));
6665                         }
6666                 }
6667         }
6668
6669         // normalize the light direction before turning
6670         VectorNormalize(diffusenormal);
6671         //Con_Printf("result: ambient %f %f %f diffuse %f %f %f diffusenormal %f %f %f\n", ambientcolor[0], ambientcolor[1], ambientcolor[2], diffusecolor[0], diffusecolor[1], diffusecolor[2], diffusenormal[0], diffusenormal[1], diffusenormal[2]);
6672 }
6673
6674 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3], double endpos[3])
6675 {
6676         double t1, t2;
6677         double midf, mid[3];
6678         int ret, side;
6679
6680         // check for empty
6681         while (node->plane)
6682         {
6683                 // find the point distances
6684                 mplane_t *plane = node->plane;
6685                 if (plane->type < 3)
6686                 {
6687                         t1 = p1[plane->type] - plane->dist;
6688                         t2 = p2[plane->type] - plane->dist;
6689                 }
6690                 else
6691                 {
6692                         t1 = DotProduct (plane->normal, p1) - plane->dist;
6693                         t2 = DotProduct (plane->normal, p2) - plane->dist;
6694                 }
6695
6696                 if (t1 < 0)
6697                 {
6698                         if (t2 < 0)
6699                         {
6700                                 node = node->children[1];
6701                                 continue;
6702                         }
6703                         side = 1;
6704                 }
6705                 else
6706                 {
6707                         if (t2 >= 0)
6708                         {
6709                                 node = node->children[0];
6710                                 continue;
6711                         }
6712                         side = 0;
6713                 }
6714
6715                 midf = t1 / (t1 - t2);
6716                 VectorLerp(p1, midf, p2, mid);
6717
6718                 // recurse both sides, front side first
6719                 // return 2 if empty is followed by solid (hit something)
6720                 // do not return 2 if both are solid or both empty,
6721                 // or if start is solid and end is empty
6722                 // as these degenerate cases usually indicate the eye is in solid and
6723                 // should see the target point anyway
6724                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side    ], p1, mid, endpos);
6725                 if (ret != 0)
6726                         return ret;
6727                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2, endpos);
6728                 if (ret != 1)
6729                         return ret;
6730                 VectorCopy(mid, endpos);
6731                 return 2;
6732         }
6733         return ((mleaf_t *)node)->clusterindex < 0;
6734 }
6735
6736 static qbool Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
6737 {
6738         if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6739         {
6740                 trace_t trace;
6741                 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
6742                 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
6743         }
6744         else
6745         {
6746                 double tracestart[3], traceend[3], traceendpos[3];
6747                 VectorCopy(start, tracestart);
6748                 VectorCopy(end, traceend);
6749                 VectorCopy(end, traceendpos);
6750                 Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend, traceendpos);
6751                 return BoxesOverlap(traceendpos, traceendpos, acceptmins, acceptmaxs);
6752         }
6753 }
6754
6755 void Mod_CollisionBIH_TracePoint(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
6756 {
6757         const bih_t *bih;
6758         const bih_leaf_t *leaf;
6759         const bih_node_t *node;
6760         const colbrushf_t *brush;
6761         int axis;
6762         int nodenum;
6763         int nodestackpos = 0;
6764         int nodestack[1024];
6765
6766         memset(trace, 0, sizeof(*trace));
6767         trace->fraction = 1;
6768         trace->hitsupercontentsmask = hitsupercontentsmask;
6769         trace->skipsupercontentsmask = skipsupercontentsmask;
6770         trace->skipmaterialflagsmask = skipmaterialflagsmask;
6771
6772         bih = &model->collision_bih;
6773         if(!bih->nodes)
6774                 return;
6775
6776         nodenum = bih->rootnode;
6777         nodestack[nodestackpos++] = nodenum;
6778         while (nodestackpos)
6779         {
6780                 nodenum = nodestack[--nodestackpos];
6781                 node = bih->nodes + nodenum;
6782 #if 1
6783                 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6784                         continue;
6785 #endif
6786                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6787                 {
6788                         axis = node->type - BIH_SPLITX;
6789                         if (start[axis] >= node->frontmin)
6790                                 nodestack[nodestackpos++] = node->front;
6791                         if (start[axis] <= node->backmax)
6792                                 nodestack[nodestackpos++] = node->back;
6793                 }
6794                 else if (node->type == BIH_UNORDERED)
6795                 {
6796                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6797                         {
6798                                 leaf = bih->leafs + node->children[axis];
6799 #if 1
6800                                 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6801                                         continue;
6802 #endif
6803                                 switch(leaf->type)
6804                                 {
6805                                 case BIH_BRUSH:
6806                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6807                                         Collision_TracePointBrushFloat(trace, start, brush);
6808                                         break;
6809                                 case BIH_COLLISIONTRIANGLE:
6810                                         // collision triangle - skipped because they have no volume
6811                                         break;
6812                                 case BIH_RENDERTRIANGLE:
6813                                         // render triangle - skipped because they have no volume
6814                                         break;
6815                                 }
6816                         }
6817                 }
6818         }
6819 }
6820
6821 static void Mod_CollisionBIH_TraceLineShared(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, const bih_t *bih)
6822 {
6823         const bih_leaf_t *leaf;
6824         const bih_node_t *node;
6825         const colbrushf_t *brush;
6826         const int *e;
6827         const texture_t *texture;
6828         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6829         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6830         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6831
6832         if(!bih->nodes)
6833                 return;
6834
6835         if (VectorCompare(start, end))
6836         {
6837                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6838                 return;
6839         }
6840
6841         nodenum = bih->rootnode;
6842
6843         memset(trace, 0, sizeof(*trace));
6844         trace->fraction = 1;
6845         trace->hitsupercontentsmask = hitsupercontentsmask;
6846         trace->skipsupercontentsmask = skipsupercontentsmask;
6847         trace->skipmaterialflagsmask = skipmaterialflagsmask;
6848
6849         // push first node
6850         nodestackline[nodestackpos][0] = start[0];
6851         nodestackline[nodestackpos][1] = start[1];
6852         nodestackline[nodestackpos][2] = start[2];
6853         nodestackline[nodestackpos][3] = end[0];
6854         nodestackline[nodestackpos][4] = end[1];
6855         nodestackline[nodestackpos][5] = end[2];
6856         nodestack[nodestackpos++] = nodenum;
6857         while (nodestackpos)
6858         {
6859                 nodenum = nodestack[--nodestackpos];
6860                 node = bih->nodes + nodenum;
6861                 VectorCopy(nodestackline[nodestackpos], nodestart);
6862                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6863                 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6864                 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6865                 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6866                 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6867                 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6868                 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6869                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs) && !collision_bih_fullrecursion.integer)
6870                         continue;
6871                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6872                 {
6873                         // recurse children of the split
6874                         axis = node->type - BIH_SPLITX;
6875                         d1 = node->backmax - nodestart[axis];
6876                         d2 = node->backmax - nodeend[axis];
6877                         d3 = nodestart[axis] - node->frontmin;
6878                         d4 = nodeend[axis] - node->frontmin;
6879                         if (collision_bih_fullrecursion.integer)
6880                                 d1 = d2 = d3 = d4 = 1; // force full recursion
6881                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6882                         {
6883                         case  0: /* >>>> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6884                         case  1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6885                         case  2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6886                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6887                         case  4: /* >><> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6888                         case  5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6889                         case  6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6890                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6891                         case  8: /* >>>< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6892                         case  9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6893                         case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6894                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6895                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6896                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6897                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6898                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
6899                         }
6900                 }
6901                 else if (node->type == BIH_UNORDERED)
6902                 {
6903                         // calculate sweep bounds for this node
6904                         // copy node bounds into local variables
6905                         VectorCopy(node->mins, nodebigmins);
6906                         VectorCopy(node->maxs, nodebigmaxs);
6907                         // clip line to this node bounds
6908                         axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6909                         axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6910                         axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6911                         // some of the line intersected the enlarged node box
6912                         // calculate sweep bounds for this node
6913                         sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6914                         sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6915                         sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6916                         sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6917                         sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6918                         sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6919                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6920                         {
6921                                 leaf = bih->leafs + node->children[axis];
6922                                 // TODO: This is very expensive in Steel Storm. Framerate halved during even light combat.
6923                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6924                                         continue;
6925                                 switch(leaf->type)
6926                                 {
6927                                 case BIH_BRUSH:
6928                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6929                                         Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6930                                         break;
6931                                 case BIH_COLLISIONTRIANGLE:
6932                                         if (!mod_q3bsp_curves_collisions.integer)
6933                                                 continue;
6934                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6935                                         texture = model->data_textures + leaf->textureindex;
6936                                         Collision_TraceLineTriangleFloat(trace, start, end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6937                                         break;
6938                                 case BIH_RENDERTRIANGLE:
6939                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6940                                         texture = model->data_textures + leaf->textureindex;
6941                                         Collision_TraceLineTriangleFloat(trace, start, end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6942                                         break;
6943                                 }
6944                         }
6945                 }
6946         }
6947 }
6948
6949 void Mod_CollisionBIH_TraceLine(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
6950 {
6951         if (VectorCompare(start, end))
6952         {
6953                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6954                 return;
6955         }
6956         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->collision_bih);
6957 }
6958
6959 void Mod_CollisionBIH_TraceBrush(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *thisbrush_start, colbrushf_t *thisbrush_end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
6960 {
6961         const bih_t *bih;
6962         const bih_leaf_t *leaf;
6963         const bih_node_t *node;
6964         const colbrushf_t *brush;
6965         const int *e;
6966         const texture_t *texture;
6967         vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6968         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6969         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6970         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6971
6972         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6973         {
6974                 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6975                         Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6976                 else
6977                         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6978                 return;
6979         }
6980
6981         bih = &model->collision_bih;
6982         if(!bih->nodes)
6983                 return;
6984         nodenum = bih->rootnode;
6985
6986         // box trace, performed as brush trace
6987         memset(trace, 0, sizeof(*trace));
6988         trace->fraction = 1;
6989         trace->hitsupercontentsmask = hitsupercontentsmask;
6990         trace->skipsupercontentsmask = skipsupercontentsmask;
6991         trace->skipmaterialflagsmask = skipmaterialflagsmask;
6992
6993         // calculate tracebox-like parameters for efficient culling
6994         VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6995         VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6996         VectorSubtract(thisbrush_start->mins, start, startmins);
6997         VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6998         VectorSubtract(thisbrush_end->mins, end, endmins);
6999         VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7000         mins[0] = min(startmins[0], endmins[0]);
7001         mins[1] = min(startmins[1], endmins[1]);
7002         mins[2] = min(startmins[2], endmins[2]);
7003         maxs[0] = max(startmaxs[0], endmaxs[0]);
7004         maxs[1] = max(startmaxs[1], endmaxs[1]);
7005         maxs[2] = max(startmaxs[2], endmaxs[2]);
7006
7007         // push first node
7008         nodestackline[nodestackpos][0] = start[0];
7009         nodestackline[nodestackpos][1] = start[1];
7010         nodestackline[nodestackpos][2] = start[2];
7011         nodestackline[nodestackpos][3] = end[0];
7012         nodestackline[nodestackpos][4] = end[1];
7013         nodestackline[nodestackpos][5] = end[2];
7014         nodestack[nodestackpos++] = nodenum;
7015         while (nodestackpos)
7016         {
7017                 nodenum = nodestack[--nodestackpos];
7018                 node = bih->nodes + nodenum;
7019                 VectorCopy(nodestackline[nodestackpos], nodestart);
7020                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7021                 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7022                 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7023                 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7024                 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7025                 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7026                 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7027                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7028                         continue;
7029                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7030                 {
7031                         // recurse children of the split
7032                         axis = node->type - BIH_SPLITX;
7033                         d1 = node->backmax - nodestart[axis] - mins[axis];
7034                         d2 = node->backmax - nodeend[axis] - mins[axis];
7035                         d3 = nodestart[axis] - node->frontmin + maxs[axis];
7036                         d4 = nodeend[axis] - node->frontmin + maxs[axis];
7037                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7038                         {
7039                         case  0: /* >>>> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7040                         case  1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7041                         case  2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7042                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7043                         case  4: /* >><> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7044                         case  5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7045                         case  6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7046                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7047                         case  8: /* >>>< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7048                         case  9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7049                         case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7050                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7051                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7052                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7053                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7054                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
7055                         }
7056                 }
7057                 else if (node->type == BIH_UNORDERED)
7058                 {
7059                         // calculate sweep bounds for this node
7060                         // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7061                         VectorSubtract(node->mins, maxs, nodebigmins);
7062                         VectorSubtract(node->maxs, mins, nodebigmaxs);
7063                         // clip line to this node bounds
7064                         axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
7065                         axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
7066                         axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
7067                         // some of the line intersected the enlarged node box
7068                         // calculate sweep bounds for this node
7069                         sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7070                         sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7071                         sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7072                         sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7073                         sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7074                         sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7075                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7076                         {
7077                                 leaf = bih->leafs + node->children[axis];
7078                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7079                                         continue;
7080                                 switch(leaf->type)
7081                                 {
7082                                 case BIH_BRUSH:
7083                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7084                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7085                                         break;
7086                                 case BIH_COLLISIONTRIANGLE:
7087                                         if (!mod_q3bsp_curves_collisions.integer)
7088                                                 continue;
7089                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7090                                         texture = model->data_textures + leaf->textureindex;
7091                                         Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
7092                                         break;
7093                                 case BIH_RENDERTRIANGLE:
7094                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7095                                         texture = model->data_textures + leaf->textureindex;
7096                                         Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
7097                                         break;
7098                                 }
7099                         }
7100                 }
7101         }
7102 }
7103
7104 void Mod_CollisionBIH_TraceBox(model_t *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, int skipmaterialflagsmask)
7105 {
7106         colboxbrushf_t thisbrush_start, thisbrush_end;
7107         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7108
7109         // box trace, performed as brush trace
7110         VectorAdd(start, boxmins, boxstartmins);
7111         VectorAdd(start, boxmaxs, boxstartmaxs);
7112         VectorAdd(end, boxmins, boxendmins);
7113         VectorAdd(end, boxmaxs, boxendmaxs);
7114         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7115         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7116         Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7117 }
7118
7119
7120 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7121 {
7122         trace_t trace;
7123         Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0, 0);
7124         return trace.startsupercontents;
7125 }
7126
7127 qbool Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
7128 {
7129         trace_t trace;
7130         Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
7131         return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
7132 }
7133
7134 void Mod_CollisionBIH_TracePoint_Mesh(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7135 {
7136 #if 0
7137         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7138         vec3_t end;
7139         int hitsupercontents;
7140         VectorSet(end, start[0], start[1], model->normalmins[2]);
7141 #endif
7142         memset(trace, 0, sizeof(*trace));
7143         trace->fraction = 1;
7144         trace->hitsupercontentsmask = hitsupercontentsmask;
7145         trace->skipsupercontentsmask = skipsupercontentsmask;
7146         trace->skipmaterialflagsmask = skipmaterialflagsmask;
7147 #if 0
7148         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7149         hitsupercontents = trace->hitsupercontents;
7150         memset(trace, 0, sizeof(*trace));
7151         trace->fraction = 1;
7152         trace->hitsupercontentsmask = hitsupercontentsmask;
7153         trace->skipsupercontentsmask = skipsupercontentsmask;
7154         trace->skipmaterialflagsmask = skipmaterialflagsmask;
7155         trace->startsupercontents = hitsupercontents;
7156 #endif
7157 }
7158
7159 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7160 {
7161 #if 0
7162         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7163         trace_t trace;
7164         vec3_t end;
7165         VectorSet(end, start[0], start[1], model->normalmins[2]);
7166         memset(&trace, 0, sizeof(trace));
7167         trace.fraction = 1;
7168         trace.hitsupercontentsmask = hitsupercontentsmask;
7169         trace.skipsupercontentsmask = skipsupercontentsmask;
7170         trace.skipmaterialflagsmask = skipmaterialflagsmask;
7171         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7172         return trace.hitsupercontents;
7173 #else
7174         return 0;
7175 #endif
7176 }
7177
7178 void Mod_CollisionBIH_TraceLineAgainstSurfaces(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7179 {
7180         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->render_bih);
7181 }
7182
7183
7184 bih_t *Mod_MakeCollisionBIH(model_t *model, qbool userendersurfaces, bih_t *out)
7185 {
7186         int j;
7187         int bihnumleafs;
7188         int bihmaxnodes;
7189         int brushindex;
7190         int triangleindex;
7191         int bihleafindex;
7192         int nummodelbrushes = model->nummodelbrushes;
7193         const int *e;
7194         const int *collisionelement3i;
7195         const float *collisionvertex3f;
7196         const int *renderelement3i;
7197         const float *rendervertex3f;
7198         bih_leaf_t *bihleafs;
7199         bih_node_t *bihnodes;
7200         int *temp_leafsort;
7201         int *temp_leafsortscratch;
7202         const msurface_t *surface;
7203         const q3mbrush_t *brush;
7204
7205         // find out how many BIH leaf nodes we need
7206         bihnumleafs = 0;
7207         if (userendersurfaces)
7208         {
7209                 for (j = model->submodelsurfaces_start;j < model->submodelsurfaces_end;j++)
7210                         bihnumleafs += model->data_surfaces[j].num_triangles;
7211         }
7212         else
7213         {
7214                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7215                         if (brush->colbrushf)
7216                                 bihnumleafs++;
7217                 for (j = model->submodelsurfaces_start;j < model->submodelsurfaces_end;j++)
7218                 {
7219                         if (model->data_surfaces[j].texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7220                                 bihnumleafs += model->data_surfaces[j].num_triangles + model->data_surfaces[j].num_collisiontriangles;
7221                         else
7222                                 bihnumleafs += model->data_surfaces[j].num_collisiontriangles;
7223                 }
7224         }
7225
7226         if (!bihnumleafs)
7227                 return NULL;
7228
7229         // allocate the memory for the BIH leaf nodes
7230         bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7231
7232         // now populate the BIH leaf nodes
7233         bihleafindex = 0;
7234
7235         // add render surfaces
7236         renderelement3i = model->surfmesh.data_element3i;
7237         rendervertex3f = model->surfmesh.data_vertex3f;
7238         for (j = model->submodelsurfaces_start; j < model->submodelsurfaces_end; j++)
7239         {
7240                 surface = model->data_surfaces + j;
7241                 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7242                 {
7243                         if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7244                                 continue;
7245                         bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7246                         bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7247                         bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7248                         bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7249                         bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7250                         bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7251                         bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7252                         bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7253                         bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7254                         bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7255                         bihleafindex++;
7256                 }
7257         }
7258
7259         if (!userendersurfaces)
7260         {
7261                 // add collision brushes
7262                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7263                 {
7264                         if (!brush->colbrushf)
7265                                 continue;
7266                         bihleafs[bihleafindex].type = BIH_BRUSH;
7267                         bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7268                         bihleafs[bihleafindex].surfaceindex = -1;
7269                         bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7270                         VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7271                         VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7272                         bihleafindex++;
7273                 }
7274
7275                 // add collision surfaces
7276                 collisionelement3i = model->brush.data_collisionelement3i;
7277                 collisionvertex3f = model->brush.data_collisionvertex3f;
7278                 for (j = model->submodelsurfaces_start; j < model->submodelsurfaces_end; j++)
7279                 {
7280                         surface = model->data_surfaces + j;
7281                         for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7282                         {
7283                                 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7284                                 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7285                                 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7286                                 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7287                                 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7288                                 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7289                                 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7290                                 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7291                                 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7292                                 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7293                                 bihleafindex++;
7294                         }
7295                 }
7296         }
7297
7298         // allocate buffers for the produced and temporary data
7299         bihmaxnodes = bihnumleafs + 1;
7300         bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7301         temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7302         temp_leafsortscratch = temp_leafsort + bihnumleafs;
7303
7304         // now build it
7305         BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7306
7307         // we're done with the temporary data
7308         Mem_Free(temp_leafsort);
7309
7310         // resize the BIH nodes array if it over-allocated
7311         if (out->maxnodes > out->numnodes)
7312         {
7313                 out->maxnodes = out->numnodes;
7314                 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7315         }
7316
7317         return out;
7318 }
7319
7320 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents)
7321 {
7322         int supercontents = 0;
7323         if (nativecontents & CONTENTSQ3_SOLID)
7324                 supercontents |= SUPERCONTENTS_SOLID;
7325         if (nativecontents & CONTENTSQ3_WATER)
7326                 supercontents |= SUPERCONTENTS_WATER;
7327         if (nativecontents & CONTENTSQ3_SLIME)
7328                 supercontents |= SUPERCONTENTS_SLIME;
7329         if (nativecontents & CONTENTSQ3_LAVA)
7330                 supercontents |= SUPERCONTENTS_LAVA;
7331         if (nativecontents & CONTENTSQ3_BODY)
7332                 supercontents |= SUPERCONTENTS_BODY;
7333         if (nativecontents & CONTENTSQ3_CORPSE)
7334                 supercontents |= SUPERCONTENTS_CORPSE;
7335         if (nativecontents & CONTENTSQ3_NODROP)
7336                 supercontents |= SUPERCONTENTS_NODROP;
7337         if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7338                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7339         if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7340                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7341         if (nativecontents & CONTENTSQ3_DONOTENTER)
7342                 supercontents |= SUPERCONTENTS_DONOTENTER;
7343         if (nativecontents & CONTENTSQ3_BOTCLIP)
7344                 supercontents |= SUPERCONTENTS_BOTCLIP;
7345         if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7346                 supercontents |= SUPERCONTENTS_OPAQUE;
7347         return supercontents;
7348 }
7349
7350 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents)
7351 {
7352         int nativecontents = 0;
7353         if (supercontents & SUPERCONTENTS_SOLID)
7354                 nativecontents |= CONTENTSQ3_SOLID;
7355         if (supercontents & SUPERCONTENTS_WATER)
7356                 nativecontents |= CONTENTSQ3_WATER;
7357         if (supercontents & SUPERCONTENTS_SLIME)
7358                 nativecontents |= CONTENTSQ3_SLIME;
7359         if (supercontents & SUPERCONTENTS_LAVA)
7360                 nativecontents |= CONTENTSQ3_LAVA;
7361         if (supercontents & SUPERCONTENTS_BODY)
7362                 nativecontents |= CONTENTSQ3_BODY;
7363         if (supercontents & SUPERCONTENTS_CORPSE)
7364                 nativecontents |= CONTENTSQ3_CORPSE;
7365         if (supercontents & SUPERCONTENTS_NODROP)
7366                 nativecontents |= CONTENTSQ3_NODROP;
7367         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7368                 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7369         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7370                 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7371         if (supercontents & SUPERCONTENTS_DONOTENTER)
7372                 nativecontents |= CONTENTSQ3_DONOTENTER;
7373         if (supercontents & SUPERCONTENTS_BOTCLIP)
7374                 nativecontents |= CONTENTSQ3_BOTCLIP;
7375         if (!(supercontents & SUPERCONTENTS_OPAQUE))
7376                 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7377         return nativecontents;
7378 }
7379
7380 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7381 {
7382         int numleafs;
7383         while (node->plane)
7384         {
7385                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7386                 node = node->children[1];
7387         }
7388         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7389         if (loadmodel->brush.num_leafs < numleafs)
7390                 loadmodel->brush.num_leafs = numleafs;
7391 }
7392
7393 static void Mod_Q3BSP_Load(model_t *mod, void *buffer, void *bufferend)
7394 {
7395         int i, j, lumps;
7396         q3dheader_t *header;
7397         float corner[3], yawradius, modelradius;
7398
7399         mod->modeldatatypestring = "Q3BSP";
7400
7401         mod->type = mod_brushq3;
7402         mod->brush.ishlbsp = false;
7403         mod->brush.isbsp2rmqe = false;
7404         mod->brush.isbsp2 = false;
7405         mod->brush.isq2bsp = false;
7406         mod->brush.isq3bsp = true;
7407         mod->brush.skymasking = true;
7408         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7409         mod->numskins = 1;
7410
7411         header = (q3dheader_t *)buffer;
7412         if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7413                 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7414
7415         i = LittleLong(header->version);
7416         if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7417                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7418
7419         mod->soundfromcenter = true;
7420         mod->TraceBox = Mod_CollisionBIH_TraceBox;
7421         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
7422         mod->TraceLine = Mod_CollisionBIH_TraceLine;
7423         mod->TracePoint = Mod_CollisionBIH_TracePoint;
7424         mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
7425         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7426         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7427         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7428         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7429         mod->brush.GetPVS = Mod_BSP_GetPVS;
7430         mod->brush.FatPVS = Mod_BSP_FatPVS;
7431         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
7432         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
7433         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
7434         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
7435         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7436         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
7437         mod->brush.AmbientSoundLevelsForPoint = NULL;
7438         mod->brush.RoundUpToHullSize = NULL;
7439         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
7440         mod->Draw = R_Mod_Draw;
7441         mod->DrawDepth = R_Mod_DrawDepth;
7442         mod->DrawDebug = R_Mod_DrawDebug;
7443         mod->DrawPrepass = R_Mod_DrawPrepass;
7444         mod->GetLightInfo = R_Mod_GetLightInfo;
7445         mod->CompileShadowMap = R_Mod_CompileShadowMap;
7446         mod->DrawShadowMap = R_Mod_DrawShadowMap;
7447         mod->DrawLight = R_Mod_DrawLight;
7448
7449         mod_base = (unsigned char *)header;
7450
7451         // swap all the lumps
7452         header->ident = LittleLong(header->ident);
7453         header->version = LittleLong(header->version);
7454         lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7455         for (i = 0;i < lumps;i++)
7456         {
7457                 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7458                 if((char *) bufferend < (char *) buffer + j)
7459                         Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7460                 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7461                 if((char *) bufferend < (char *) buffer + j)
7462                         Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7463         }
7464         /*
7465          * NO, do NOT clear them!
7466          * they contain actual data referenced by other stuff.
7467          * Instead, before using the advertisements lump, check header->versio
7468          * again!
7469          * Sorry, but otherwise it breaks memory of the first lump.
7470         for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7471         {
7472                 header->lumps[i].fileofs = 0;
7473                 header->lumps[i].filelen = 0;
7474         }
7475         */
7476
7477         mod->brush.qw_md4sum = 0;
7478         mod->brush.qw_md4sum2 = 0;
7479         for (i = 0;i < lumps;i++)
7480         {
7481                 if (i == Q3LUMP_ENTITIES)
7482                         continue;
7483                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7484                 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7485                         continue;
7486                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7487
7488                 // all this checksumming can take a while, so let's send keepalives here too
7489                 CL_KeepaliveMessage(false);
7490         }
7491
7492         // allocate a texture pool if we need it
7493         if (mod->texturepool == NULL)
7494                 mod->texturepool = R_AllocTexturePool();
7495
7496         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7497         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7498         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7499         if (header->version == Q3BSPVERSION_IG)
7500                 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7501         else
7502                 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7503         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7504         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7505         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7506         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7507         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7508         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7509         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7510         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7511         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7512         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7513         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7514         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7515         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7516         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7517
7518         // the MakePortals code works fine on the q3bsp data as well
7519         if (mod_bsp_portalize.integer)
7520                 Mod_BSP_MakePortals();
7521
7522         // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7523         loadmodel->brush.supportwateralpha = true;
7524
7525         loadmodel->brush.num_leafs = 0;
7526         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7527
7528         if (loadmodel->brush.numsubmodels)
7529                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
7530
7531         mod = loadmodel;
7532         mod->modelsurfaces_sorted = (int*)Mem_Alloc(loadmodel->mempool, mod->num_surfaces * sizeof(*mod->modelsurfaces_sorted));
7533         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7534         {
7535                 if (i > 0)
7536                 {
7537                         char name[10];
7538                         // duplicate the basic information
7539                         dpsnprintf(name, sizeof(name), "*%i", i);
7540                         mod = Mod_FindName(name, loadmodel->name);
7541                         // copy the base model to this one
7542                         *mod = *loadmodel;
7543                         // rename the clone back to its proper name
7544                         strlcpy(mod->name, name, sizeof(mod->name));
7545                         mod->brush.parentmodel = loadmodel;
7546                         // textures and memory belong to the main model
7547                         mod->texturepool = NULL;
7548                         mod->mempool = NULL;
7549                         mod->brush.GetPVS = NULL;
7550                         mod->brush.FatPVS = NULL;
7551                         mod->brush.BoxTouchingPVS = NULL;
7552                         mod->brush.BoxTouchingLeafPVS = NULL;
7553                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7554                         mod->brush.FindBoxClusters = NULL;
7555                         mod->brush.LightPoint = NULL;
7556                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7557                 }
7558                 mod->brush.submodel = i;
7559                 if (loadmodel->brush.submodels)
7560                         loadmodel->brush.submodels[i] = mod;
7561
7562                 // make the model surface list (used by shadowing/lighting)
7563                 mod->submodelsurfaces_start = mod->brushq3.data_models[i].firstface;
7564                 mod->submodelsurfaces_end = mod->brushq3.data_models[i].firstface + mod->brushq3.data_models[i].numfaces;
7565                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7566                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7567
7568                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7569                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7570                 // enlarge the bounding box to enclose all geometry of this model,
7571                 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7572                 // which can in turn mess up the farclip (as well as culling when
7573                 // outside the level - an unimportant concern)
7574
7575                 //printf("Editing model %d... BEFORE re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7576                 for (j = mod->submodelsurfaces_start;j < mod->submodelsurfaces_end;j++)
7577                 {
7578                         const msurface_t *surface = mod->data_surfaces + j;
7579                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7580                         int k;
7581                         if (!surface->num_vertices)
7582                                 continue;
7583                         for (k = 0;k < surface->num_vertices;k++, v += 3)
7584                         {
7585                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7586                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7587                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7588                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7589                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7590                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7591                         }
7592                 }
7593                 //printf("Editing model %d... AFTER re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7594                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7595                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7596                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7597                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7598                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7599                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7600                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7601                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7602                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7603                 mod->yawmins[2] = mod->normalmins[2];
7604                 mod->yawmaxs[2] = mod->normalmaxs[2];
7605                 mod->radius = modelradius;
7606                 mod->radius2 = modelradius * modelradius;
7607
7608                 Mod_SetDrawSkyAndWater(mod);
7609                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7610                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7611
7612                 // generate VBOs and other shared data before cloning submodels
7613                 if (i == 0)
7614                         Mod_BuildVBOs();
7615         }
7616         mod = loadmodel;
7617
7618         // make the model surface list (used by shadowing/lighting)
7619         Mod_MakeSortedSurfaces(loadmodel);
7620
7621         if (mod_q3bsp_sRGBlightmaps.integer)
7622         {
7623                 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7624                 {
7625                         // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7626                         // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7627                         // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7628                         // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7629                         //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7630                 }
7631                 else // if this is NOT set, regular rendering looks right by this requirement anyway
7632                 {
7633                         /*
7634                         // we want color 1 to do the same as without sRGB
7635                         // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7636                         loadmodel->lightmapscale *= 2.476923f; // fixes max level
7637                         */
7638
7639                         // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7640                         // we need to undo that
7641                         loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7642                 }
7643         }
7644
7645         Con_DPrintf("Stats for q3bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
7646 }
7647
7648 void Mod_IBSP_Load(model_t *mod, void *buffer, void *bufferend)
7649 {
7650         int i = LittleLong(((int *)buffer)[1]);
7651         if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7652                 Mod_Q3BSP_Load(mod,buffer, bufferend);
7653         else if (i == Q2BSPVERSION)
7654                 Mod_Q2BSP_Load(mod,buffer, bufferend);
7655         else
7656                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7657 }
7658
7659 static void Mod_VBSP_LoadEntities(sizebuf_t *sb)
7660 {
7661         loadmodel->brush.entities = NULL;
7662         if (!sb->cursize)
7663                 return;
7664         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
7665         MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
7666         loadmodel->brush.entities[sb->cursize] = 0;
7667 }
7668
7669 static void Mod_VBSP_LoadVertexes(sizebuf_t *sb)
7670 {
7671         mvertex_t       *out;
7672         int                     i, count;
7673         int                     structsize = 12;
7674
7675         if (sb->cursize % structsize)
7676                 Host_Error("Mod_VBSP_LoadVertexes: funny lump size in %s",loadmodel->name);
7677         count = sb->cursize / structsize;
7678         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
7679
7680         loadmodel->brushq1.vertexes = out;
7681         loadmodel->brushq1.numvertexes = count;
7682
7683         for ( i=0 ; i<count ; i++, out++)
7684         {
7685                 out->position[0] = MSG_ReadLittleFloat(sb);
7686                 out->position[1] = MSG_ReadLittleFloat(sb);
7687                 out->position[2] = MSG_ReadLittleFloat(sb);
7688         }
7689 }
7690
7691 static void Mod_VBSP_LoadEdges(sizebuf_t *sb)
7692 {
7693         medge_t *out;
7694         int     i, count;
7695         int             structsize = 4;
7696
7697         if (sb->cursize % structsize)
7698                 Host_Error("Mod_VBSP_LoadEdges: funny lump size in %s",loadmodel->name);
7699         count = sb->cursize / structsize;
7700         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
7701
7702         loadmodel->brushq1.edges = out;
7703         loadmodel->brushq1.numedges = count;
7704
7705         for ( i=0 ; i<count ; i++, out++)
7706         {
7707                 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
7708                 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
7709                 
7710                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
7711                 {
7712                         Con_Printf("Mod_VBSP_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);
7713                         if(!loadmodel->brushq1.numvertexes)
7714                                 Host_Error("Mod_VBSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
7715                                 
7716                         out->v[0] = 0;
7717                         out->v[1] = 0;
7718                 }
7719         }
7720 }
7721
7722 static void Mod_VBSP_LoadSurfedges(sizebuf_t *sb)
7723 {
7724         int             i;
7725         int structsize = 4;
7726
7727         if (sb->cursize % structsize)
7728                 Host_Error("Mod_VBSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
7729         loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
7730         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
7731
7732         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
7733                 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
7734 }
7735
7736 static void Mod_VBSP_LoadTextures(sizebuf_t *sb)
7737 {
7738         Con_Printf(CON_WARN "Mod_VBSP_LoadTextures: Don't know how to do this yet\n");
7739 }
7740
7741 static void Mod_VBSP_LoadPlanes(sizebuf_t *sb)
7742 {
7743         int                     i;
7744         mplane_t        *out;
7745         int structsize = 20;
7746
7747         if (sb->cursize % structsize)
7748                 Host_Error("Mod_VBSP_LoadPlanes: funny lump size in %s", loadmodel->name);
7749         loadmodel->brush.num_planes = sb->cursize / structsize;
7750         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
7751
7752         for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
7753         {
7754                 out->normal[0] = MSG_ReadLittleFloat(sb);
7755                 out->normal[1] = MSG_ReadLittleFloat(sb);
7756                 out->normal[2] = MSG_ReadLittleFloat(sb);
7757                 out->dist = MSG_ReadLittleFloat(sb);
7758                 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
7759                 PlaneClassify(out);
7760         }
7761 }
7762
7763 static void Mod_VBSP_LoadTexinfo(sizebuf_t *sb)
7764 {
7765         mtexinfo_t *out;
7766         int i, j, k, count, miptex;
7767         int structsize = 72;
7768
7769         if (sb->cursize % structsize)
7770                 Host_Error("Mod_VBSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
7771         count = sb->cursize / structsize;
7772         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
7773
7774         loadmodel->brushq1.texinfo = out;
7775         loadmodel->brushq1.numtexinfo = count;
7776
7777         for (i = 0;i < count;i++, out++)
7778         {
7779                 for (k = 0;k < 2;k++)
7780                         for (j = 0;j < 4;j++)
7781                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
7782
7783                 for (k = 0;k < 2;k++)
7784                         for (j = 0;j < 4;j++)
7785                                 MSG_ReadLittleFloat(sb); // TODO lightmapVecs
7786
7787                 out->q1flags = MSG_ReadLittleLong(sb);
7788                 miptex = MSG_ReadLittleLong(sb);
7789
7790                 if (out->q1flags & TEX_SPECIAL)
7791                 {
7792                         // if texture chosen is NULL or the shader needs a lightmap,
7793                         // force to notexture water shader
7794                         out->textureindex = loadmodel->num_textures - 1;
7795                 }
7796                 else
7797                 {
7798                         // if texture chosen is NULL, force to notexture
7799                         out->textureindex = loadmodel->num_textures - 2;
7800                 }
7801                 // see if the specified miptex is valid and try to use it instead
7802                 if (loadmodel->data_textures)
7803                 {
7804                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
7805                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
7806                         else
7807                                 out->textureindex = miptex;
7808                 }
7809         }
7810 }
7811
7812 static void Mod_VBSP_LoadFaces(sizebuf_t *sb)
7813 {
7814         msurface_t *surface;
7815         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
7816         float texmins[2], texmaxs[2], val;
7817         rtexture_t *lightmaptexture, *deluxemaptexture;
7818         char vabuf[1024];
7819         int structsize =  56;
7820
7821         if (sb->cursize % structsize)
7822                 Host_Error("Mod_VBSP_LoadFaces: funny lump size in %s",loadmodel->name);
7823         count = sb->cursize / structsize;
7824         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
7825         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
7826
7827         loadmodel->num_surfaces = count;
7828
7829         loadmodel->brushq1.firstrender = true;
7830         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
7831
7832         totalverts = 0;
7833         totaltris = 0;
7834         for (surfacenum = 0;surfacenum < count;surfacenum++)
7835         {
7836                 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
7837                 totalverts += numedges;
7838                 totaltris += numedges - 2;
7839         }
7840
7841         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
7842
7843         lightmaptexture = NULL;
7844         deluxemaptexture = r_texture_blanknormalmap;
7845         lightmapnumber = 0;
7846         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
7847         totallightmapsamples = 0;
7848
7849         totalverts = 0;
7850         totaltris = 0;
7851         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
7852         {
7853                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
7854                 planenum = (unsigned short)MSG_ReadLittleShort(sb);
7855                 /*side = */MSG_ReadLittleShort(sb); // TODO support onNode?
7856                 firstedge = MSG_ReadLittleLong(sb);
7857                 numedges = (unsigned short)MSG_ReadLittleShort(sb);
7858                 texinfoindex = (unsigned short)MSG_ReadLittleShort(sb);
7859                 MSG_ReadLittleLong(sb); // skipping over dispinfo and surfaceFogVolumeID, both short
7860                 for (i = 0;i < MAXLIGHTMAPS;i++)
7861                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
7862                 lightmapoffset = MSG_ReadLittleLong(sb);
7863
7864                 // FIXME: validate edges, texinfo, etc?
7865                 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)
7866                         Host_Error("Mod_VBSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
7867                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
7868                         Host_Error("Mod_VBSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
7869                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
7870                         Host_Error("Mod_VBSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
7871
7872                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
7873                 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
7874
7875                 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
7876                 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
7877                         lightmapoffset = -1;
7878
7879                 //surface->flags = surface->texture->flags;
7880                 //if (LittleShort(in->side))
7881                 //      surface->flags |= SURF_PLANEBACK;
7882                 //surface->plane = loadmodel->brush.data_planes + planenum;
7883
7884                 surface->num_firstvertex = totalverts;
7885                 surface->num_vertices = numedges;
7886                 surface->num_firsttriangle = totaltris;
7887                 surface->num_triangles = numedges - 2;
7888                 totalverts += numedges;
7889                 totaltris += numedges - 2;
7890
7891                 // convert edges back to a normal polygon
7892                 for (i = 0;i < surface->num_vertices;i++)
7893                 {
7894                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
7895                         float s, t;
7896                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
7897                         if (lindex >= 0)
7898                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
7899                         else
7900                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
7901                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
7902                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
7903                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
7904                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
7905                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
7906                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
7907                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
7908                 }
7909
7910                 for (i = 0;i < surface->num_triangles;i++)
7911                 {
7912                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
7913                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
7914                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
7915                 }
7916
7917                 // compile additional data about the surface geometry
7918                 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);
7919                 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);
7920                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
7921
7922                 // generate surface extents information
7923                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
7924                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
7925                 for (i = 1;i < surface->num_vertices;i++)
7926                 {
7927                         for (j = 0;j < 2;j++)
7928                         {
7929                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
7930                                 texmins[j] = min(texmins[j], val);
7931                                 texmaxs[j] = max(texmaxs[j], val);
7932                         }
7933                 }
7934                 for (i = 0;i < 2;i++)
7935                 {
7936                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
7937                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
7938                 }
7939
7940                 smax = surface->lightmapinfo->extents[0] >> 4;
7941                 tmax = surface->lightmapinfo->extents[1] >> 4;
7942                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
7943                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
7944
7945                 // lighting info
7946                 surface->lightmaptexture = NULL;
7947                 surface->deluxemaptexture = r_texture_blanknormalmap;
7948                 if (lightmapoffset == -1)
7949                 {
7950                         surface->lightmapinfo->samples = NULL;
7951 #if 1
7952                         // give non-lightmapped water a 1x white lightmap
7953                         if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
7954                         {
7955                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
7956                                 surface->lightmapinfo->styles[0] = 0;
7957                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
7958                         }
7959 #endif
7960                 }
7961                 else
7962                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
7963
7964                 // check if we should apply a lightmap to this
7965                 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
7966                 {
7967                         if (ssize > 256 || tsize > 256)
7968                                 Host_Error("Bad surface extents");
7969
7970                         if (lightmapsize < ssize)
7971                                 lightmapsize = ssize;
7972                         if (lightmapsize < tsize)
7973                                 lightmapsize = tsize;
7974
7975                         totallightmapsamples += ssize*tsize;
7976
7977                         // force lightmap upload on first time seeing the surface
7978                         //
7979                         // additionally this is used by the later code to see if a
7980                         // lightmap is needed on this surface (rather than duplicating the
7981                         // logic above)
7982                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
7983                         loadmodel->lit = true;
7984                 }
7985         }
7986
7987         // small maps (such as ammo boxes especially) don't need big lightmap
7988         // textures, so this code tries to guess a good size based on
7989         // totallightmapsamples (size of the lightmaps lump basically), as well as
7990         // trying to max out the size if there is a lot of lightmap data to store
7991         // additionally, never choose a lightmapsize that is smaller than the
7992         // largest surface encountered (as it would fail)
7993         i = lightmapsize;
7994         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
7995                 ;
7996
7997         // now that we've decided the lightmap texture size, we can do the rest
7998         if (cls.state != ca_dedicated)
7999         {
8000                 int stainmapsize = 0;
8001                 mod_alloclightmap_state_t allocState;
8002
8003                 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
8004                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
8005                 {
8006                         int iu, iv, lightmapx = 0, lightmapy = 0;
8007                         float u, v, ubase, vbase, uscale, vscale;
8008
8009                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
8010                                 continue;
8011
8012                         smax = surface->lightmapinfo->extents[0] >> 4;
8013                         tmax = surface->lightmapinfo->extents[1] >> 4;
8014                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
8015                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
8016                         stainmapsize += ssize * tsize * 3;
8017
8018                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
8019                         {
8020                                 // allocate a texture pool if we need it
8021                                 if (loadmodel->texturepool == NULL)
8022                                         loadmodel->texturepool = R_AllocTexturePool();
8023                                 // could not find room, make a new lightmap
8024                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
8025                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
8026                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
8027                                 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);
8028                                 if (loadmodel->brushq1.nmaplightdata)
8029                                         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);
8030                                 lightmapnumber++;
8031                                 Mod_AllocLightmap_Reset(&allocState);
8032                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
8033                         }
8034                         surface->lightmaptexture = lightmaptexture;
8035                         surface->deluxemaptexture = deluxemaptexture;
8036                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
8037                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
8038
8039                         uscale = 1.0f / (float)lightmapsize;
8040                         vscale = 1.0f / (float)lightmapsize;
8041                         ubase = lightmapx * uscale;
8042                         vbase = lightmapy * vscale;
8043
8044                         for (i = 0;i < surface->num_vertices;i++)
8045                         {
8046                                 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);
8047                                 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);
8048                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
8049                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
8050                                 // LadyHavoc: calc lightmap data offset for vertex lighting to use
8051                                 iu = (int) u;
8052                                 iv = (int) v;
8053                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
8054                         }
8055                 }
8056
8057                 if (cl_stainmaps.integer)
8058                 {
8059                         // allocate stainmaps for permanent marks on walls and clear white
8060                         unsigned char *stainsamples = NULL;
8061                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
8062                         memset(stainsamples, 255, stainmapsize);
8063                         // assign pointers
8064                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
8065                         {
8066                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
8067                                         continue;
8068                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
8069                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
8070                                 surface->lightmapinfo->stainsamples = stainsamples;
8071                                 stainsamples += ssize * tsize * 3;
8072                         }
8073                 }
8074         }
8075
8076         // generate ushort elements array if possible
8077         if (loadmodel->surfmesh.data_element3s)
8078                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8079                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8080 }
8081
8082 // Valve BSP loader
8083 // Cloudwalk: Wasn't sober when I wrote this. I screamed and ran away at the face loader
8084 void Mod_VBSP_Load(model_t *mod, void *buffer, void *bufferend)
8085 {
8086         static cvar_t *testing = NULL; // TEMPORARY
8087         int i;
8088         sizebuf_t sb;
8089         sizebuf_t lumpsb[HL2HEADER_LUMPS];
8090
8091         if(!testing || !testing->integer)
8092         {
8093                 if(!testing)
8094                         testing = Cvar_Get(&cvars_all, "mod_bsp_vbsptest", "0", CF_CLIENT | CF_SERVER, "uhhh");
8095                 Host_Error("Mod_VBSP_Load: not yet fully implemented. Change the now-generated \"mod_bsp_vbsptest\" to 1 if you wish to test this");
8096         }
8097         else
8098         {
8099
8100                 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
8101
8102                 mod->type = mod_brushhl2;
8103
8104                 MSG_ReadLittleLong(&sb);
8105                 MSG_ReadLittleLong(&sb); // TODO version check
8106
8107                 mod->modeldatatypestring = "VBSP";
8108
8109                 // read lumps
8110                 for (i = 0; i < HL2HEADER_LUMPS; i++)
8111                 {
8112                         int offset = MSG_ReadLittleLong(&sb);
8113                         int size = MSG_ReadLittleLong(&sb);
8114                         MSG_ReadLittleLong(&sb); // TODO support version
8115                         MSG_ReadLittleLong(&sb); // TODO support ident
8116                         if (offset < 0 || offset + size > sb.cursize)
8117                                 Host_Error("Mod_VBSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
8118                         MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
8119                 }
8120
8121                 MSG_ReadLittleLong(&sb); // TODO support revision field
8122
8123                 mod->soundfromcenter = true;
8124                 mod->TraceBox = Mod_CollisionBIH_TraceBox;
8125                 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
8126                 mod->TraceLine = Mod_CollisionBIH_TraceLine;
8127                 mod->TracePoint = Mod_CollisionBIH_TracePoint;
8128                 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
8129                 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8130                 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight; // probably not correct
8131                 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents; // probably not correct
8132                 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents; // probably not correct
8133                 mod->brush.GetPVS = Mod_BSP_GetPVS;
8134                 mod->brush.FatPVS = Mod_BSP_FatPVS;
8135                 mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
8136                 mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
8137                 mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
8138                 mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
8139                 mod->brush.LightPoint = Mod_Q3BSP_LightPoint; // probably not correct
8140                 mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
8141                 mod->brush.AmbientSoundLevelsForPoint = NULL;
8142                 mod->brush.RoundUpToHullSize = NULL;
8143                 mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
8144                 mod->Draw = R_Mod_Draw;
8145                 mod->DrawDepth = R_Mod_DrawDepth;
8146                 mod->DrawDebug = R_Mod_DrawDebug;
8147                 mod->DrawPrepass = R_Mod_DrawPrepass;
8148                 mod->GetLightInfo = R_Mod_GetLightInfo;
8149                 mod->CompileShadowMap = R_Mod_CompileShadowMap;
8150                 mod->DrawShadowMap = R_Mod_DrawShadowMap;
8151                 mod->DrawLight = R_Mod_DrawLight;
8152
8153                 // allocate a texture pool if we need it
8154                 if (mod->texturepool == NULL)
8155                         mod->texturepool = R_AllocTexturePool();
8156
8157                 Mod_VBSP_LoadEntities(&lumpsb[HL2LUMP_ENTITIES]);
8158                 Mod_VBSP_LoadVertexes(&lumpsb[HL2LUMP_VERTEXES]);
8159                 Mod_VBSP_LoadEdges(&lumpsb[HL2LUMP_EDGES]);
8160                 Mod_VBSP_LoadSurfedges(&lumpsb[HL2LUMP_SURFEDGES]);
8161                 Mod_VBSP_LoadTextures(&lumpsb[HL2LUMP_TEXDATA/*?*/]);
8162                 //Mod_VBSP_LoadLighting(&lumpsb[HL2LUMP_LIGHTING]);
8163                 Mod_VBSP_LoadPlanes(&lumpsb[HL2LUMP_PLANES]);
8164                 Mod_VBSP_LoadTexinfo(&lumpsb[HL2LUMP_TEXINFO]);
8165
8166                 // AHHHHHHH
8167                 Mod_VBSP_LoadFaces(&lumpsb[HL2LUMP_FACES]);
8168         }
8169 }
8170
8171 void Mod_MAP_Load(model_t *mod, void *buffer, void *bufferend)
8172 {
8173         Host_Error("Mod_MAP_Load: not yet implemented");
8174 }
8175
8176 typedef struct objvertex_s
8177 {
8178         int nextindex;
8179         int submodelindex;
8180         int textureindex;
8181         float v[3];
8182         float vt[2];
8183         float vn[3];
8184 }
8185 objvertex_t;
8186
8187 static unsigned char nobsp_pvs[1] = {1};
8188
8189 void Mod_OBJ_Load(model_t *mod, void *buffer, void *bufferend)
8190 {
8191         const char *textbase = (char *)buffer, *text = textbase;
8192         char *s;
8193         char *argv[512];
8194         char line[1024];
8195         char materialname[MAX_QPATH];
8196         int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8197         int index1, index2, index3;
8198         objvertex_t vfirst, vprev, vcurrent;
8199         int argc;
8200         int linelen;
8201         int numtriangles = 0;
8202         int maxtriangles = 0;
8203         objvertex_t *vertices = NULL;
8204         int linenumber = 0;
8205         int maxtextures = 0, numtextures = 0, textureindex = 0;
8206         int maxv = 0, numv = 1;
8207         int maxvt = 0, numvt = 1;
8208         int maxvn = 0, numvn = 1;
8209         char *texturenames = NULL;
8210         float dist, modelradius, modelyawradius, yawradius;
8211         float *obj_v = NULL;
8212         float *obj_vt = NULL;
8213         float *obj_vn = NULL;
8214         float mins[3];
8215         float maxs[3];
8216         float corner[3];
8217         objvertex_t *thisvertex = NULL;
8218         int vertexhashindex;
8219         int *vertexhashtable = NULL;
8220         objvertex_t *vertexhashdata = NULL;
8221         objvertex_t *vdata = NULL;
8222         int vertexhashsize = 0;
8223         int vertexhashcount = 0;
8224         skinfile_t *skinfiles = NULL;
8225         unsigned char *data = NULL;
8226         int *submodelfirstsurface;
8227         msurface_t *tempsurface;
8228         msurface_t *tempsurfaces;
8229
8230         memset(&vfirst, 0, sizeof(vfirst));
8231         memset(&vprev, 0, sizeof(vprev));
8232         memset(&vcurrent, 0, sizeof(vcurrent));
8233
8234         dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8235
8236         loadmodel->modeldatatypestring = "OBJ";
8237
8238         loadmodel->type = mod_obj;
8239         loadmodel->soundfromcenter = true;
8240         loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8241         loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8242         loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8243         loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8244         loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8245         loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8246         loadmodel->brush.TraceLineOfSight = NULL;
8247         loadmodel->brush.SuperContentsFromNativeContents = NULL;
8248         loadmodel->brush.NativeContentsFromSuperContents = NULL;
8249         loadmodel->brush.GetPVS = NULL;
8250         loadmodel->brush.FatPVS = NULL;
8251         loadmodel->brush.BoxTouchingPVS = NULL;
8252         loadmodel->brush.BoxTouchingLeafPVS = NULL;
8253         loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8254         loadmodel->brush.FindBoxClusters = NULL;
8255         loadmodel->brush.LightPoint = NULL;
8256         loadmodel->brush.FindNonSolidLocation = NULL;
8257         loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8258         loadmodel->brush.RoundUpToHullSize = NULL;
8259         loadmodel->brush.PointInLeaf = NULL;
8260         loadmodel->Draw = R_Mod_Draw;
8261         loadmodel->DrawDepth = R_Mod_DrawDepth;
8262         loadmodel->DrawDebug = R_Mod_DrawDebug;
8263         loadmodel->DrawPrepass = R_Mod_DrawPrepass;
8264         loadmodel->GetLightInfo = R_Mod_GetLightInfo;
8265         loadmodel->CompileShadowMap = R_Mod_CompileShadowMap;
8266         loadmodel->DrawShadowMap = R_Mod_DrawShadowMap;
8267         loadmodel->DrawLight = R_Mod_DrawLight;
8268
8269         skinfiles = Mod_LoadSkinFiles();
8270         if (loadmodel->numskins < 1)
8271                 loadmodel->numskins = 1;
8272
8273         // make skinscenes for the skins (no groups)
8274         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8275         for (i = 0;i < loadmodel->numskins;i++)
8276         {
8277                 loadmodel->skinscenes[i].firstframe = i;
8278                 loadmodel->skinscenes[i].framecount = 1;
8279                 loadmodel->skinscenes[i].loop = true;
8280                 loadmodel->skinscenes[i].framerate = 10;
8281         }
8282
8283         VectorClear(mins);
8284         VectorClear(maxs);
8285
8286         // we always have model 0, i.e. the first "submodel"
8287         loadmodel->brush.numsubmodels = 1;
8288
8289         // parse the OBJ text now
8290         for(;;)
8291         {
8292                 static char emptyarg[1] = "";
8293                 if (!*text)
8294                         break;
8295                 linenumber++;
8296                 linelen = 0;
8297                 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8298                         line[linelen] = text[linelen];
8299                 line[linelen] = 0;
8300                 for (argc = 0;argc < 4;argc++)
8301                         argv[argc] = emptyarg;
8302                 argc = 0;
8303                 s = line;
8304                 while (*s == ' ' || *s == '\t')
8305                         s++;
8306                 while (*s)
8307                 {
8308                         argv[argc++] = s;
8309                         while (*s > ' ')
8310                                 s++;
8311                         if (!*s)
8312                                 break;
8313                         *s++ = 0;
8314                         while (*s == ' ' || *s == '\t')
8315                                 s++;
8316                 }
8317                 text += linelen;
8318                 if (*text == '\r')
8319                         text++;
8320                 if (*text == '\n')
8321                         text++;
8322                 if (!argc)
8323                         continue;
8324                 if (argv[0][0] == '#')
8325                         continue;
8326                 if (!strcmp(argv[0], "v"))
8327                 {
8328                         if (maxv <= numv)
8329                         {
8330                                 maxv = max(maxv * 2, 1024);
8331                                 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8332                         }
8333                         if(mod_obj_orientation.integer)
8334                         {
8335                                 obj_v[numv*3+0] = atof(argv[1]);
8336                                 obj_v[numv*3+2] = atof(argv[2]);
8337                                 obj_v[numv*3+1] = atof(argv[3]);
8338                         }
8339                         else
8340                         {
8341                                 obj_v[numv*3+0] = atof(argv[1]);
8342                                 obj_v[numv*3+1] = atof(argv[2]);
8343                                 obj_v[numv*3+2] = atof(argv[3]);
8344                         }
8345                         numv++;
8346                 }
8347                 else if (!strcmp(argv[0], "vt"))
8348                 {
8349                         if (maxvt <= numvt)
8350                         {
8351                                 maxvt = max(maxvt * 2, 1024);
8352                                 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8353                         }
8354                         obj_vt[numvt*2+0] = atof(argv[1]);
8355                         obj_vt[numvt*2+1] = 1-atof(argv[2]);
8356                         numvt++;
8357                 }
8358                 else if (!strcmp(argv[0], "vn"))
8359                 {
8360                         if (maxvn <= numvn)
8361                         {
8362                                 maxvn = max(maxvn * 2, 1024);
8363                                 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8364                         }
8365                         if(mod_obj_orientation.integer)
8366                         {
8367                                 obj_vn[numvn*3+0] = atof(argv[1]);
8368                                 obj_vn[numvn*3+2] = atof(argv[2]);
8369                                 obj_vn[numvn*3+1] = atof(argv[3]);
8370                         }
8371                         else
8372                         {
8373                                 obj_vn[numvn*3+0] = atof(argv[1]);
8374                                 obj_vn[numvn*3+1] = atof(argv[2]);
8375                                 obj_vn[numvn*3+2] = atof(argv[3]);
8376                         }
8377                         numvn++;
8378                 }
8379                 else if (!strcmp(argv[0], "f"))
8380                 {
8381                         if (!numtextures)
8382                         {
8383                                 if (maxtextures <= numtextures)
8384                                 {
8385                                         maxtextures = max(maxtextures * 2, 256);
8386                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8387                                 }
8388                                 textureindex = numtextures++;
8389                                 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8390                         }
8391                         for (j = 1;j < argc;j++)
8392                         {
8393                                 index1 = atoi(argv[j]);
8394                                 while(argv[j][0] && argv[j][0] != '/')
8395                                         argv[j]++;
8396                                 if (argv[j][0])
8397                                         argv[j]++;
8398                                 index2 = atoi(argv[j]);
8399                                 while(argv[j][0] && argv[j][0] != '/')
8400                                         argv[j]++;
8401                                 if (argv[j][0])
8402                                         argv[j]++;
8403                                 index3 = atoi(argv[j]);
8404                                 // negative refers to a recent vertex
8405                                 // zero means not specified
8406                                 // positive means an absolute vertex index
8407                                 if (index1 < 0)
8408                                         index1 = numv - index1;
8409                                 if (index2 < 0)
8410                                         index2 = numvt - index2;
8411                                 if (index3 < 0)
8412                                         index3 = numvn - index3;
8413                                 vcurrent.nextindex = -1;
8414                                 vcurrent.textureindex = textureindex;
8415                                 vcurrent.submodelindex = submodelindex;
8416                                 if (obj_v && index1 >= 0 && index1 < numv)
8417                                         VectorCopy(obj_v + 3*index1, vcurrent.v);
8418                                 if (obj_vt && index2 >= 0 && index2 < numvt)
8419                                         Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8420                                 if (obj_vn && index3 >= 0 && index3 < numvn)
8421                                         VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8422                                 if (numtriangles == 0)
8423                                 {
8424                                         VectorCopy(vcurrent.v, mins);
8425                                         VectorCopy(vcurrent.v, maxs);
8426                                 }
8427                                 else
8428                                 {
8429                                         mins[0] = min(mins[0], vcurrent.v[0]);
8430                                         mins[1] = min(mins[1], vcurrent.v[1]);
8431                                         mins[2] = min(mins[2], vcurrent.v[2]);
8432                                         maxs[0] = max(maxs[0], vcurrent.v[0]);
8433                                         maxs[1] = max(maxs[1], vcurrent.v[1]);
8434                                         maxs[2] = max(maxs[2], vcurrent.v[2]);
8435                                 }
8436                                 if (j == 1)
8437                                         vfirst = vcurrent;
8438                                 else if (j >= 3)
8439                                 {
8440                                         if (maxtriangles <= numtriangles)
8441                                         {
8442                                                 maxtriangles = max(maxtriangles * 2, 32768);
8443                                                 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8444                                         }
8445                                         if(mod_obj_orientation.integer)
8446                                         {
8447                                                 vertices[numtriangles*3+0] = vfirst;
8448                                                 vertices[numtriangles*3+1] = vprev;
8449                                                 vertices[numtriangles*3+2] = vcurrent;
8450                                         }
8451                                         else
8452                                         {
8453                                                 vertices[numtriangles*3+0] = vfirst;
8454                                                 vertices[numtriangles*3+2] = vprev;
8455                                                 vertices[numtriangles*3+1] = vcurrent;
8456                                         }
8457                                         numtriangles++;
8458                                 }
8459                                 vprev = vcurrent;
8460                         }
8461                 }
8462                 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8463                 {
8464                         submodelindex = atof(argv[1]);
8465                         loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8466                 }
8467                 else if (!strcmp(argv[0], "usemtl"))
8468                 {
8469                         for (i = 0;i < numtextures;i++)
8470                                 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8471                                         break;
8472                         if (i < numtextures)
8473                                 textureindex = i;
8474                         else
8475                         {
8476                                 if (maxtextures <= numtextures)
8477                                 {
8478                                         maxtextures = max(maxtextures * 2, 256);
8479                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8480                                 }
8481                                 textureindex = numtextures++;
8482                                 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8483                         }
8484                 }
8485         }
8486
8487         // now that we have the OBJ data loaded as-is, we can convert it
8488
8489         // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8490         VectorCopy(mins, loadmodel->normalmins);
8491         VectorCopy(maxs, loadmodel->normalmaxs);
8492         dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8493         modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8494         modelyawradius = dist*dist+modelyawradius*modelyawradius;
8495         modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8496         modelradius = modelyawradius + modelradius * modelradius;
8497         modelyawradius = sqrt(modelyawradius);
8498         modelradius = sqrt(modelradius);
8499         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8500         loadmodel->yawmins[2] = loadmodel->normalmins[2];
8501         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] =  modelyawradius;
8502         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8503         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8504         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] =  modelradius;
8505         loadmodel->radius = modelradius;
8506         loadmodel->radius2 = modelradius * modelradius;
8507
8508         // allocate storage for triangles
8509         loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8510         // allocate vertex hash structures to build an optimal vertex subset
8511         vertexhashsize = numtriangles*2;
8512         vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8513         memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8514         vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8515         vertexhashcount = 0;
8516
8517         // gather surface stats for assigning vertex/triangle ranges
8518         firstvertex = 0;
8519         firsttriangle = 0;
8520         elementindex = 0;
8521         loadmodel->num_surfaces = 0;
8522         // allocate storage for the worst case number of surfaces, later we resize
8523         tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8524         submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8525         tempsurface = tempsurfaces;
8526         for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8527         {
8528                 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8529                 for (textureindex = 0;textureindex < numtextures;textureindex++)
8530                 {
8531                         for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8532                         {
8533                                 thisvertex = vertices + vertexindex;
8534                                 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8535                                         break;
8536                         }
8537                         // skip the surface creation if there are no triangles for it
8538                         if (vertexindex == numtriangles*3)
8539                                 continue;
8540                         // create a surface for these vertices
8541                         surfacevertices = 0;
8542                         surfaceelements = 0;
8543                         // we hack in a texture index in the surface to be fixed up later...
8544                         tempsurface->texture = (texture_t *)((size_t)textureindex);
8545                         // calculate bounds as we go
8546                         VectorCopy(thisvertex->v, tempsurface->mins);
8547                         VectorCopy(thisvertex->v, tempsurface->maxs);
8548                         for (;vertexindex < numtriangles*3;vertexindex++)
8549                         {
8550                                 thisvertex = vertices + vertexindex;
8551                                 if (thisvertex->submodelindex != submodelindex)
8552                                         continue;
8553                                 if (thisvertex->textureindex != textureindex)
8554                                         continue;
8555                                 // add vertex to surface bounds
8556                                 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8557                                 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8558                                 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8559                                 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8560                                 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8561                                 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8562                                 // add the vertex if it is not found in the merged set, and
8563                                 // get its index (triangle element) for the surface
8564                                 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8565                                 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8566                                 {
8567                                         vdata = vertexhashdata + i;
8568                                         if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8569                                                 break;
8570                                 }
8571                                 if (i < 0)
8572                                 {
8573                                         i = vertexhashcount++;
8574                                         vdata = vertexhashdata + i;
8575                                         *vdata = *thisvertex;
8576                                         vdata->nextindex = vertexhashtable[vertexhashindex];
8577                                         vertexhashtable[vertexhashindex] = i;
8578                                         surfacevertices++;
8579                                 }
8580                                 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8581                                 surfaceelements++;
8582                         }
8583                         surfacetriangles = surfaceelements / 3;
8584                         tempsurface->num_vertices = surfacevertices;
8585                         tempsurface->num_triangles = surfacetriangles;
8586                         tempsurface->num_firstvertex = firstvertex;
8587                         tempsurface->num_firsttriangle = firsttriangle;
8588                         firstvertex += tempsurface->num_vertices;
8589                         firsttriangle += tempsurface->num_triangles;
8590                         tempsurface++;
8591                         loadmodel->num_surfaces++;
8592                 }
8593         }
8594         submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8595         numvertices = firstvertex;
8596         loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8597         tempsurfaces = NULL;
8598
8599         // allocate storage for final mesh data
8600         loadmodel->num_textures = numtextures * loadmodel->numskins;
8601         loadmodel->num_texturesperskin = numtextures;
8602         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(model_t *));
8603         loadmodel->brush.submodels = (model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(model_t *);
8604         loadmodel->modelsurfaces_sorted = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8605         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8606         loadmodel->surfmesh.num_vertices = numvertices;
8607         loadmodel->surfmesh.num_triangles = numtriangles;
8608         loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8609         loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8610         loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8611         loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8612         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8613
8614         if (loadmodel->surfmesh.num_vertices <= 65536) {
8615                 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8616         }
8617
8618         for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8619         {
8620                 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8621                 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8622                 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8623         }
8624
8625         // load the textures
8626         for (textureindex = 0;textureindex < numtextures;textureindex++)
8627                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8628         Mod_FreeSkinFiles(skinfiles);
8629
8630         // set the surface textures to their real values now that we loaded them...
8631         for (i = 0;i < loadmodel->num_surfaces;i++)
8632                 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8633
8634         // free data
8635         Mem_Free(vertices);
8636         Mem_Free(texturenames);
8637         Mem_Free(obj_v);
8638         Mem_Free(obj_vt);
8639         Mem_Free(obj_vn);
8640         Mem_Free(vertexhashtable);
8641         Mem_Free(vertexhashdata);
8642
8643         // compute all the mesh information that was not loaded from the file
8644         if (loadmodel->surfmesh.data_element3s)
8645                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8646                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8647         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8648         // generate normals if the file did not have them
8649         if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8650                 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
8651         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
8652
8653         // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8654         loadmodel->brush.num_visleafs = 1;
8655         loadmodel->brush.num_leafs = 1;
8656         loadmodel->brush.num_nodes = 0;
8657         loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8658         loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8659         loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8660         loadmodel->brush.num_pvsclusters = 1;
8661         loadmodel->brush.num_pvsclusterbytes = 1;
8662         loadmodel->brush.data_pvsclusters = nobsp_pvs;
8663         //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8664         //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8665         loadmodel->brush.data_leafsurfaces = loadmodel->modelsurfaces_sorted;
8666         VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8667         VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8668         loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8669         loadmodel->brush.data_leafs->clusterindex = 0;
8670         loadmodel->brush.data_leafs->areaindex = 0;
8671         loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8672         loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8673         loadmodel->brush.data_leafs->numleafbrushes = 0;
8674         loadmodel->brush.data_leafs->firstleafbrush = NULL;
8675         loadmodel->brush.supportwateralpha = true;
8676
8677         if (loadmodel->brush.numsubmodels)
8678                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
8679
8680         mod = loadmodel;
8681         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8682         {
8683                 if (i > 0)
8684                 {
8685                         char name[10];
8686                         // duplicate the basic information
8687                         dpsnprintf(name, sizeof(name), "*%i", i);
8688                         mod = Mod_FindName(name, loadmodel->name);
8689                         // copy the base model to this one
8690                         *mod = *loadmodel;
8691                         // rename the clone back to its proper name
8692                         strlcpy(mod->name, name, sizeof(mod->name));
8693                         mod->brush.parentmodel = loadmodel;
8694                         // textures and memory belong to the main model
8695                         mod->texturepool = NULL;
8696                         mod->mempool = NULL;
8697                         mod->brush.GetPVS = NULL;
8698                         mod->brush.FatPVS = NULL;
8699                         mod->brush.BoxTouchingPVS = NULL;
8700                         mod->brush.BoxTouchingLeafPVS = NULL;
8701                         mod->brush.BoxTouchingVisibleLeafs = NULL;
8702                         mod->brush.FindBoxClusters = NULL;
8703                         mod->brush.LightPoint = NULL;
8704                         mod->brush.AmbientSoundLevelsForPoint = NULL;
8705                 }
8706                 mod->brush.submodel = i;
8707                 if (loadmodel->brush.submodels)
8708                         loadmodel->brush.submodels[i] = mod;
8709
8710                 // make the model surface list (used by shadowing/lighting)
8711                 mod->submodelsurfaces_start = submodelfirstsurface[i];
8712                 mod->submodelsurfaces_end = submodelfirstsurface[i+1];
8713                 mod->firstmodelbrush = 0;
8714                 mod->nummodelbrushes = 0;
8715
8716                 VectorClear(mod->normalmins);
8717                 VectorClear(mod->normalmaxs);
8718                 l = false;
8719                 for (j = mod->submodelsurfaces_start;j < mod->submodelsurfaces_end;j++)
8720                 {
8721                         const msurface_t *surface = mod->data_surfaces + j;
8722                         const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8723                         int k;
8724                         if (!surface->num_vertices)
8725                                 continue;
8726                         if (!l)
8727                         {
8728                                 l = true;
8729                                 VectorCopy(v3f, mod->normalmins);
8730                                 VectorCopy(v3f, mod->normalmaxs);
8731                         }
8732                         for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8733                         {
8734                                 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8735                                 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8736                                 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8737                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8738                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8739                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8740                         }
8741                 }
8742                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8743                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8744                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8745                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8746                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8747                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8748                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8749                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8750                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8751                 mod->yawmins[2] = mod->normalmins[2];
8752                 mod->yawmaxs[2] = mod->normalmaxs[2];
8753                 mod->radius = modelradius;
8754                 mod->radius2 = modelradius * modelradius;
8755
8756                 Mod_SetDrawSkyAndWater(mod);
8757
8758                 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8759                 mod->render_bih = mod->collision_bih;
8760
8761                 // generate VBOs and other shared data before cloning submodels
8762                 if (i == 0)
8763                         Mod_BuildVBOs();
8764         }
8765         mod = loadmodel;
8766         Mem_Free(submodelfirstsurface);
8767
8768         // make the model surface list (used by shadowing/lighting)
8769         Mod_MakeSortedSurfaces(loadmodel);
8770
8771         Con_DPrintf("Stats for obj model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
8772 }