2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
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)"};
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"};
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"};
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_traceoutofsolid = {CF_SHARED, "mod_q1bsp_traceoutofsolid", "1", "enables tracebox to move an entity that's stuck in solid brushwork out to empty space, 1 matches FTEQW and QSS and is required by many community maps (items/monsters will be missing otherwise), 0 matches old versions of DP and the original Quake engine (if your map or QC needs 0 it's buggy)"};
65 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"};
67 cvar_t mod_bsp_portalize = {CF_CLIENT, "mod_bsp_portalize", "0", "enables portal generation from BSP tree (takes a minute or more and GBs of memory when loading a complex map), used by r_drawportals, r_useportalculling, r_shadow_realtime_dlight_portalculling, r_shadow_realtime_world_compileportalculling"};
68 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"};
70 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)"};
72 static texture_t mod_q1bsp_texture_solid;
73 static texture_t mod_q1bsp_texture_sky;
74 static texture_t mod_q1bsp_texture_lava;
75 static texture_t mod_q1bsp_texture_slime;
76 static texture_t mod_q1bsp_texture_water;
78 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);
80 void Mod_BrushInit(void)
82 // Cvar_RegisterVariable(&r_subdivide_size);
83 Cvar_RegisterVariable(&mod_bsp_portalize);
84 Cvar_RegisterVariable(&r_novis);
85 Cvar_RegisterVariable(&r_nosurftextures);
86 Cvar_RegisterVariable(&r_subdivisions_tolerance);
87 Cvar_RegisterVariable(&r_subdivisions_mintess);
88 Cvar_RegisterVariable(&r_subdivisions_maxtess);
89 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
90 Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_tolerance);
91 Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_mintess);
92 Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_maxtess);
93 Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_maxvertices);
94 Cvar_RegisterVariable(&r_trippy);
95 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
96 Cvar_RegisterVariable(&mod_obj_orientation);
97 Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
98 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
99 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
100 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
101 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
102 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
103 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_texture);
104 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_world_surfaces);
105 Cvar_RegisterVariable(&mod_q3bsp_lightgrid_bsp_surfaces);
106 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
107 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
108 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
109 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
110 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
111 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
112 Cvar_RegisterVariable(&mod_q3shader_default_refractive_index);
113 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
114 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
115 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
116 Cvar_RegisterVariable(&mod_q1bsp_traceoutofsolid);
117 Cvar_RegisterVariable(&mod_q1bsp_zero_hullsize_cutoff);
118 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
120 // these games were made for older DP engines and are no longer
121 // maintained; use this hack to show their textures properly
122 if(gamemode == GAME_NEXUIZ)
123 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
125 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
126 dp_strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
127 mod_q1bsp_texture_solid.surfaceflags = 0;
128 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
130 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
131 dp_strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
132 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
133 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
135 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
136 dp_strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
137 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
138 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
140 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
141 dp_strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
142 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
143 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
145 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
146 dp_strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
147 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
148 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
151 static mleaf_t *Mod_BSP_PointInLeaf(model_t *model, const vec3_t p)
158 // LadyHavoc: modified to start at first clip node,
159 // in other words: first node of the (sub)model
160 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
162 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
164 return (mleaf_t *)node;
167 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(model_t *model, const vec3_t p, unsigned char *out, int outsize)
171 leaf = Mod_BSP_PointInLeaf(model, p);
174 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
177 memcpy(out, leaf->ambient_sound_level, i);
183 memset(out, 0, outsize);
186 static int Mod_BSP_FindBoxClusters(model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
189 int nodestackindex = 0;
190 mnode_t *node, *nodestack[1024];
191 if (!model->brush.num_pvsclusters)
193 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
199 // node - recurse down the BSP tree
200 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
204 return -1; // ERROR: NAN bounding box!
205 // box is on one side of plane, take that path
206 node = node->children[sides-1];
210 // box crosses plane, take one path and remember the other
211 if (nodestackindex < 1024)
212 nodestack[nodestackindex++] = node->children[0];
213 node = node->children[1];
219 // leaf - add clusterindex to list
220 if (numclusters < maxclusters)
221 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
225 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
229 if (nodestackindex < 1024)
230 nodestack[nodestackindex++] = node->children[0];
231 node = node->children[1];
236 // leaf - add clusterindex to list
237 if (numclusters < maxclusters)
238 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
243 // try another path we didn't take earlier
244 if (nodestackindex == 0)
246 node = nodestack[--nodestackindex];
248 // return number of clusters found (even if more than the maxclusters)
252 static int Mod_BSP_BoxTouchingPVS(model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
254 int nodestackindex = 0;
255 mnode_t *node, *nodestack[1024];
256 if (!model->brush.num_pvsclusters)
258 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
264 // node - recurse down the BSP tree
265 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
269 return -1; // ERROR: NAN bounding box!
270 // box is on one side of plane, take that path
271 node = node->children[sides-1];
275 // box crosses plane, take one path and remember the other
276 if (nodestackindex < 1024)
277 nodestack[nodestackindex++] = node->children[0];
278 node = node->children[1];
284 // leaf - check cluster bit
285 int clusterindex = ((mleaf_t *)node)->clusterindex;
286 if (CHECKPVSBIT(pvs, clusterindex))
288 // it is visible, return immediately with the news
293 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
297 if (nodestackindex < 1024)
298 nodestack[nodestackindex++] = node->children[0];
299 node = node->children[1];
304 // leaf - check cluster bit
305 int clusterindex = ((mleaf_t *)node)->clusterindex;
306 if (CHECKPVSBIT(pvs, clusterindex))
308 // it is visible, return immediately with the news
314 // nothing to see here, try another path we didn't take earlier
315 if (nodestackindex == 0)
317 node = nodestack[--nodestackindex];
323 static int Mod_BSP_BoxTouchingLeafPVS(model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
325 int nodestackindex = 0;
326 mnode_t *node, *nodestack[1024];
327 if (!model->brush.num_leafs)
329 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
335 // node - recurse down the BSP tree
336 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
340 return -1; // ERROR: NAN bounding box!
341 // box is on one side of plane, take that path
342 node = node->children[sides-1];
346 // box crosses plane, take one path and remember the other
347 if (nodestackindex < 1024)
348 nodestack[nodestackindex++] = node->children[0];
349 node = node->children[1];
355 // leaf - check cluster bit
356 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
357 if (CHECKPVSBIT(pvs, clusterindex))
359 // it is visible, return immediately with the news
364 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
368 if (nodestackindex < 1024)
369 nodestack[nodestackindex++] = node->children[0];
370 node = node->children[1];
375 // leaf - check cluster bit
376 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
377 if (CHECKPVSBIT(pvs, clusterindex))
379 // it is visible, return immediately with the news
385 // nothing to see here, try another path we didn't take earlier
386 if (nodestackindex == 0)
388 node = nodestack[--nodestackindex];
394 static int Mod_BSP_BoxTouchingVisibleLeafs(model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
396 int nodestackindex = 0;
397 mnode_t *node, *nodestack[1024];
398 if (!model->brush.num_leafs)
400 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
406 // node - recurse down the BSP tree
407 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
411 return -1; // ERROR: NAN bounding box!
412 // box is on one side of plane, take that path
413 node = node->children[sides-1];
417 // box crosses plane, take one path and remember the other
418 if (nodestackindex < 1024)
419 nodestack[nodestackindex++] = node->children[0];
420 node = node->children[1];
426 // leaf - check if it is visible
427 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
429 // it is visible, return immediately with the news
434 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
438 if (nodestackindex < 1024)
439 nodestack[nodestackindex++] = node->children[0];
440 node = node->children[1];
445 // leaf - check if it is visible
446 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
448 // it is visible, return immediately with the news
454 // nothing to see here, try another path we didn't take earlier
455 if (nodestackindex == 0)
457 node = nodestack[--nodestackindex];
463 typedef struct findnonsolidlocationinfo_s
466 vec3_t absmin, absmax;
472 findnonsolidlocationinfo_t;
474 static void Mod_BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
477 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
479 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
480 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
481 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
482 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
483 VectorSubtract(vert[1], vert[0], edge[0]);
484 VectorSubtract(vert[2], vert[1], edge[1]);
485 CrossProduct(edge[1], edge[0], facenormal);
486 if (facenormal[0] || facenormal[1] || facenormal[2])
488 VectorNormalize(facenormal);
489 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
490 if (f <= info->bestdist && f >= -info->bestdist)
492 VectorSubtract(vert[0], vert[2], edge[2]);
493 VectorNormalize(edge[0]);
494 VectorNormalize(edge[1]);
495 VectorNormalize(edge[2]);
496 CrossProduct(facenormal, edge[0], edgenormal[0]);
497 CrossProduct(facenormal, edge[1], edgenormal[1]);
498 CrossProduct(facenormal, edge[2], edgenormal[2]);
500 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
501 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
502 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
504 // we got lucky, the center is within the face
505 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
509 if (info->bestdist > dist)
511 info->bestdist = dist;
512 VectorScale(facenormal, (info->radius - -dist), info->nudge);
517 if (info->bestdist > dist)
519 info->bestdist = dist;
520 VectorScale(facenormal, (info->radius - dist), info->nudge);
526 // check which edge or vertex the center is nearest
527 for (i = 0;i < 3;i++)
529 f = DotProduct(info->center, edge[i]);
530 if (f >= DotProduct(vert[0], edge[i])
531 && f <= DotProduct(vert[1], edge[i]))
534 VectorMA(info->center, -f, edge[i], point);
535 dist = sqrt(DotProduct(point, point));
536 if (info->bestdist > dist)
538 info->bestdist = dist;
539 VectorScale(point, (info->radius / dist), info->nudge);
541 // skip both vertex checks
542 // (both are further away than this edge)
547 // not on edge, check first vertex of edge
548 VectorSubtract(info->center, vert[i], point);
549 dist = sqrt(DotProduct(point, point));
550 if (info->bestdist > dist)
552 info->bestdist = dist;
553 VectorScale(point, (info->radius / dist), info->nudge);
562 static void Mod_BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
564 int surfacenum, k, *mark;
566 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
568 surface = info->model->data_surfaces + *mark;
569 if(!surface->texture)
571 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
573 for (k = 0;k < surface->num_triangles;k++)
575 Mod_BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
581 static void Mod_BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
585 float f = PlaneDiff(info->center, node->plane);
586 if (f >= -info->bestdist)
587 Mod_BSP_FindNonSolidLocation_r(info, node->children[0]);
588 if (f <= info->bestdist)
589 Mod_BSP_FindNonSolidLocation_r(info, node->children[1]);
593 if (((mleaf_t *)node)->numleafsurfaces)
594 Mod_BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
598 static void Mod_BSP_FindNonSolidLocation(model_t *model, const vec3_t in, vec3_t out, float radius)
601 findnonsolidlocationinfo_t info;
607 VectorCopy(in, info.center);
608 info.radius = radius;
613 VectorClear(info.nudge);
614 info.bestdist = radius;
615 VectorCopy(info.center, info.absmin);
616 VectorCopy(info.center, info.absmax);
617 info.absmin[0] -= info.radius + 1;
618 info.absmin[1] -= info.radius + 1;
619 info.absmin[2] -= info.radius + 1;
620 info.absmax[0] += info.radius + 1;
621 info.absmax[1] += info.radius + 1;
622 info.absmax[2] += info.radius + 1;
623 Mod_BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
624 VectorAdd(info.center, info.nudge, info.center);
626 while (info.bestdist < radius && ++i < 10);
627 VectorCopy(info.center, out);
630 int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
632 switch(nativecontents)
637 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
639 return SUPERCONTENTS_WATER;
641 return SUPERCONTENTS_SLIME;
643 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
645 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
650 int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
652 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
653 return CONTENTS_SOLID;
654 if (supercontents & SUPERCONTENTS_SKY)
656 if (supercontents & SUPERCONTENTS_LAVA)
657 return CONTENTS_LAVA;
658 if (supercontents & SUPERCONTENTS_SLIME)
659 return CONTENTS_SLIME;
660 if (supercontents & SUPERCONTENTS_WATER)
661 return CONTENTS_WATER;
662 return CONTENTS_EMPTY;
665 typedef struct RecursiveHullCheckTraceInfo_s
667 // the hull we're tracing through
670 // the trace structure to fill in
673 // start, end, and end - start (in model space)
678 RecursiveHullCheckTraceInfo_t;
680 // 1/32 epsilon to keep floating point happy
681 #define DIST_EPSILON (0.03125)
683 #define HULLCHECKSTATE_EMPTY 0
684 #define HULLCHECKSTATE_SOLID 1
685 #define HULLCHECKSTATE_DONE 2
687 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
689 // status variables, these don't need to be saved on the stack when
690 // recursing... but are because this should be thread-safe
691 // (note: tracing against a bbox is not thread-safe, yet)
696 // variables that need to be stored on the stack when recursing
701 // keep looping until we hit a leaf
704 // find the point distances
705 node = t->hull->clipnodes + num;
706 plane = t->hull->planes + node->planenum;
708 // axial planes can be calculated more quickly without the DotProduct
711 t1 = p1[plane->type] - plane->dist;
712 t2 = p2[plane->type] - plane->dist;
716 t1 = DotProduct (plane->normal, p1) - plane->dist;
717 t2 = DotProduct (plane->normal, p2) - plane->dist;
720 // negative plane distances indicate children[1] (behind plane)
724 // if the line starts and ends on the same side of the plane, recurse
725 // into that child instantly
726 if (p1side == p2side)
728 #if COLLISIONPARANOID >= 3
734 // loop back and process the start child
735 num = node->children[p1side];
739 // find the midpoint where the line crosses the plane, use the
740 // original line for best accuracy
741 #if COLLISIONPARANOID >= 3
746 t1 = t->start[plane->type] - plane->dist;
747 t2 = t->end[plane->type] - plane->dist;
751 t1 = DotProduct (plane->normal, t->start) - plane->dist;
752 t2 = DotProduct (plane->normal, t->end) - plane->dist;
754 midf = t1 / (t1 - t2);
755 midf = bound(p1f, midf, p2f);
756 VectorMA(t->start, midf, t->dist, mid);
758 // we now have a mid point, essentially splitting the line into
759 // the segments in the near child and the far child, we can now
760 // recurse those in order and get their results
762 // recurse both sides, front side first
763 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
764 // if this side is not empty, return what it is (solid or done)
765 if (ret != HULLCHECKSTATE_EMPTY && (!t->trace->allsolid || !mod_q1bsp_traceoutofsolid.integer))
768 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
769 // if other side is not solid, return what it is (empty or done)
770 if (ret != HULLCHECKSTATE_SOLID)
773 // front is air and back is solid, this is the impact point...
775 // copy the plane information, flipping it if needed
778 t->trace->plane.dist = -plane->dist;
779 VectorNegate (plane->normal, t->trace->plane.normal);
783 t->trace->plane.dist = plane->dist;
784 VectorCopy (plane->normal, t->trace->plane.normal);
787 // calculate the return fraction which is nudged off the surface a bit
788 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
789 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
790 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
791 t->trace->fraction = bound(0, midf, 1);
793 #if COLLISIONPARANOID >= 3
796 return HULLCHECKSTATE_DONE;
800 // we reached a leaf contents
803 num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
804 if (!t->trace->startfound)
806 t->trace->startfound = true;
807 t->trace->startsupercontents |= num;
809 if (num & SUPERCONTENTS_LIQUIDSMASK)
810 t->trace->inwater = true;
812 t->trace->inopen = true;
813 if (num & SUPERCONTENTS_SOLID)
814 t->trace->hittexture = &mod_q1bsp_texture_solid;
815 else if (num & SUPERCONTENTS_SKY)
816 t->trace->hittexture = &mod_q1bsp_texture_sky;
817 else if (num & SUPERCONTENTS_LAVA)
818 t->trace->hittexture = &mod_q1bsp_texture_lava;
819 else if (num & SUPERCONTENTS_SLIME)
820 t->trace->hittexture = &mod_q1bsp_texture_slime;
822 t->trace->hittexture = &mod_q1bsp_texture_water;
823 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
824 t->trace->hitsupercontents = num;
825 if (num & t->trace->hitsupercontentsmask)
827 // if the first leaf is solid, set startsolid
828 if (t->trace->allsolid)
829 t->trace->startsolid = true;
830 #if COLLISIONPARANOID >= 3
833 return HULLCHECKSTATE_SOLID;
837 t->trace->allsolid = false;
838 #if COLLISIONPARANOID >= 3
841 return HULLCHECKSTATE_EMPTY;
845 //#if COLLISIONPARANOID < 2
846 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
849 mclipnode_t *nodes = t->hull->clipnodes;
850 mplane_t *planes = t->hull->planes;
852 VectorCopy(t->start, point);
855 plane = planes + nodes[num].planenum;
856 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
858 num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
859 t->trace->startsupercontents |= num;
860 if (num & SUPERCONTENTS_LIQUIDSMASK)
861 t->trace->inwater = true;
863 t->trace->inopen = true;
864 if (num & t->trace->hitsupercontentsmask)
866 t->trace->allsolid = t->trace->startsolid = true;
867 return HULLCHECKSTATE_SOLID;
871 t->trace->allsolid = t->trace->startsolid = false;
872 return HULLCHECKSTATE_EMPTY;
877 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)
879 RecursiveHullCheckTraceInfo_t rhc;
881 memset(&rhc, 0, sizeof(rhc));
882 memset(trace, 0, sizeof(trace_t));
884 rhc.trace->fraction = 1;
885 rhc.trace->allsolid = true;
886 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
887 VectorCopy(start, rhc.start);
888 VectorCopy(start, rhc.end);
889 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
892 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);
894 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)
896 RecursiveHullCheckTraceInfo_t rhc;
898 if (VectorCompare(start, end))
900 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
904 // 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...
905 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
907 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
911 memset(&rhc, 0, sizeof(rhc));
912 memset(trace, 0, sizeof(trace_t));
914 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
915 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
916 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
917 rhc.trace->fraction = 1;
918 rhc.trace->allsolid = true;
919 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
920 VectorCopy(start, rhc.start);
921 VectorCopy(end, rhc.end);
922 VectorSubtract(rhc.end, rhc.start, rhc.dist);
923 #if COLLISIONPARANOID >= 2
924 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]);
925 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
930 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
931 memset(&testtrace, 0, sizeof(trace_t));
932 rhc.trace = &testtrace;
933 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
934 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
935 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
936 rhc.trace->fraction = 1;
937 rhc.trace->allsolid = true;
938 VectorCopy(test, rhc.start);
939 VectorCopy(test, rhc.end);
940 VectorClear(rhc.dist);
941 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
942 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
943 if (!trace->startsolid && testtrace.startsolid)
944 Con_Printf(" - ended in solid!\n");
948 if (VectorLength2(rhc.dist))
949 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
951 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
955 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)
957 // this function currently only supports same size start and end
959 RecursiveHullCheckTraceInfo_t rhc;
961 if (VectorCompare(boxmins, boxmaxs))
963 if (VectorCompare(start, end))
964 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
966 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
970 memset(&rhc, 0, sizeof(rhc));
971 memset(trace, 0, sizeof(trace_t));
973 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
974 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
975 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
976 rhc.trace->fraction = 1;
977 rhc.trace->allsolid = true;
978 VectorSubtract(boxmaxs, boxmins, boxsize);
979 if (boxsize[0] < mod_q1bsp_zero_hullsize_cutoff.value)
980 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
981 else if (model->brush.ishlbsp)
983 // LadyHavoc: this has to have a minor tolerance (the .1) because of
984 // minor float precision errors from the box being transformed around
985 if (boxsize[0] < 32.1)
987 if (boxsize[2] < 54) // pick the nearest of 36 or 72
988 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
990 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
993 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
997 // LadyHavoc: this has to have a minor tolerance (the .1) because of
998 // minor float precision errors from the box being transformed around
999 if (boxsize[0] < 32.1)
1000 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1002 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1004 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1005 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1006 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1007 #if COLLISIONPARANOID >= 2
1008 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]);
1009 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1014 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1015 memset(&testtrace, 0, sizeof(trace_t));
1016 rhc.trace = &testtrace;
1017 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1018 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1019 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1020 rhc.trace->fraction = 1;
1021 rhc.trace->allsolid = true;
1022 VectorCopy(test, rhc.start);
1023 VectorCopy(test, rhc.end);
1024 VectorClear(rhc.dist);
1025 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1026 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1027 if (!trace->startsolid && testtrace.startsolid)
1028 Con_Printf(" - ended in solid!\n");
1032 if (VectorLength2(rhc.dist))
1033 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1035 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1039 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1041 int num = model->brushq1.hulls[0].firstclipnode;
1043 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1044 mplane_t *planes = model->brushq1.hulls[0].planes;
1047 plane = planes + nodes[num].planenum;
1048 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1050 return Mod_Q1BSP_SuperContentsFromNativeContents(num);
1053 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)
1057 colplanef_t cbox_planes[6];
1059 cbox.hasaabbplanes = true;
1060 cbox.supercontents = boxsupercontents;
1063 cbox.numtriangles = 0;
1064 cbox.planes = cbox_planes;
1066 cbox.elements = NULL;
1074 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];
1075 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];
1076 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];
1077 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];
1078 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];
1079 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];
1080 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1081 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1082 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1083 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1084 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1085 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1086 memset(trace, 0, sizeof(trace_t));
1087 trace->hitsupercontentsmask = hitsupercontentsmask;
1088 trace->skipsupercontentsmask = skipsupercontentsmask;
1089 trace->skipmaterialflagsmask = skipmaterialflagsmask;
1090 trace->fraction = 1;
1091 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1093 RecursiveHullCheckTraceInfo_t rhc;
1094 static hull_t box_hull;
1095 static mclipnode_t box_clipnodes[6];
1096 static mplane_t box_planes[6];
1097 // fill in a default trace
1098 memset(&rhc, 0, sizeof(rhc));
1099 memset(trace, 0, sizeof(trace_t));
1100 //To keep everything totally uniform, bounding boxes are turned into small
1101 //BSP trees instead of being compared directly.
1102 // create a temp hull from bounding box sizes
1103 box_planes[0].dist = cmaxs[0] - mins[0];
1104 box_planes[1].dist = cmins[0] - maxs[0];
1105 box_planes[2].dist = cmaxs[1] - mins[1];
1106 box_planes[3].dist = cmins[1] - maxs[1];
1107 box_planes[4].dist = cmaxs[2] - mins[2];
1108 box_planes[5].dist = cmins[2] - maxs[2];
1109 #if COLLISIONPARANOID >= 3
1110 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]);
1113 if (box_hull.clipnodes == NULL)
1117 //Set up the planes and clipnodes so that the six floats of a bounding box
1118 //can just be stored out and get a proper hull_t structure.
1120 box_hull.clipnodes = box_clipnodes;
1121 box_hull.planes = box_planes;
1122 box_hull.firstclipnode = 0;
1123 box_hull.lastclipnode = 5;
1125 for (i = 0;i < 6;i++)
1127 box_clipnodes[i].planenum = i;
1131 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1133 box_clipnodes[i].children[side^1] = i + 1;
1135 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1137 box_planes[i].type = i>>1;
1138 box_planes[i].normal[i>>1] = 1;
1142 // trace a line through the generated clipping hull
1143 //rhc.boxsupercontents = boxsupercontents;
1144 rhc.hull = &box_hull;
1146 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1147 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1148 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1149 rhc.trace->fraction = 1;
1150 rhc.trace->allsolid = true;
1151 VectorCopy(start, rhc.start);
1152 VectorCopy(end, rhc.end);
1153 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1154 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1155 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1156 if (rhc.trace->startsupercontents)
1157 rhc.trace->startsupercontents = boxsupercontents;
1161 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)
1163 memset(trace, 0, sizeof(trace_t));
1164 trace->fraction = 1;
1165 trace->hitsupercontentsmask = hitsupercontentsmask;
1166 trace->skipsupercontentsmask = skipsupercontentsmask;
1167 trace->skipmaterialflagsmask = skipmaterialflagsmask;
1168 if (BoxesOverlap(start, start, cmins, cmaxs))
1170 trace->startsupercontents |= boxsupercontents;
1171 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1173 trace->startsolid = true;
1174 trace->allsolid = true;
1179 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)
1182 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
1183 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
1186 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)
1190 float mid, distz = endz - startz;
1194 switch (node->plane->type)
1197 node = node->children[x < node->plane->dist];
1198 continue; // loop back and process the new node
1200 node = node->children[y < node->plane->dist];
1201 continue; // loop back and process the new node
1203 side = startz < node->plane->dist;
1204 if ((endz < node->plane->dist) == side)
1206 node = node->children[side];
1207 continue; // loop back and process the new node
1209 // found an intersection
1210 mid = node->plane->dist;
1213 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1214 front += startz * node->plane->normal[2];
1215 back += endz * node->plane->normal[2];
1216 side = front < node->plane->dist;
1217 if ((back < node->plane->dist) == side)
1219 node = node->children[side];
1220 continue; // loop back and process the new node
1222 // found an intersection
1223 mid = startz + distz * (front - node->plane->dist) / (front - back);
1227 // go down front side
1228 if (node->children[side]->plane && Mod_BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1229 return true; // hit something
1231 // check for impact on this node
1232 if (node->numsurfaces)
1235 int dsi, dti, lmwidth, lmheight;
1237 msurface_t *surface;
1238 unsigned char *lightmap;
1239 int maps, line3, size3;
1242 float scale, w, w00, w01, w10, w11;
1244 surface = model->data_surfaces + node->firstsurface;
1245 for (i = 0;i < node->numsurfaces;i++, surface++)
1247 if(!surface->texture)
1249 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1250 continue; // no lightmaps
1252 // location we want to sample in the lightmap
1253 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;
1254 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;
1257 // thanks to jitspoe for pointing out that this int cast was
1258 // rounding toward zero, so we floor it
1259 dsi = (int)floor(ds);
1260 dti = (int)floor(dt);
1261 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1262 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1265 // we have to tolerate a position of lmwidth-1 for some rare
1266 // cases - in which case the sampling position still gets
1267 // clamped but the color gets interpolated to that edge.
1268 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1270 // in the rare cases where we're sampling slightly off
1271 // the polygon, clamp the sampling position (we can still
1272 // interpolate outside it, where it becomes extrapolation)
1277 if (dsi > lmwidth-2)
1279 if (dti > lmheight-2)
1282 // calculate bilinear interpolation factors
1283 // and also multiply by fixedpoint conversion factors to
1284 // compensate for lightmaps being 0-255 (as 0-2), we use
1285 // r_refdef.scene.rtlightstylevalue here which is already
1286 // 0.000-2.148 range
1287 // (if we used r_refdef.scene.lightstylevalue this
1288 // divisor would be 32768 rather than 128)
1291 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1292 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1293 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1294 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1296 // values for pointer math
1297 line3 = lmwidth * 3; // LadyHavoc: *3 for colored lighting
1298 size3 = lmwidth * lmheight * 3; // LadyHavoc: *3 for colored lighting
1300 // look up the pixel
1301 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LadyHavoc: *3 for colored lighting
1303 // bilinear filter each lightmap style, and sum them
1304 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1306 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1307 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1308 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1309 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1310 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1314 return true; // success
1319 // go down back side
1320 node = node->children[side ^ 1];
1322 distz = endz - startz;
1323 // loop back and process the new node
1326 // did not hit anything
1330 static void Mod_BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1332 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1333 VectorSet(diffusenormal, 0, 0, 1);
1335 if (!model->brushq1.lightdata)
1337 VectorSet(ambientcolor, 1, 1, 1);
1338 VectorSet(diffusecolor, 0, 0, 0);
1342 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);
1345 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const model_t *model, const mnode_t *node, double mid[3])
1350 const msurface_t *surface;
1355 float edgenormal[3];
1362 surface = model->data_surfaces + node->firstsurface;
1363 for (i = 0;i < node->numsurfaces;i++, surface++)
1365 if(!surface->texture)
1367 // skip surfaces whose bounding box does not include the point
1368 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1370 // skip faces with contents we don't care about
1371 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1373 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1374 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1376 // skip surfaces matching the skipmaterialflagsmask (e.g. MATERIALFLAG_NOSHADOW)
1377 if (t->trace->skipmaterialflagsmask & surface->texture->currentmaterialflags)
1379 // get the surface normal - since it is flat we know any vertex normal will suffice
1380 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1382 if (DotProduct(t->dist, normal) > 0)
1384 // iterate edges and see if the point is outside one of them
1385 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1387 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1388 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1389 VectorSubtract(v0, v1, edgedir);
1390 CrossProduct(edgedir, normal, edgenormal);
1391 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1394 // if the point is outside one of the edges, it is not within the surface
1395 if (j < surface->num_vertices)
1398 // we hit a surface, this is the impact point...
1399 VectorCopy(normal, t->trace->plane.normal);
1400 t->trace->plane.dist = DotProduct(normal, p);
1402 // calculate the return fraction which is nudged off the surface a bit
1403 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1404 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1405 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1406 t->trace->fraction = bound(0, midf, 1);
1408 t->trace->hittexture = surface->texture->currentframe;
1409 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1410 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1411 return surface->texture->currentframe;
1416 static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
1418 const mplane_t *plane;
1421 double midf, mid[3];
1422 const mleaf_t *leaf;
1426 plane = node->plane;
1427 if (plane->type < 3)
1429 t1 = p1[plane->type] - plane->dist;
1430 t2 = p2[plane->type] - plane->dist;
1434 t1 = DotProduct (plane->normal, p1) - plane->dist;
1435 t2 = DotProduct (plane->normal, p2) - plane->dist;
1441 node = node->children[1];
1450 node = node->children[0];
1456 // the line intersects, find intersection point
1457 // LadyHavoc: this uses the original trace for maximum accuracy
1458 if (plane->type < 3)
1460 t1 = t->start[plane->type] - plane->dist;
1461 t2 = t->end[plane->type] - plane->dist;
1465 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1466 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1469 midf = t1 / (t1 - t2);
1470 VectorMA(t->start, midf, t->dist, mid);
1472 // recurse both sides, front side first, return if we hit a surface
1473 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1474 return HULLCHECKSTATE_DONE;
1476 // test each surface on the node
1477 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1478 if (t->trace->hittexture)
1479 return HULLCHECKSTATE_DONE;
1481 // recurse back side
1482 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1484 leaf = (const mleaf_t *)node;
1485 side = Mod_Q1BSP_SuperContentsFromNativeContents(leaf->contents);
1486 if (!t->trace->startfound)
1488 t->trace->startfound = true;
1489 t->trace->startsupercontents |= side;
1491 if (side & SUPERCONTENTS_LIQUIDSMASK)
1492 t->trace->inwater = true;
1494 t->trace->inopen = true;
1495 if (side & t->trace->hitsupercontentsmask)
1497 // if the first leaf is solid, set startsolid
1498 if (t->trace->allsolid)
1499 t->trace->startsolid = true;
1500 return HULLCHECKSTATE_SOLID;
1504 t->trace->allsolid = false;
1505 return HULLCHECKSTATE_EMPTY;
1509 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)
1511 RecursiveHullCheckTraceInfo_t rhc;
1513 memset(&rhc, 0, sizeof(rhc));
1514 memset(trace, 0, sizeof(trace_t));
1516 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1517 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1518 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1519 rhc.trace->fraction = 1;
1520 rhc.trace->allsolid = true;
1521 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1522 VectorCopy(start, rhc.start);
1523 VectorCopy(end, rhc.end);
1524 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1525 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1526 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1529 static void Mod_BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1532 unsigned char *outstart = out;
1533 while (out < outend)
1537 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));
1547 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));
1550 for (c = *in++;c > 0;c--)
1554 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));
1565 Mod_Q1BSP_LoadSplitSky
1567 A sky texture is 256*128, with the right side being a masked overlay
1570 static void Mod_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1575 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1576 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1578 // allocate a texture pool if we need it
1579 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1580 loadmodel->texturepool = R_AllocTexturePool();
1582 if (bytesperpixel == 4)
1584 for (y = 0;y < h;y++)
1586 for (x = 0;x < w;x++)
1588 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1589 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1595 // make an average value for the back to avoid
1596 // a fringe on the top level
1605 for (y = 0;y < h;y++)
1607 for (x = 0;x < w;x++)
1609 p = src[x*width+y+w];
1610 r += palette_rgb[p][0];
1611 g += palette_rgb[p][1];
1612 b += palette_rgb[p][2];
1615 bgra.b[2] = r/(w*h);
1616 bgra.b[1] = g/(w*h);
1617 bgra.b[0] = b/(w*h);
1619 for (y = 0;y < h;y++)
1621 for (x = 0;x < w;x++)
1623 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1625 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1630 // Load the solid and alpha parts of the sky texture as separate textures
1631 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA(
1634 (unsigned char *) solidpixels,
1636 CRC_Block((unsigned char *) solidpixels, w*h*4),
1638 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA(
1641 (unsigned char *) alphapixels,
1643 CRC_Block((unsigned char *) alphapixels, w*h*4),
1645 Mem_Free(solidpixels);
1646 Mem_Free(alphapixels);
1649 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1651 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0, firstskynoshadowtexture = 0;
1652 skinframe_t *skinframemissing;
1653 texture_t *tx, *tx2, *anims[10], *altanims[10], *currentskynoshadowtexture;
1654 texture_t backuptex;
1655 unsigned char *data, *mtdata;
1657 char mapname[MAX_QPATH], name[MAX_QPATH];
1658 unsigned char zeroopaque[4], zerotrans[4];
1661 Vector4Set(zeroopaque, 0, 0, 0, 255);
1662 Vector4Set(zerotrans, 0, 0, 0, 128);
1664 loadmodel->data_textures = NULL;
1666 // add two slots for notexture walls and notexture liquids, and duplicate
1667 // all sky textures; sky surfaces can be shadow-casting or not, the surface
1668 // loading will choose according to the contents behind the surface
1669 // (necessary to support e1m5 logo shadow which has a SKY contents brush,
1670 // while correctly treating sky textures as occluders in other situations).
1675 nummiptex = MSG_ReadLittleLong(sb);
1676 loadmodel->num_textures = nummiptex + 2;
1677 // save the position so we can go back to it
1678 watermark = sb->readcount;
1679 for (i = 0; i < nummiptex; i++)
1681 doffset = MSG_ReadLittleLong(sb);
1682 if (r_nosurftextures.integer)
1686 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1690 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1692 // copy name, but only up to 16 characters
1693 // (the output buffer can hold more than this, but the input buffer is
1695 for (j = 0; j < 16; j++)
1696 name[j] = MSG_ReadByte(&miptexsb);
1698 // pretty up the buffer (replacing any trailing garbage with 0)
1699 for (j = (int)strlen(name); j < 16; j++)
1701 // bones_was_here: force all names to lowercase (matching code below) so we don't crash on e2m9
1702 for (j = 0;name[j];j++)
1703 if (name[j] >= 'A' && name[j] <= 'Z')
1704 name[j] += 'a' - 'A';
1706 if (!strncmp(name, "sky", 3))
1710 // bump it back to where we started parsing
1711 sb->readcount = (int)watermark;
1713 firstskynoshadowtexture = loadmodel->num_textures;
1714 loadmodel->num_textures += numsky;
1718 loadmodel->num_textures = 2;
1719 firstskynoshadowtexture = loadmodel->num_textures;
1721 loadmodel->num_texturesperskin = loadmodel->num_textures;
1723 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1725 // we'll be writing to these in parallel for sky textures
1726 currentskynoshadowtexture = loadmodel->data_textures + firstskynoshadowtexture;
1728 // fill out all slots with notexture
1729 skinframemissing = R_SkinFrame_LoadMissing();
1730 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1732 dp_strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1735 tx->basealpha = 1.0f;
1736 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(loadmodel->mempool, skinframemissing);
1737 tx->materialshaderpass->skinframes[0] = skinframemissing;
1738 tx->currentskinframe = skinframemissing;
1739 tx->basematerialflags = MATERIALFLAG_WALL;
1740 if (i == loadmodel->num_textures - 1)
1742 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1743 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1744 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1748 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1749 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1751 tx->currentframe = tx;
1753 // clear water settings
1756 tx->refractive_index = mod_q3shader_default_refractive_index.value;
1757 tx->refractfactor = 1;
1758 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1759 tx->reflectfactor = 1;
1760 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1761 tx->r_water_wateralpha = 1;
1762 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1763 tx->offsetscale = 1;
1765 tx->specularscalemod = 1;
1766 tx->specularpowermod = 1;
1767 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1768 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1769 // JUST GREP FOR "specularscalemod = 1".
1774 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1778 s = loadmodel->name;
1779 if (!strncasecmp(s, "maps/", 5))
1781 FS_StripExtension(s, mapname, sizeof(mapname));
1783 // LadyHavoc: mostly rewritten map texture loader
1784 for (i = 0;i < nummiptex;i++)
1786 doffset = MSG_ReadLittleLong(sb);
1787 if (r_nosurftextures.integer)
1791 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1795 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1797 // copy name, but only up to 16 characters
1798 // (the output buffer can hold more than this, but the input buffer is
1800 for (j = 0;j < 16;j++)
1801 name[j] = MSG_ReadByte(&miptexsb);
1803 // pretty up the buffer (replacing any trailing garbage with 0)
1804 for (j = (int)strlen(name);j < 16;j++)
1809 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1810 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1813 mtwidth = MSG_ReadLittleLong(&miptexsb);
1814 mtheight = MSG_ReadLittleLong(&miptexsb);
1816 j = MSG_ReadLittleLong(&miptexsb);
1820 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1822 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1825 mtdata = miptexsb.data + j;
1828 if ((mtwidth & 15) || (mtheight & 15))
1829 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1831 // LadyHavoc: force all names to lowercase
1832 for (j = 0;name[j];j++)
1833 if (name[j] >= 'A' && name[j] <= 'Z')
1834 name[j] += 'a' - 'A';
1836 tx = loadmodel->data_textures + i;
1837 // 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
1838 backuptex = loadmodel->data_textures[i];
1839 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) ||
1840 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)))
1842 // set the width/height fields which are used for parsing texcoords in this bsp format
1843 tx->width = mtwidth;
1844 tx->height = mtheight;
1847 // no luck with loading shaders or external textures - restore the in-progress texture loading
1848 loadmodel->data_textures[i] = backuptex;
1850 dp_strlcpy(tx->name, name, sizeof(tx->name));
1851 tx->width = mtwidth;
1852 tx->height = mtheight;
1853 tx->basealpha = 1.0f;
1855 // start out with no animation
1856 tx->currentframe = tx;
1857 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1859 if (tx->name[0] == '*')
1861 if (!strncmp(tx->name, "*lava", 5))
1863 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1864 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1866 else if (!strncmp(tx->name, "*slime", 6))
1868 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1869 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1873 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1874 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1877 else if (!strncmp(tx->name, "sky", 3))
1879 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1880 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1881 // for the surface traceline we need to hit this surface as a solid...
1882 tx->supercontents |= SUPERCONTENTS_SOLID;
1886 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1887 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1890 if (cls.state != ca_dedicated)
1892 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);
1894 !(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)))
1895 // HACK: It loads custom skybox textures as a wall if loaded as a skinframe.
1896 || !strncmp(tx->name, "sky", 3))
1898 // did not find external texture via shader loading, load it from the bsp or wad3
1899 if (loadmodel->brush.ishlbsp)
1901 // internal texture overrides wad
1902 unsigned char* pixels, * freepixels;
1903 pixels = freepixels = NULL;
1905 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1907 pixels = freepixels = W_GetTextureBGRA(tx->name);
1910 tx->width = image_width;
1911 tx->height = image_height;
1912 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);
1915 Mem_Free(freepixels);
1917 else if (!strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1919 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1921 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1922 if (data && image_width == image_height * 2)
1924 Mod_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1927 else if (mtdata != NULL)
1928 Mod_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1930 else if (mtdata) // texture included
1931 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1932 // if mtdata is NULL, the "missing" texture has already been assigned to this
1933 // LadyHavoc: some Tenebrae textures get replaced by black
1934 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1935 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, 0, 0, 0, false);
1936 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1937 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, 0, 0, 0, false);
1940 tx->materialshaderpass->skinframes[0] = skinframe;
1941 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1944 tx->basematerialflags = MATERIALFLAG_WALL;
1945 if (tx->name[0] == '*')
1947 // LadyHavoc: some turbulent textures should not be affected by wateralpha
1948 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1949 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1950 else if (!strncmp(tx->name,"*lava",5)
1951 || !strncmp(tx->name,"*teleport",9)
1952 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1953 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1955 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1956 if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1957 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1959 else if (tx->name[0] == '{') // fence textures
1961 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1963 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1965 // replace the texture with black
1966 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1968 else if (!strncmp(tx->name, "sky", 3))
1969 tx->basematerialflags = MATERIALFLAG_SKY;
1970 else if (!strcmp(tx->name, "caulk"))
1971 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1972 else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1973 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1974 tx->currentmaterialflags = tx->basematerialflags;
1976 // duplicate of sky with NOSHADOW
1977 if (tx->basematerialflags & MATERIALFLAG_SKY)
1979 *currentskynoshadowtexture = *tx;
1980 currentskynoshadowtexture->basematerialflags |= MATERIALFLAG_NOSHADOW;
1981 tx->skynoshadowtexture = currentskynoshadowtexture;
1982 currentskynoshadowtexture++;
1986 // sequence the animations
1987 for (i = 0;i < nummiptex;i++)
1989 tx = loadmodel->data_textures + i;
1990 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1993 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1995 Con_Printf("Bad animating texture %s\n", tx->name);
1998 if (tx->anim_total[0] || tx->anim_total[1])
1999 continue; // already sequenced
2001 // find the number of frames in the animation
2002 memset(anims, 0, sizeof(anims));
2003 memset(altanims, 0, sizeof(altanims));
2005 for (j = i;j < nummiptex;j++)
2007 tx2 = loadmodel->data_textures + j;
2008 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
2012 if (num >= '0' && num <= '9')
2013 anims[num - '0'] = tx2;
2014 else if (num >= 'a' && num <= 'j')
2015 altanims[num - 'a'] = tx2;
2016 // No need to warn otherwise - we already did above.
2020 for (j = 0;j < 10;j++)
2027 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
2030 for (j = 0;j < max;j++)
2034 Con_Printf("Missing frame %i of %s\n", j, tx->name);
2038 for (j = 0;j < altmax;j++)
2042 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
2049 // If we have exactly one frame, something's wrong.
2050 if (max + altmax <= 1)
2052 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
2057 // if there is no alternate animation, duplicate the primary
2058 // animation into the alternate
2060 for (k = 0;k < 10;k++)
2061 altanims[k] = anims[k];
2067 Con_Printf("Missing frame 0 of %s\n", tx->name);
2069 // however, we can handle this by duplicating the alternate animation into the primary
2071 for (k = 0;k < 10;k++)
2072 anims[k] = altanims[k];
2076 // link together the primary animation
2077 for (j = 0;j < max;j++)
2080 tx2->animated = 1; // q1bsp
2081 tx2->anim_total[0] = max;
2082 tx2->anim_total[1] = altmax;
2083 for (k = 0;k < 10;k++)
2085 tx2->anim_frames[0][k] = anims[k];
2086 tx2->anim_frames[1][k] = altanims[k];
2090 // if there really is an alternate anim...
2091 if (anims[0] != altanims[0])
2093 // link together the alternate animation
2094 for (j = 0;j < altmax;j++)
2097 tx2->animated = 1; // q1bsp
2098 // the primary/alternate are reversed here
2099 tx2->anim_total[0] = altmax;
2100 tx2->anim_total[1] = max;
2101 for (k = 0;k < 10;k++)
2103 tx2->anim_frames[0][k] = altanims[k];
2104 tx2->anim_frames[1][k] = anims[k];
2111 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2114 unsigned char *in, *out, *data, d;
2115 char litfilename[MAX_QPATH];
2116 char dlitfilename[MAX_QPATH];
2117 fs_offset_t filesize;
2118 if (loadmodel->brush.ishlbsp) // LadyHavoc: load the colored lighting data straight
2120 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2121 for (i = 0;i < sb->cursize;i++)
2122 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2124 else // LadyHavoc: bsp version 29 (normal white lighting)
2126 // LadyHavoc: hope is not lost yet, check for a .lit file to load
2127 dp_strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2128 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2129 dp_strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2130 dp_strlcat (litfilename, ".lit", sizeof (litfilename));
2131 dp_strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2132 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2135 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2137 i = LittleLong(((int *)data)[1]);
2140 if (developer_loading.integer)
2141 Con_Printf("loaded %s\n", litfilename);
2142 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2143 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2145 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2148 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2150 i = LittleLong(((int *)data)[1]);
2153 if (developer_loading.integer)
2154 Con_Printf("loaded %s\n", dlitfilename);
2155 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2156 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2157 loadmodel->brushq3.deluxemapping_modelspace = false;
2158 loadmodel->brushq3.deluxemapping = true;
2167 Con_Printf("Unknown .lit file version (%d)\n", i);
2169 else if (filesize == 8)
2170 Con_Print("Empty .lit file, ignoring\n");
2172 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2179 // LadyHavoc: oh well, expand the white lighting data
2182 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2184 out = loadmodel->brushq1.lightdata;
2185 for (i = 0;i < sb->cursize;i++)
2195 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2197 loadmodel->brushq1.num_compressedpvs = 0;
2198 loadmodel->brushq1.data_compressedpvs = NULL;
2201 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2202 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2203 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2206 // used only for HalfLife maps
2207 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2209 char key[128], value[4096];
2213 if (!COM_ParseToken_Simple(&data, false, false, true))
2215 if (com_token[0] != '{')
2219 if (!COM_ParseToken_Simple(&data, false, false, true))
2221 if (com_token[0] == '}')
2222 break; // end of worldspawn
2223 if (com_token[0] == '_')
2224 dp_strlcpy(key, com_token + 1, sizeof(key));
2226 dp_strlcpy(key, com_token, sizeof(key));
2227 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2228 key[strlen(key)-1] = 0;
2229 if (!COM_ParseToken_Simple(&data, false, false, true))
2231 dpsnprintf(value, sizeof(value), "%s", com_token);
2232 if (!strcmp("wad", key)) // for HalfLife maps
2234 if (loadmodel->brush.ishlbsp)
2237 for (i = 0;i < (int)sizeof(value);i++)
2238 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2240 if (i < (int)sizeof(value) && value[i])
2242 for (;i < (int)sizeof(value);i++)
2244 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2245 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2247 else if (value[i] == ';' || value[i] == 0)
2251 W_LoadTextureWadFile(&value[j], false);
2263 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2265 loadmodel->brush.entities = NULL;
2268 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2269 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2270 loadmodel->brush.entities[sb->cursize] = 0;
2271 if (loadmodel->brush.ishlbsp)
2272 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2276 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2280 int structsize = 12;
2282 if (sb->cursize % structsize)
2283 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2284 count = sb->cursize / structsize;
2285 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2287 loadmodel->brushq1.vertexes = out;
2288 loadmodel->brushq1.numvertexes = count;
2290 for ( i=0 ; i<count ; i++, out++)
2292 out->position[0] = MSG_ReadLittleFloat(sb);
2293 out->position[1] = MSG_ReadLittleFloat(sb);
2294 out->position[2] = MSG_ReadLittleFloat(sb);
2298 static void Mod_BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2302 int structsize = hullinfo ? (48+4*hullinfo->filehulls) : 48;
2304 if (sb->cursize % structsize)
2305 Host_Error ("Mod_BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2307 count = sb->cursize / structsize;
2308 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2310 loadmodel->brushq1.submodels = out;
2311 loadmodel->brush.numsubmodels = count;
2313 for (i = 0; i < count; i++, out++)
2315 // spread out the mins / maxs by a pixel
2316 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2317 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2318 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2319 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2320 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2321 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2322 out->origin[0] = MSG_ReadLittleFloat(sb);
2323 out->origin[1] = MSG_ReadLittleFloat(sb);
2324 out->origin[2] = MSG_ReadLittleFloat(sb);
2327 for (j = 0; j < hullinfo->filehulls; j++)
2328 out->headnode[j] = MSG_ReadLittleLong(sb);
2329 out->visleafs = MSG_ReadLittleLong(sb);
2331 else // Quake 2 has only one hull
2332 out->headnode[0] = MSG_ReadLittleLong(sb);
2334 out->firstface = MSG_ReadLittleLong(sb);
2335 out->numfaces = MSG_ReadLittleLong(sb);
2339 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2343 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2345 if (sb->cursize % structsize)
2346 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2347 count = sb->cursize / structsize;
2348 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2350 loadmodel->brushq1.edges = out;
2351 loadmodel->brushq1.numedges = count;
2353 for ( i=0 ; i<count ; i++, out++)
2355 if (loadmodel->brush.isbsp2)
2357 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2358 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2362 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2363 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2365 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2367 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);
2368 if(!loadmodel->brushq1.numvertexes)
2369 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2377 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2380 int i, j, k, count, miptex;
2381 int structsize = 40;
2383 if (sb->cursize % structsize)
2384 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2385 count = sb->cursize / structsize;
2386 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2388 loadmodel->brushq1.texinfo = out;
2389 loadmodel->brushq1.numtexinfo = count;
2391 for (i = 0;i < count;i++, out++)
2393 for (k = 0;k < 2;k++)
2394 for (j = 0;j < 4;j++)
2395 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2397 miptex = MSG_ReadLittleLong(sb);
2398 out->q1flags = MSG_ReadLittleLong(sb);
2400 if (out->q1flags & TEX_SPECIAL)
2402 // if texture chosen is NULL or the shader needs a lightmap,
2403 // force to notexture water shader
2404 out->textureindex = loadmodel->num_textures - 1;
2408 // if texture chosen is NULL, force to notexture
2409 out->textureindex = loadmodel->num_textures - 2;
2411 // see if the specified miptex is valid and try to use it instead
2412 if (loadmodel->data_textures)
2414 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2415 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2417 out->textureindex = miptex;
2423 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2428 mins[0] = mins[1] = mins[2] = 9999;
2429 maxs[0] = maxs[1] = maxs[2] = -9999;
2431 for (i = 0;i < numverts;i++)
2433 for (j = 0;j < 3;j++, v++)
2443 #define MAX_SUBDIVPOLYTRIANGLES 4096
2444 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2446 static int subdivpolyverts, subdivpolytriangles;
2447 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2448 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2450 static int subdivpolylookupvert(vec3_t v)
2453 for (i = 0;i < subdivpolyverts;i++)
2454 if (subdivpolyvert[i][0] == v[0]
2455 && subdivpolyvert[i][1] == v[1]
2456 && subdivpolyvert[i][2] == v[2])
2458 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2459 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2460 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2461 return subdivpolyverts++;
2464 static void SubdividePolygon(int numverts, float *verts)
2466 int i, i1, i2, i3, f, b, c, p;
2467 vec3_t mins, maxs, front[256], back[256];
2468 float m, *pv, *cv, dist[256], frac;
2471 Host_Error("SubdividePolygon: ran out of verts in buffer");
2473 BoundPoly(numverts, verts, mins, maxs);
2475 for (i = 0;i < 3;i++)
2477 m = (mins[i] + maxs[i]) * 0.5;
2478 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2479 if (maxs[i] - m < 8)
2481 if (m - mins[i] < 8)
2485 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2486 dist[c] = cv[i] - m;
2489 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2493 VectorCopy(pv, front[f]);
2498 VectorCopy(pv, back[b]);
2501 if (dist[p] == 0 || dist[c] == 0)
2503 if ((dist[p] > 0) != (dist[c] > 0) )
2506 frac = dist[p] / (dist[p] - dist[c]);
2507 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2508 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2509 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2515 SubdividePolygon(f, front[0]);
2516 SubdividePolygon(b, back[0]);
2520 i1 = subdivpolylookupvert(verts);
2521 i2 = subdivpolylookupvert(verts + 3);
2522 for (i = 2;i < numverts;i++)
2524 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2526 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2530 i3 = subdivpolylookupvert(verts + i * 3);
2531 subdivpolyindex[subdivpolytriangles][0] = i1;
2532 subdivpolyindex[subdivpolytriangles][1] = i2;
2533 subdivpolyindex[subdivpolytriangles][2] = i3;
2535 subdivpolytriangles++;
2539 //Breaks a polygon up along axial 64 unit
2540 //boundaries so that turbulent and sky warps
2541 //can be done reasonably.
2542 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2548 subdivpolytriangles = 0;
2549 subdivpolyverts = 0;
2550 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2551 if (subdivpolytriangles < 1)
2552 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2554 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2555 mesh->num_vertices = subdivpolyverts;
2556 mesh->num_triangles = subdivpolytriangles;
2557 mesh->vertex = (surfvertex_t *)(mesh + 1);
2558 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2559 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2561 for (i = 0;i < mesh->num_triangles;i++)
2562 for (j = 0;j < 3;j++)
2563 mesh->index[i*3+j] = subdivpolyindex[i][j];
2565 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2567 VectorCopy(subdivpolyvert[i], v->v);
2568 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2569 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2574 extern cvar_t gl_max_lightmapsize;
2575 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2577 msurface_t *surface;
2578 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2579 float texmins[2], texmaxs[2], val;
2580 rtexture_t *lightmaptexture, *deluxemaptexture;
2582 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2584 if (sb->cursize % structsize)
2585 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2586 count = sb->cursize / structsize;
2587 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2588 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2590 loadmodel->num_surfaces = count;
2592 loadmodel->brushq1.firstrender = true;
2593 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2597 for (surfacenum = 0;surfacenum < count;surfacenum++)
2599 if (loadmodel->brush.isbsp2)
2600 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2602 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2603 totalverts += numedges;
2604 totaltris += numedges - 2;
2607 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
2609 lightmaptexture = NULL;
2610 deluxemaptexture = r_texture_blanknormalmap;
2612 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2613 totallightmapsamples = 0;
2617 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2619 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2620 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2621 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2622 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2623 firstedge = MSG_ReadLittleLong(sb);
2624 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2625 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2626 for (i = 0;i < MAXLIGHTMAPS;i++)
2627 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2628 lightmapoffset = MSG_ReadLittleLong(sb);
2630 // FIXME: validate edges, texinfo, etc?
2631 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)
2632 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2633 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2634 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2635 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2636 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2638 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2639 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2641 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2642 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2643 lightmapoffset = -1;
2645 //surface->flags = surface->texture->flags;
2646 //if (LittleShort(in->side))
2647 // surface->flags |= SURF_PLANEBACK;
2648 //surface->plane = loadmodel->brush.data_planes + planenum;
2650 surface->num_firstvertex = totalverts;
2651 surface->num_vertices = numedges;
2652 surface->num_firsttriangle = totaltris;
2653 surface->num_triangles = numedges - 2;
2654 totalverts += numedges;
2655 totaltris += numedges - 2;
2657 // convert edges back to a normal polygon
2658 for (i = 0;i < surface->num_vertices;i++)
2660 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2662 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2664 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2666 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2667 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2668 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2669 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2670 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2671 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2672 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2673 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2676 for (i = 0;i < surface->num_triangles;i++)
2678 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2679 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2680 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2683 // compile additional data about the surface geometry
2684 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);
2685 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);
2686 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2688 // generate surface extents information
2689 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2690 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2691 for (i = 1;i < surface->num_vertices;i++)
2693 for (j = 0;j < 2;j++)
2695 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2696 texmins[j] = min(texmins[j], val);
2697 texmaxs[j] = max(texmaxs[j], val);
2700 for (i = 0;i < 2;i++)
2702 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2703 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2706 smax = surface->lightmapinfo->extents[0] >> 4;
2707 tmax = surface->lightmapinfo->extents[1] >> 4;
2708 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2709 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2712 surface->lightmaptexture = NULL;
2713 surface->deluxemaptexture = r_texture_blanknormalmap;
2714 if (lightmapoffset == -1)
2716 surface->lightmapinfo->samples = NULL;
2718 // give non-lightmapped water a 1x white lightmap
2719 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2721 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2722 surface->lightmapinfo->styles[0] = 0;
2723 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2727 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LadyHavoc: HalfLife map (bsp version 30)
2728 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2729 else // LadyHavoc: white lighting (bsp version 29)
2731 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2732 if (loadmodel->brushq1.nmaplightdata)
2733 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2736 // check if we should apply a lightmap to this
2737 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2739 if (ssize > 256 || tsize > 256)
2740 Host_Error("Bad surface extents");
2742 if (lightmapsize < ssize)
2743 lightmapsize = ssize;
2744 if (lightmapsize < tsize)
2745 lightmapsize = tsize;
2747 totallightmapsamples += ssize*tsize;
2749 // force lightmap upload on first time seeing the surface
2751 // additionally this is used by the later code to see if a
2752 // lightmap is needed on this surface (rather than duplicating the
2754 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2755 loadmodel->lit = true;
2759 // small maps (such as ammo boxes especially) don't need big lightmap
2760 // textures, so this code tries to guess a good size based on
2761 // totallightmapsamples (size of the lightmaps lump basically), as well as
2762 // trying to max out the size if there is a lot of lightmap data to store
2763 // additionally, never choose a lightmapsize that is smaller than the
2764 // largest surface encountered (as it would fail)
2766 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2769 // now that we've decided the lightmap texture size, we can do the rest
2770 if (cls.state != ca_dedicated)
2772 int stainmapsize = 0;
2773 mod_alloclightmap_state_t allocState;
2775 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2776 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2778 int iu, iv, lightmapx = 0, lightmapy = 0;
2779 float u, v, ubase, vbase, uscale, vscale;
2781 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2784 smax = surface->lightmapinfo->extents[0] >> 4;
2785 tmax = surface->lightmapinfo->extents[1] >> 4;
2786 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2787 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2788 stainmapsize += ssize * tsize * 3;
2790 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2792 // allocate a texture pool if we need it
2793 if (loadmodel->texturepool == NULL)
2794 loadmodel->texturepool = R_AllocTexturePool();
2795 // could not find room, make a new lightmap
2796 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2797 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2798 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2799 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);
2800 if (loadmodel->brushq1.nmaplightdata)
2801 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);
2803 Mod_AllocLightmap_Reset(&allocState);
2804 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2806 surface->lightmaptexture = lightmaptexture;
2807 surface->deluxemaptexture = deluxemaptexture;
2808 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2809 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2811 uscale = 1.0f / (float)lightmapsize;
2812 vscale = 1.0f / (float)lightmapsize;
2813 ubase = lightmapx * uscale;
2814 vbase = lightmapy * vscale;
2816 for (i = 0;i < surface->num_vertices;i++)
2818 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);
2819 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);
2820 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2821 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2822 // LadyHavoc: calc lightmap data offset for vertex lighting to use
2825 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2829 if (cl_stainmaps.integer)
2831 // allocate stainmaps for permanent marks on walls and clear white
2832 unsigned char *stainsamples = NULL;
2833 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2834 memset(stainsamples, 255, stainmapsize);
2836 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2838 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2840 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2841 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2842 surface->lightmapinfo->stainsamples = stainsamples;
2843 stainsamples += ssize * tsize * 3;
2848 // generate ushort elements array if possible
2849 if (loadmodel->surfmesh.data_element3s)
2850 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2851 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2854 static void Mod_BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2857 // Host_Error("Mod_BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2858 node->parent = parent;
2861 // this is a node, recurse to children
2862 Mod_BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2863 Mod_BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2864 // combine supercontents of children
2865 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2870 mleaf_t *leaf = (mleaf_t *)node;
2871 // if this is a leaf, calculate supercontents mask from all collidable
2872 // primitives in the leaf (brushes and collision surfaces)
2873 // also flag if the leaf contains any collision surfaces
2874 leaf->combinedsupercontents = 0;
2875 // combine the supercontents values of all brushes in this leaf
2876 for (j = 0;j < leaf->numleafbrushes;j++)
2877 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2878 // check if this leaf contains any collision surfaces (q3 patches)
2879 for (j = 0;j < leaf->numleafsurfaces;j++)
2881 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2882 if (surface->num_collisiontriangles)
2884 leaf->containscollisionsurfaces = true;
2885 leaf->combinedsupercontents |= surface->texture->supercontents;
2891 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2893 int i, j, count, p, child[2];
2895 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2897 if (sb->cursize % structsize)
2898 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2899 count = sb->cursize / structsize;
2901 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2902 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2904 loadmodel->brush.data_nodes = out;
2905 loadmodel->brush.num_nodes = count;
2907 for ( i=0 ; i<count ; i++, out++)
2909 p = MSG_ReadLittleLong(sb);
2910 out->plane = loadmodel->brush.data_planes + p;
2912 if (loadmodel->brush.isbsp2rmqe)
2914 child[0] = MSG_ReadLittleLong(sb);
2915 child[1] = MSG_ReadLittleLong(sb);
2916 out->mins[0] = MSG_ReadLittleShort(sb);
2917 out->mins[1] = MSG_ReadLittleShort(sb);
2918 out->mins[2] = MSG_ReadLittleShort(sb);
2919 out->maxs[0] = MSG_ReadLittleShort(sb);
2920 out->maxs[1] = MSG_ReadLittleShort(sb);
2921 out->maxs[2] = MSG_ReadLittleShort(sb);
2922 out->firstsurface = MSG_ReadLittleLong(sb);
2923 out->numsurfaces = MSG_ReadLittleLong(sb);
2925 else if (loadmodel->brush.isbsp2)
2927 child[0] = MSG_ReadLittleLong(sb);
2928 child[1] = MSG_ReadLittleLong(sb);
2929 out->mins[0] = MSG_ReadLittleFloat(sb);
2930 out->mins[1] = MSG_ReadLittleFloat(sb);
2931 out->mins[2] = MSG_ReadLittleFloat(sb);
2932 out->maxs[0] = MSG_ReadLittleFloat(sb);
2933 out->maxs[1] = MSG_ReadLittleFloat(sb);
2934 out->maxs[2] = MSG_ReadLittleFloat(sb);
2935 out->firstsurface = MSG_ReadLittleLong(sb);
2936 out->numsurfaces = MSG_ReadLittleLong(sb);
2940 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2941 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2942 if (child[0] >= count)
2944 if (child[1] >= count)
2947 out->mins[0] = MSG_ReadLittleShort(sb);
2948 out->mins[1] = MSG_ReadLittleShort(sb);
2949 out->mins[2] = MSG_ReadLittleShort(sb);
2950 out->maxs[0] = MSG_ReadLittleShort(sb);
2951 out->maxs[1] = MSG_ReadLittleShort(sb);
2952 out->maxs[2] = MSG_ReadLittleShort(sb);
2954 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2955 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2958 for (j=0 ; j<2 ; j++)
2960 // LadyHavoc: this code supports broken bsp files produced by
2961 // arguire qbsp which can produce more than 32768 nodes, any value
2962 // below count is assumed to be a node number, any other value is
2963 // assumed to be a leaf number
2967 if (p < loadmodel->brush.num_nodes)
2968 out->children[j] = loadmodel->brush.data_nodes + p;
2971 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2972 // map it to the solid leaf
2973 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2978 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2980 if (p < loadmodel->brush.num_leafs)
2981 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2984 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2985 // map it to the solid leaf
2986 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2992 Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2995 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2998 int i, j, count, p, firstmarksurface, nummarksurfaces;
2999 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
3001 if (sb->cursize % structsize)
3002 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3003 count = sb->cursize / structsize;
3004 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3006 loadmodel->brush.data_leafs = out;
3007 loadmodel->brush.num_leafs = count;
3008 // get visleafs from the submodel data
3009 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
3010 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
3011 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
3012 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
3014 // FIXME: this function could really benefit from some error checking
3015 for ( i=0 ; i<count ; i++, out++)
3017 out->contents = MSG_ReadLittleLong(sb);
3019 out->clusterindex = i - 1;
3020 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
3021 out->clusterindex = -1;
3023 p = MSG_ReadLittleLong(sb);
3024 // ignore visofs errors on leaf 0 (solid)
3025 if (p >= 0 && out->clusterindex >= 0)
3027 if (p >= loadmodel->brushq1.num_compressedpvs)
3028 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
3030 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);
3033 if (loadmodel->brush.isbsp2rmqe)
3035 out->mins[0] = MSG_ReadLittleShort(sb);
3036 out->mins[1] = MSG_ReadLittleShort(sb);
3037 out->mins[2] = MSG_ReadLittleShort(sb);
3038 out->maxs[0] = MSG_ReadLittleShort(sb);
3039 out->maxs[1] = MSG_ReadLittleShort(sb);
3040 out->maxs[2] = MSG_ReadLittleShort(sb);
3042 firstmarksurface = MSG_ReadLittleLong(sb);
3043 nummarksurfaces = MSG_ReadLittleLong(sb);
3045 else if (loadmodel->brush.isbsp2)
3047 out->mins[0] = MSG_ReadLittleFloat(sb);
3048 out->mins[1] = MSG_ReadLittleFloat(sb);
3049 out->mins[2] = MSG_ReadLittleFloat(sb);
3050 out->maxs[0] = MSG_ReadLittleFloat(sb);
3051 out->maxs[1] = MSG_ReadLittleFloat(sb);
3052 out->maxs[2] = MSG_ReadLittleFloat(sb);
3054 firstmarksurface = MSG_ReadLittleLong(sb);
3055 nummarksurfaces = MSG_ReadLittleLong(sb);
3059 out->mins[0] = MSG_ReadLittleShort(sb);
3060 out->mins[1] = MSG_ReadLittleShort(sb);
3061 out->mins[2] = MSG_ReadLittleShort(sb);
3062 out->maxs[0] = MSG_ReadLittleShort(sb);
3063 out->maxs[1] = MSG_ReadLittleShort(sb);
3064 out->maxs[2] = MSG_ReadLittleShort(sb);
3066 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
3067 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
3070 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
3072 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3073 out->numleafsurfaces = nummarksurfaces;
3077 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3078 out->firstleafsurface = NULL;
3079 out->numleafsurfaces = 0;
3082 for (j = 0;j < 4;j++)
3083 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3087 static qbool Mod_Q1BSP_CheckWaterAlphaSupport(void)
3091 const unsigned char *pvs;
3092 // if there's no vis data, assume supported (because everything is visible all the time)
3093 if (!loadmodel->brush.data_pvsclusters)
3095 // check all liquid leafs to see if they can see into empty leafs, if any
3096 // can we can assume this map supports r_wateralpha
3097 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3099 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3101 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3102 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3103 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3110 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3115 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3117 if (sb->cursize % structsize)
3118 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3119 count = sb->cursize / structsize;
3120 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3122 loadmodel->brushq1.clipnodes = out;
3123 loadmodel->brushq1.numclipnodes = count;
3125 for (i = 1; i < MAX_MAP_HULLS; i++)
3127 hull = &loadmodel->brushq1.hulls[i];
3128 hull->clipnodes = out;
3129 hull->firstclipnode = 0;
3130 hull->lastclipnode = count-1;
3131 hull->planes = loadmodel->brush.data_planes;
3132 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3133 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3134 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3135 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3136 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3137 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3138 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3141 for (i=0 ; i<count ; i++, out++)
3143 out->planenum = MSG_ReadLittleLong(sb);
3144 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3145 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3146 if (loadmodel->brush.isbsp2)
3148 out->children[0] = MSG_ReadLittleLong(sb);
3149 out->children[1] = MSG_ReadLittleLong(sb);
3150 if (out->children[0] >= count)
3151 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3152 if (out->children[1] >= count)
3153 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3157 // LadyHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3158 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3159 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3160 if (out->children[0] >= count)
3161 out->children[0] -= 65536;
3162 if (out->children[1] >= count)
3163 out->children[1] -= 65536;
3168 //Duplicate the drawing hull structure as a clipping hull
3169 static void Mod_Q1BSP_MakeHull0(void)
3176 hull = &loadmodel->brushq1.hulls[0];
3178 in = loadmodel->brush.data_nodes;
3179 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3181 hull->clipnodes = out;
3182 hull->firstclipnode = 0;
3183 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3184 hull->planes = loadmodel->brush.data_planes;
3186 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3188 out->planenum = in->plane - loadmodel->brush.data_planes;
3189 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3190 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3194 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3197 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3199 if (sb->cursize % structsize)
3200 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3201 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3202 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3204 if (loadmodel->brush.isbsp2)
3206 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3208 j = MSG_ReadLittleLong(sb);
3209 if (j < 0 || j >= loadmodel->num_surfaces)
3210 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3211 loadmodel->brush.data_leafsurfaces[i] = j;
3216 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3218 j = (unsigned short) MSG_ReadLittleShort(sb);
3219 if (j >= loadmodel->num_surfaces)
3220 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3221 loadmodel->brush.data_leafsurfaces[i] = j;
3226 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3231 if (sb->cursize % structsize)
3232 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3233 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3234 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3236 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3237 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3241 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3245 int structsize = 20;
3247 if (sb->cursize % structsize)
3248 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3249 loadmodel->brush.num_planes = sb->cursize / structsize;
3250 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3252 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3254 out->normal[0] = MSG_ReadLittleFloat(sb);
3255 out->normal[1] = MSG_ReadLittleFloat(sb);
3256 out->normal[2] = MSG_ReadLittleFloat(sb);
3257 out->dist = MSG_ReadLittleFloat(sb);
3258 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3263 // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
3264 static void Mod_Q1BSP_AssignNoShadowSkySurfaces(model_t *mod)
3267 msurface_t *surface;
3270 for (surfaceindex = mod->submodelsurfaces_start; surfaceindex < mod->submodelsurfaces_end;surfaceindex++)
3272 surface = mod->data_surfaces + surfaceindex;
3273 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3275 // check if the point behind the surface polygon is SOLID or SKY contents
3276 VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
3277 contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
3278 if (!(contents & SUPERCONTENTS_SOLID))
3279 surface->texture = surface->texture->skynoshadowtexture;
3284 static void Mod_Q1BSP_LoadMapBrushes(void)
3288 int submodel, numbrushes;
3290 char *text, *maptext;
3291 char mapfilename[MAX_QPATH];
3292 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3293 strlcat (mapfilename, ".map", sizeof (mapfilename));
3294 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3298 if (!COM_ParseToken_Simple(&data, false, false, true))
3303 if (!COM_ParseToken_Simple(&data, false, false, true))
3305 if (com_token[0] != '{')
3311 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3314 if (!COM_ParseToken_Simple(&data, false, false, true))
3316 if (com_token[0] == '}')
3317 break; // end of entity
3318 if (com_token[0] == '{')
3325 if (submodel > loadmodel->brush.numsubmodels)
3327 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3331 model = loadmodel->brush.submodels[submodel];
3338 if (!COM_ParseToken_Simple(&data, false, false, true))
3340 if (com_token[0] == '}')
3341 break; // end of brush
3342 // each brush face should be this format:
3343 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3344 // FIXME: support hl .map format
3345 for (pointnum = 0;pointnum < 3;pointnum++)
3347 COM_ParseToken_Simple(&data, false, false, true);
3348 for (componentnum = 0;componentnum < 3;componentnum++)
3350 COM_ParseToken_Simple(&data, false, false, true);
3351 point[pointnum][componentnum] = atof(com_token);
3353 COM_ParseToken_Simple(&data, false, false, true);
3355 COM_ParseToken_Simple(&data, false, false, true);
3356 strlcpy(facetexture, com_token, sizeof(facetexture));
3357 COM_ParseToken_Simple(&data, false, false, true);
3358 //scroll_s = atof(com_token);
3359 COM_ParseToken_Simple(&data, false, false, true);
3360 //scroll_t = atof(com_token);
3361 COM_ParseToken_Simple(&data, false, false, true);
3362 //rotate = atof(com_token);
3363 COM_ParseToken_Simple(&data, false, false, true);
3364 //scale_s = atof(com_token);
3365 COM_ParseToken_Simple(&data, false, false, true);
3366 //scale_t = atof(com_token);
3367 TriangleNormal(point[0], point[1], point[2], planenormal);
3368 VectorNormalizeDouble(planenormal);
3369 planedist = DotProduct(point[0], planenormal);
3370 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3380 #define MAX_PORTALPOINTS 64
3382 typedef struct portal_s
3385 mnode_t *nodes[2]; // [0] = front side of plane
3386 struct portal_s *next[2];
3388 double points[3*MAX_PORTALPOINTS];
3389 struct portal_s *chain; // all portals are linked into a list
3393 static memexpandablearray_t portalarray;
3395 static void Mod_BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3397 // process only nodes (leafs already had their box calculated)
3401 // calculate children first
3402 Mod_BSP_RecursiveRecalcNodeBBox(node->children[0]);
3403 Mod_BSP_RecursiveRecalcNodeBBox(node->children[1]);
3405 // make combined bounding box from children
3406 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3407 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3408 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3409 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3410 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3411 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3414 static void Mod_BSP_FinalizePortals(void)
3416 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3420 mleaf_t *leaf, *endleaf;
3422 // tally up portal and point counts and recalculate bounding boxes for all
3423 // leafs (because qbsp is very sloppy)
3424 leaf = loadmodel->brush.data_leafs;
3425 endleaf = leaf + loadmodel->brush.num_leafs;
3426 if (mod_recalculatenodeboxes.integer)
3428 for (;leaf < endleaf;leaf++)
3430 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3431 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3436 for (portalindex = 0;portalindex < portalrange;portalindex++)
3438 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3441 // note: this check must match the one below or it will usually corrupt memory
3442 // 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
3443 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3446 numpoints += p->numpoints * 2;
3449 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3450 loadmodel->brush.num_portals = numportals;
3451 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3452 loadmodel->brush.num_portalpoints = numpoints;
3453 // clear all leaf portal chains
3454 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3455 loadmodel->brush.data_leafs[i].portals = NULL;
3456 // process all portals in the global portal chain, while freeing them
3457 portal = loadmodel->brush.data_portals;
3458 point = loadmodel->brush.data_portalpoints;
3459 for (portalindex = 0;portalindex < portalrange;portalindex++)
3461 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3464 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3466 // note: this check must match the one above or it will usually corrupt memory
3467 // 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
3468 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3470 // first make the back to front portal(forward portal)
3471 portal->points = point;
3472 portal->numpoints = p->numpoints;
3473 portal->plane.dist = p->plane.dist;
3474 VectorCopy(p->plane.normal, portal->plane.normal);
3475 portal->here = (mleaf_t *)p->nodes[1];
3476 portal->past = (mleaf_t *)p->nodes[0];
3478 for (j = 0;j < portal->numpoints;j++)
3480 VectorCopy(p->points + j*3, point->position);
3483 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3484 PlaneClassify(&portal->plane);
3486 // link into leaf's portal chain
3487 portal->next = portal->here->portals;
3488 portal->here->portals = portal;
3490 // advance to next portal
3493 // then make the front to back portal(backward portal)
3494 portal->points = point;
3495 portal->numpoints = p->numpoints;
3496 portal->plane.dist = -p->plane.dist;
3497 VectorNegate(p->plane.normal, portal->plane.normal);
3498 portal->here = (mleaf_t *)p->nodes[0];
3499 portal->past = (mleaf_t *)p->nodes[1];
3501 for (j = portal->numpoints - 1;j >= 0;j--)
3503 VectorCopy(p->points + j*3, point->position);
3506 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3507 PlaneClassify(&portal->plane);
3509 // link into leaf's portal chain
3510 portal->next = portal->here->portals;
3511 portal->here->portals = portal;
3513 // advance to next portal
3516 // add the portal's polygon points to the leaf bounding boxes
3517 if (mod_recalculatenodeboxes.integer)
3519 for (i = 0;i < 2;i++)
3521 leaf = (mleaf_t *)p->nodes[i];
3522 for (j = 0;j < p->numpoints;j++)
3524 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3525 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3526 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3527 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3528 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3529 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3535 // now recalculate the node bounding boxes from the leafs
3536 if (mod_recalculatenodeboxes.integer)
3537 Mod_BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3545 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3548 Host_Error("AddPortalToNodes: NULL front node");
3550 Host_Error("AddPortalToNodes: NULL back node");
3551 if (p->nodes[0] || p->nodes[1])
3552 Host_Error("AddPortalToNodes: already included");
3553 // 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
3555 p->nodes[0] = front;
3556 p->next[0] = (portal_t *)front->portals;
3557 front->portals = (mportal_t *)p;
3560 p->next[1] = (portal_t *)back->portals;
3561 back->portals = (mportal_t *)p;
3566 RemovePortalFromNode
3569 static void RemovePortalFromNodes(portal_t *portal)
3573 void **portalpointer;
3575 for (i = 0;i < 2;i++)
3577 node = portal->nodes[i];
3579 portalpointer = (void **) &node->portals;
3582 t = (portal_t *)*portalpointer;
3584 Host_Error("RemovePortalFromNodes: portal not in leaf");
3588 if (portal->nodes[0] == node)
3590 *portalpointer = portal->next[0];
3591 portal->nodes[0] = NULL;
3593 else if (portal->nodes[1] == node)
3595 *portalpointer = portal->next[1];
3596 portal->nodes[1] = NULL;
3599 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3603 if (t->nodes[0] == node)
3604 portalpointer = (void **) &t->next[0];
3605 else if (t->nodes[1] == node)
3606 portalpointer = (void **) &t->next[1];
3608 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3613 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3614 static double *portalpointsbuffer;
3615 static int portalpointsbufferoffset;
3616 static int portalpointsbuffersize;
3617 static void Mod_BSP_RecursiveNodePortals(mnode_t *node)
3620 mnode_t *front, *back, *other_node;
3621 mplane_t clipplane, *plane;
3622 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3623 int numfrontpoints, numbackpoints;
3624 double *frontpoints, *backpoints;
3626 // if a leaf, we're done
3630 // get some space for our clipping operations to use
3631 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3633 portalpointsbuffersize = portalpointsbufferoffset * 2;
3634 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3636 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3637 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3638 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3639 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3641 plane = node->plane;
3643 front = node->children[0];
3644 back = node->children[1];
3646 Host_Error("Mod_BSP_RecursiveNodePortals: corrupt node hierarchy");
3648 // create the new portal by generating a polygon for the node plane,
3649 // and clipping it by all of the other portals(which came from nodes above this one)
3650 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3651 nodeportal->plane = *plane;
3653 // 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)
3654 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);
3655 nodeportal->numpoints = 4;
3657 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3659 clipplane = portal->plane;
3660 if (portal->nodes[0] == portal->nodes[1])
3661 Host_Error("Mod_BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3662 if (portal->nodes[0] == node)
3664 else if (portal->nodes[1] == node)
3666 clipplane.dist = -clipplane.dist;
3667 VectorNegate(clipplane.normal, clipplane.normal);
3672 Host_Error("Mod_BSP_RecursiveNodePortals: mislinked portal");
3673 side = 0; // hush warning
3676 for (i = 0;i < nodeportal->numpoints*3;i++)
3677 frontpoints[i] = nodeportal->points[i];
3678 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);
3679 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3683 if (nodeportal->numpoints < 3)
3685 Con_Print(CON_WARN "Mod_BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3686 nodeportal->numpoints = 0;
3688 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3690 Con_Print(CON_WARN "Mod_BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3691 nodeportal->numpoints = 0;
3694 AddPortalToNodes(nodeportal, front, back);
3696 // split the portals of this node along this node's plane and assign them to the children of this node
3697 // (migrating the portals downward through the tree)
3698 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3700 if (portal->nodes[0] == portal->nodes[1])
3701 Host_Error("Mod_BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3702 if (portal->nodes[0] == node)
3704 else if (portal->nodes[1] == node)
3708 Host_Error("Mod_BSP_RecursiveNodePortals: mislinked portal");
3709 side = 0; // hush warning
3711 nextportal = portal->next[side];
3712 if (!portal->numpoints)
3715 other_node = portal->nodes[!side];
3716 RemovePortalFromNodes(portal);
3718 // cut the portal into two portals, one on each side of the node plane
3719 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);
3721 if (!numfrontpoints)
3724 AddPortalToNodes(portal, back, other_node);
3726 AddPortalToNodes(portal, other_node, back);
3732 AddPortalToNodes(portal, front, other_node);
3734 AddPortalToNodes(portal, other_node, front);
3738 // the portal is split
3739 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3740 temp = splitportal->chain;
3741 *splitportal = *portal;
3742 splitportal->chain = temp;
3743 for (i = 0;i < numbackpoints*3;i++)
3744 splitportal->points[i] = backpoints[i];
3745 splitportal->numpoints = numbackpoints;
3746 for (i = 0;i < numfrontpoints*3;i++)
3747 portal->points[i] = frontpoints[i];
3748 portal->numpoints = numfrontpoints;
3752 AddPortalToNodes(portal, front, other_node);
3753 AddPortalToNodes(splitportal, back, other_node);
3757 AddPortalToNodes(portal, other_node, front);
3758 AddPortalToNodes(splitportal, other_node, back);
3762 Mod_BSP_RecursiveNodePortals(front);
3763 Mod_BSP_RecursiveNodePortals(back);
3765 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3768 static void Mod_BSP_MakePortals(void)
3770 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3771 portalpointsbufferoffset = 0;
3772 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3773 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3774 Mod_BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3775 Mem_Free(portalpointsbuffer);
3776 portalpointsbuffer = NULL;
3777 portalpointsbufferoffset = 0;
3778 portalpointsbuffersize = 0;
3779 Mod_BSP_FinalizePortals();
3780 Mem_ExpandableArray_FreeArray(&portalarray);
3783 //Returns PVS data for a given point
3784 //(note: can return NULL)
3785 static unsigned char *Mod_BSP_GetPVS(model_t *model, const vec3_t p)
3788 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3790 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3791 if (((mleaf_t *)node)->clusterindex >= 0)
3792 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3797 static void Mod_BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
3801 float d = PlaneDiff(org, node->plane);
3803 node = node->children[0];
3804 else if (d < -radius)
3805 node = node->children[1];
3808 // go down both sides
3809 Mod_BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3810 node = node->children[1];
3813 // if this leaf is in a cluster, accumulate the pvs bits
3814 if (((mleaf_t *)node)->clusterindex >= 0)
3817 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3818 for (i = 0;i < pvsbytes;i++)
3819 pvsbuffer[i] |= pvs[i];
3823 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3824 //of the given point.
3825 static int Mod_BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qbool merge)
3827 int bytes = model->brush.num_pvsclusterbytes;
3828 bytes = min(bytes, pvsbufferlength);
3829 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_BSP_GetPVS(model, org))
3831 memset(pvsbuffer, 0xFF, bytes);
3835 memset(pvsbuffer, 0, bytes);
3836 Mod_BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3840 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3845 VectorSubtract(inmaxs, inmins, size);
3846 if (size[0] < mod_q1bsp_zero_hullsize_cutoff.value)
3847 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3848 else if (cmodel->brush.ishlbsp)
3852 if (size[2] < 54) // pick the nearest of 36 or 72
3853 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3855 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3858 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3863 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3865 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3867 VectorCopy(inmins, outmins);
3868 VectorAdd(inmins, hull->clip_size, outmaxs);
3871 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);
3873 void Mod_2PSB_Load(model_t *mod, void *buffer, void *bufferend)
3875 mod->brush.isbsp2 = true;
3876 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3877 mod->modeldatatypestring = "Q1BSP2rmqe";
3878 Mod_Q1BSP_Load(mod, buffer, bufferend);
3881 void Mod_BSP2_Load(model_t *mod, void *buffer, void *bufferend)
3883 mod->brush.isbsp2 = true;
3884 mod->modeldatatypestring = "Q1BSP2";
3885 Mod_Q1BSP_Load(mod, buffer, bufferend);
3888 void Mod_HLBSP_Load(model_t *mod, void *buffer, void *bufferend)
3890 mod->brush.ishlbsp = true;
3891 mod->modeldatatypestring = "HLBSP";
3892 Mod_Q1BSP_Load(mod, buffer, bufferend);
3895 void Mod_Q1BSP_Load(model_t *mod, void *buffer, void *bufferend)
3898 sizebuf_t lumpsb[HEADER_LUMPS];
3900 float dist, modelyawradius, modelradius;
3901 msurface_t *surface;
3902 hullinfo_t hullinfo;
3903 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3904 model_brush_lightstyleinfo_t styleinfo[256];
3906 model_brush_lightstyleinfo_t *lsidatapointer;
3909 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3911 mod->type = mod_brushq1;
3913 mod->brush.skymasking = true;
3914 i = MSG_ReadLittleLong(&sb);
3916 if(!mod->modeldatatypestring)
3917 mod->modeldatatypestring = "Q1BSP";
3919 // fill in hull info
3920 VectorClear (hullinfo.hullsizes[0][0]);
3921 VectorClear (hullinfo.hullsizes[0][1]);
3922 if (mod->brush.ishlbsp)
3924 hullinfo.filehulls = 4;
3925 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3926 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3927 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3928 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3929 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3930 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3934 hullinfo.filehulls = 4;
3935 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3936 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3937 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3938 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3942 for (i = 0; i < HEADER_LUMPS; i++)
3944 int offset = MSG_ReadLittleLong(&sb);
3945 int size = MSG_ReadLittleLong(&sb);
3946 if (offset < 0 || offset + size > sb.cursize)
3947 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);
3948 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3951 mod->soundfromcenter = true;
3952 mod->TraceBox = Mod_Q1BSP_TraceBox;
3953 mod->TraceLine = Mod_Q1BSP_TraceLine;
3954 mod->TracePoint = Mod_Q1BSP_TracePoint;
3955 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3956 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3957 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3958 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3959 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3960 mod->brush.GetPVS = Mod_BSP_GetPVS;
3961 mod->brush.FatPVS = Mod_BSP_FatPVS;
3962 mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
3963 mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
3964 mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
3965 mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
3966 mod->brush.LightPoint = Mod_BSP_LightPoint;
3967 mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
3968 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3969 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3970 mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
3971 mod->Draw = R_Mod_Draw;
3972 mod->DrawDepth = R_Mod_DrawDepth;
3973 mod->DrawDebug = R_Mod_DrawDebug;
3974 mod->DrawPrepass = R_Mod_DrawPrepass;
3975 mod->GetLightInfo = R_Mod_GetLightInfo;
3976 mod->CompileShadowMap = R_Mod_CompileShadowMap;
3977 mod->DrawShadowMap = R_Mod_DrawShadowMap;
3978 mod->DrawLight = R_Mod_DrawLight;
3982 mod->brush.qw_md4sum = 0;
3983 mod->brush.qw_md4sum2 = 0;
3984 for (i = 0;i < HEADER_LUMPS;i++)
3987 if (i == LUMP_ENTITIES)
3989 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3990 mod->brush.qw_md4sum ^= LittleLong(temp);
3991 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3993 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3996 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3997 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3998 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3999 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
4000 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
4001 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
4002 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
4003 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
4004 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
4005 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
4006 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
4007 // load submodels before leafs because they contain the number of vis leafs
4008 Mod_BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
4009 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
4010 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
4011 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
4013 for (i = 0; i < HEADER_LUMPS; i++)
4014 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
4015 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4017 // check if the map supports transparent water rendering
4018 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
4020 // we don't need the compressed pvs data anymore
4021 if (mod->brushq1.data_compressedpvs)
4022 Mem_Free(mod->brushq1.data_compressedpvs);
4023 mod->brushq1.data_compressedpvs = NULL;
4024 mod->brushq1.num_compressedpvs = 0;
4026 Mod_Q1BSP_MakeHull0();
4027 if (mod_bsp_portalize.integer && cls.state != ca_dedicated)
4028 Mod_BSP_MakePortals();
4030 mod->numframes = 2; // regular and alternate animation
4033 if (loadmodel->brush.numsubmodels)
4034 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
4036 // LadyHavoc: to clear the fog around the original quake submodel code, I
4038 // first of all, some background info on the submodels:
4039 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
4040 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
4041 // now the weird for loop itself:
4042 // the loop functions in an odd way, on each iteration it sets up the
4043 // current 'mod' model (which despite the confusing code IS the model of
4044 // the number i), at the end of the loop it duplicates the model to become
4045 // the next submodel, and loops back to set up the new submodel.
4047 // LadyHavoc: now the explanation of my sane way (which works identically):
4048 // set up the world model, then on each submodel copy from the world model
4049 // and set up the submodel with the respective model info.
4050 totalstylesurfaces = 0;
4052 for (i = 0;i < mod->brush.numsubmodels;i++)
4054 memset(stylecounts, 0, sizeof(stylecounts));
4055 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4057 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4058 for (j = 0;j < MAXLIGHTMAPS;j++)
4059 stylecounts[surface->lightmapinfo->styles[j]]++;
4061 for (k = 0;k < 255;k++)
4065 totalstylesurfaces += stylecounts[k];
4068 // bones_was_here: using a separate allocation for model_brush_lightstyleinfo_t
4069 // because on a 64-bit machine it no longer has the same alignment requirement as int.
4070 lsidatapointer = Mem_AllocType(mod->mempool, model_brush_lightstyleinfo_t, totalstyles * sizeof(model_brush_lightstyleinfo_t));
4071 datapointer = Mem_AllocType(mod->mempool, int, mod->num_surfaces * sizeof(int) + totalstylesurfaces * sizeof(int));
4072 mod->modelsurfaces_sorted = datapointer;datapointer += mod->num_surfaces;
4073 for (i = 0;i < mod->brush.numsubmodels;i++)
4075 // LadyHavoc: this code was originally at the end of this loop, but
4076 // has been transformed to something more readable at the start here.
4081 // duplicate the basic information
4082 dpsnprintf(name, sizeof(name), "*%i", i);
4083 mod = Mod_FindName(name, loadmodel->name);
4084 // copy the base model to this one
4086 // rename the clone back to its proper name
4087 dp_strlcpy(mod->name, name, sizeof(mod->name));
4088 mod->brush.parentmodel = loadmodel;
4089 // textures and memory belong to the main model
4090 mod->texturepool = NULL;
4091 mod->mempool = NULL;
4092 mod->brush.GetPVS = NULL;
4093 mod->brush.FatPVS = NULL;
4094 mod->brush.BoxTouchingPVS = NULL;
4095 mod->brush.BoxTouchingLeafPVS = NULL;
4096 mod->brush.BoxTouchingVisibleLeafs = NULL;
4097 mod->brush.FindBoxClusters = NULL;
4098 mod->brush.LightPoint = NULL;
4099 mod->brush.AmbientSoundLevelsForPoint = NULL;
4102 mod->brush.submodel = i;
4104 if (loadmodel->brush.submodels)
4105 loadmodel->brush.submodels[i] = mod;
4107 bm = &mod->brushq1.submodels[i];
4109 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4110 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4112 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4113 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4116 mod->submodelsurfaces_start = bm->firstface;
4117 mod->submodelsurfaces_end = bm->firstface + bm->numfaces;
4119 // set node/leaf parents for this submodel
4120 Mod_BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4122 // this has to occur after hull info has been set, as it uses Mod_Q1BSP_PointSuperContents
4123 Mod_Q1BSP_AssignNoShadowSkySurfaces(mod);
4125 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4126 // (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)
4127 VectorCopy(bm->mins, mod->normalmins);
4128 VectorCopy(bm->maxs, mod->normalmaxs);
4129 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4130 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4131 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4132 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4133 modelradius = modelyawradius + modelradius * modelradius;
4134 modelyawradius = sqrt(modelyawradius);
4135 modelradius = sqrt(modelradius);
4136 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4137 mod->yawmins[2] = mod->normalmins[2];
4138 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4139 mod->yawmaxs[2] = mod->normalmaxs[2];
4140 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4141 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4142 mod->radius = modelradius;
4143 mod->radius2 = modelradius * modelradius;
4145 Mod_SetDrawSkyAndWater(mod);
4147 if (mod->submodelsurfaces_start < mod->submodelsurfaces_end)
4149 // build lightstyle update chains
4150 // (used to rapidly mark lightmapupdateflags on many surfaces
4151 // when d_lightstylevalue changes)
4152 memset(stylecounts, 0, sizeof(stylecounts));
4153 for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
4154 for (j = 0;j < MAXLIGHTMAPS;j++)
4155 stylecounts[mod->data_surfaces[k].lightmapinfo->styles[j]]++;
4156 mod->brushq1.num_lightstyles = 0;
4157 for (k = 0;k < 255;k++)
4161 styleinfo[mod->brushq1.num_lightstyles].style = k;
4162 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4163 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4164 styleinfo[mod->brushq1.num_lightstyles].surfacelist = datapointer;datapointer += stylecounts[k];
4165 remapstyles[k] = mod->brushq1.num_lightstyles;
4166 mod->brushq1.num_lightstyles++;
4169 for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
4171 surface = mod->data_surfaces + k;
4172 for (j = 0;j < MAXLIGHTMAPS;j++)
4174 if (surface->lightmapinfo->styles[j] != 255)
4176 int r = remapstyles[surface->lightmapinfo->styles[j]];
4177 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = k;
4181 mod->brushq1.data_lightstyleinfo = lsidatapointer;lsidatapointer += mod->brushq1.num_lightstyles;
4182 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4186 // LadyHavoc: empty submodel(lacrima.bsp has such a glitch)
4187 Con_Printf(CON_WARN "warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4189 //mod->brushq1.num_visleafs = bm->visleafs;
4191 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4192 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4194 if (mod_q1bsp_polygoncollisions.integer)
4196 mod->collision_bih = mod->render_bih;
4197 // point traces and contents checks still use the bsp tree
4198 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4199 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4200 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4201 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4204 // generate VBOs and other shared data before cloning submodels
4208 Mod_Q1BSP_LoadMapBrushes();
4209 //Mod_Q1BSP_ProcessLightList();
4214 // make the model surface list (used by shadowing/lighting)
4215 Mod_MakeSortedSurfaces(loadmodel);
4217 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);
4220 int Mod_Q2BSP_SuperContentsFromNativeContents(int nativecontents)
4222 int supercontents = 0;
4223 if (nativecontents & CONTENTSQ2_SOLID)
4224 supercontents |= SUPERCONTENTS_SOLID;
4225 if (nativecontents & CONTENTSQ2_WATER)
4226 supercontents |= SUPERCONTENTS_WATER;
4227 if (nativecontents & CONTENTSQ2_SLIME)
4228 supercontents |= SUPERCONTENTS_SLIME;
4229 if (nativecontents & CONTENTSQ2_LAVA)
4230 supercontents |= SUPERCONTENTS_LAVA;
4231 if (nativecontents & CONTENTSQ2_MONSTER)
4232 supercontents |= SUPERCONTENTS_BODY;
4233 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4234 supercontents |= SUPERCONTENTS_CORPSE;
4235 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4236 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4237 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4238 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4239 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4240 supercontents |= SUPERCONTENTS_OPAQUE;
4241 return supercontents;
4244 int Mod_Q2BSP_NativeContentsFromSuperContents(int supercontents)
4246 int nativecontents = 0;
4247 if (supercontents & SUPERCONTENTS_SOLID)
4248 nativecontents |= CONTENTSQ2_SOLID;
4249 if (supercontents & SUPERCONTENTS_WATER)
4250 nativecontents |= CONTENTSQ2_WATER;
4251 if (supercontents & SUPERCONTENTS_SLIME)
4252 nativecontents |= CONTENTSQ2_SLIME;
4253 if (supercontents & SUPERCONTENTS_LAVA)
4254 nativecontents |= CONTENTSQ2_LAVA;
4255 if (supercontents & SUPERCONTENTS_BODY)
4256 nativecontents |= CONTENTSQ2_MONSTER;
4257 if (supercontents & SUPERCONTENTS_CORPSE)
4258 nativecontents |= CONTENTSQ2_DEADMONSTER;
4259 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4260 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4261 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4262 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4263 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4264 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4265 return nativecontents;
4268 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4271 loadmodel->brushq1.num_compressedpvs = 0;
4272 loadmodel->brushq1.data_compressedpvs = NULL;
4273 loadmodel->brush.num_pvsclusters = 0;
4274 loadmodel->brush.num_pvsclusterbytes = 0;
4275 loadmodel->brush.data_pvsclusters = NULL;
4280 count = MSG_ReadLittleLong(sb);
4281 loadmodel->brush.num_pvsclusters = count;
4282 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4283 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4284 for (i = 0;i < count;i++)
4286 int pvsofs = MSG_ReadLittleLong(sb);
4287 /*int phsofs = */MSG_ReadLittleLong(sb);
4288 // decompress the vis data for this cluster
4289 // (note this accesses the underlying data store of sb, which is kind of evil)
4290 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);
4292 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4293 sb->readcount = sb->cursize;
4296 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4298 int i, j, count, p, child[2];
4300 int structsize = 28;
4302 if (sb->cursize % structsize)
4303 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4304 count = sb->cursize / structsize;
4306 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4307 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4309 loadmodel->brush.data_nodes = out;
4310 loadmodel->brush.num_nodes = count;
4312 for ( i=0 ; i<count ; i++, out++)
4314 p = MSG_ReadLittleLong(sb);
4315 out->plane = loadmodel->brush.data_planes + p;
4316 child[0] = MSG_ReadLittleLong(sb);
4317 child[1] = MSG_ReadLittleLong(sb);
4318 out->mins[0] = MSG_ReadLittleShort(sb);
4319 out->mins[1] = MSG_ReadLittleShort(sb);
4320 out->mins[2] = MSG_ReadLittleShort(sb);
4321 out->maxs[0] = MSG_ReadLittleShort(sb);
4322 out->maxs[1] = MSG_ReadLittleShort(sb);
4323 out->maxs[2] = MSG_ReadLittleShort(sb);
4324 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4325 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4326 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4328 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4329 out->firstsurface = 0;
4330 out->numsurfaces = 0;
4332 for (j=0 ; j<2 ; j++)
4337 if (p < loadmodel->brush.num_nodes)
4338 out->children[j] = loadmodel->brush.data_nodes + p;
4341 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4342 // map it to the solid leaf
4343 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4348 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4350 if (p < loadmodel->brush.num_leafs)
4351 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4354 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4355 // map it to the solid leaf
4356 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4362 Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4365 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4369 int structsize = 76;
4370 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4371 char filename[MAX_QPATH];
4373 if (sb->cursize % structsize)
4374 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4375 count = sb->cursize / structsize;
4376 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4377 loadmodel->brushq1.texinfo = out;
4378 loadmodel->brushq1.numtexinfo = count;
4379 loadmodel->num_texturesperskin = 0;
4380 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4382 for (i = 0;i < count;i++, out++)
4385 for (k = 0;k < 2;k++)
4386 for (j = 0;j < 4;j++)
4387 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4389 out->q2flags = MSG_ReadLittleLong(sb);
4390 out->q2value = MSG_ReadLittleLong(sb);
4391 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4392 out->q2texture[31] = 0; // make absolutely sure it is terminated
4393 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4395 // find an existing match for the texture if possible
4396 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4397 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4398 if (!strcmp(filename, loadmodel->data_textures[j].name)
4399 && out->q2flags == loadmodel->data_textures[j].q2flags
4400 && out->q2value == loadmodel->data_textures[j].q2value)
4402 // if we don't find the texture, store the new texture
4403 if (j == loadmodel->num_texturesperskin)
4405 if (loadmodel->num_texturesperskin < maxtextures)
4407 texture_t *tx = loadmodel->data_textures + j;
4408 int q2flags = out->q2flags;
4409 unsigned char *walfile = NULL;
4410 fs_offset_t walfilesize = 0;
4411 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
4412 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4413 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4417 LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4427 tx->q2flags = out->q2flags;
4428 tx->q2value = out->q2value;
4429 // also modify the texture to have the correct contents and such based on flags
4430 // note that we create multiple texture_t structures if q2flags differs
4431 if (q2flags & Q2SURF_LIGHT)
4433 // doesn't mean anything to us
4435 if (q2flags & Q2SURF_SLICK)
4437 // would be nice to support...
4439 if (q2flags & Q2SURF_SKY)
4441 // sky is a rather specific thing
4442 q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4443 tx->basematerialflags = MATERIALFLAG_SKY;
4444 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4445 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4447 if (q2flags & Q2SURF_WARP)
4449 // we use a scroll instead of a warp
4450 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4451 // if it's also transparent, we can enable the WATERSHADER
4452 // but we do not set the WATERALPHA flag because we don't
4453 // want to honor r_wateralpha in q2bsp
4454 // (it would go against the artistic intent)
4455 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4456 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4458 if (q2flags & Q2SURF_TRANS33)
4460 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4461 tx->basealpha = 1.0f / 3.0f;
4462 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4463 if (tx->q2contents & Q2CONTENTS_SOLID)
4464 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4466 if (q2flags & Q2SURF_TRANS66)
4468 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4469 tx->basealpha = 2.0f / 3.0f;
4470 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4471 if (tx->q2contents & Q2CONTENTS_SOLID)
4472 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4474 if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
4476 tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4477 if (q2flags & Q2SURF_WARP)
4478 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4480 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4481 tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4483 if (q2flags & Q2SURF_ALPHATEST)
4485 // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4486 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4488 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4490 if (!mod_q2bsp_littransparentsurfaces.integer)
4491 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4493 if (q2flags & Q2SURF_NODRAW)
4495 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4497 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4498 tx->q2contents |= Q2CONTENTS_DETAIL;
4499 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4500 tx->q2contents |= Q2CONTENTS_SOLID;
4501 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4503 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(tx->q2contents);
4504 // set the current values to the base values
4505 tx->currentframe = tx;
4506 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
4507 tx->currentmaterialflags = tx->basematerialflags;
4508 loadmodel->num_texturesperskin++;
4509 loadmodel->num_textures = loadmodel->num_texturesperskin;
4513 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4514 j = 0; // use first texture and give up
4517 // store the index we found for this texture
4518 out->textureindex = j;
4521 // realloc the textures array now that we know how many we actually need
4522 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4524 // now assemble the texture chains
4525 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4526 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4529 texture_t *t = loadmodel->data_textures + out->textureindex;
4530 t->currentframe = t; // fix the reallocated pointer
4532 // if this is not animated, skip it
4533 // if this is already processed, skip it (part of an existing sequence)
4534 if (out->q2nexttexinfo == 0 || t->animated)
4537 // store the array of frames to use
4538 t->animated = 2; // q2bsp animation
4539 t->anim_total[0] = 0;
4540 t->anim_total[1] = 0;
4541 // gather up to 10 frames (we don't support more)
4542 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)
4544 // detect looping and stop there
4545 if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4547 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4549 // we could look for the +a sequence here if this is the +0 sequence,
4550 // but it seems that quake2 did not implement that (even though the
4551 // files exist in the baseq2 content)
4553 // write the frame sequence to all the textures involved (just like
4554 // in the q1bsp loader)
4556 // note that this can overwrite the rest of the sequence - so if the
4557 // start of a sequence is found later than the other parts of the
4558 // sequence, it will go back and rewrite them correctly.
4559 for (k = 0;k < t->anim_total[0];k++)
4561 texture_t *txk = t->anim_frames[0][k];
4562 txk->animated = t->animated;
4563 txk->anim_total[0] = t->anim_total[0];
4564 for (l = 0;l < t->anim_total[0];l++)
4565 txk->anim_frames[0][l] = t->anim_frames[0][l];
4570 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4572 // LadyHavoc: this fits exactly the same format that we use in .lit files
4573 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4574 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4577 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4580 int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4581 int structsize = 28;
4583 if (sb->cursize % structsize)
4584 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4585 count = sb->cursize / structsize;
4586 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4588 loadmodel->brush.data_leafs = out;
4589 loadmodel->brush.num_leafs = count;
4591 // FIXME: this function could really benefit from some error checking
4592 for ( i=0 ; i<count ; i++, out++)
4594 out->contents = MSG_ReadLittleLong(sb);
4595 out->clusterindex = MSG_ReadLittleShort(sb);
4596 out->areaindex = MSG_ReadLittleShort(sb);
4597 out->mins[0] = MSG_ReadLittleShort(sb);
4598 out->mins[1] = MSG_ReadLittleShort(sb);
4599 out->mins[2] = MSG_ReadLittleShort(sb);
4600 out->maxs[0] = MSG_ReadLittleShort(sb);
4601 out->maxs[1] = MSG_ReadLittleShort(sb);
4602 out->maxs[2] = MSG_ReadLittleShort(sb);
4604 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4605 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4606 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4607 nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
4609 for (j = 0;j < 4;j++)
4610 out->ambient_sound_level[j] = 0;
4612 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4614 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4615 out->clusterindex = -1;
4618 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4620 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4621 out->numleafsurfaces = nummarksurfaces;
4625 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4626 out->firstleafsurface = NULL;
4627 out->numleafsurfaces = 0;
4630 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4632 out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4633 out->numleafbrushes = nummarkbrushes;
4637 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4638 out->firstleafbrush = NULL;
4639 out->numleafbrushes = 0;
4644 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4649 if (sb->cursize % structsize)
4650 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4651 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4652 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4654 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4656 j = (unsigned short) MSG_ReadLittleShort(sb);
4657 if (j >= loadmodel->brush.num_brushes)
4658 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4659 loadmodel->brush.data_leafbrushes[i] = j;
4663 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4665 q3mbrushside_t *out;
4669 if (sb->cursize % structsize)
4670 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4671 count = sb->cursize / structsize;
4672 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4674 loadmodel->brush.data_brushsides = out;
4675 loadmodel->brush.num_brushsides = count;
4677 for (i = 0;i < count;i++, out++)
4679 n = (unsigned short)MSG_ReadLittleShort(sb);
4680 if (n < 0 || n >= loadmodel->brush.num_planes)
4681 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4682 out->plane = loadmodel->brush.data_planes + n;
4683 n = MSG_ReadLittleShort(sb);
4686 if (n >= loadmodel->brushq1.numtexinfo)
4687 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4688 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4692 //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4693 out->texture = &mod_q1bsp_texture_solid;
4698 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4701 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4702 colplanef_t *planes;
4703 int structsize = 12;
4704 qbool brushmissingtextures;
4705 int numbrushesmissingtextures = 0;
4706 int numcreatedtextures = 0;
4708 if (sb->cursize % structsize)
4709 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4710 count = sb->cursize / structsize;
4711 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4713 loadmodel->brush.data_brushes = out;
4714 loadmodel->brush.num_brushes = count;
4719 for (i = 0; i < count; i++, out++)
4721 firstside = MSG_ReadLittleLong(sb);
4722 numsides = MSG_ReadLittleLong(sb);
4723 contents = MSG_ReadLittleLong(sb);
4724 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4725 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4727 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4728 out->numbrushsides = numsides;
4729 // convert the contents to our values
4730 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(contents);
4732 // problem: q2bsp brushes have contents but not a texture
4733 // problem: q2bsp brushsides *may* have a texture or may not
4734 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4735 // solution: nasty hacks
4736 brushmissingtextures = false;
4737 out->texture = NULL;
4738 for (j = 0; j < out->numbrushsides; j++)
4740 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4741 brushmissingtextures = true;
4744 // if we can find a matching texture on a brush side we can use it instead of creating one
4745 if (out->firstbrushside[j].texture->supercontents == supercontents)
4746 out->texture = out->firstbrushside[j].texture;
4749 if (brushmissingtextures || out->texture == NULL)
4751 numbrushesmissingtextures++;
4752 // if we didn't find any appropriate texture (matching contents), we'll have to create one
4753 // we could search earlier ones for a matching one but that can be slow
4754 if (out->texture == NULL)
4756 texture_t *validtexture;
4757 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4758 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4759 validtexture->surfaceflags = 0;
4760 validtexture->supercontents = supercontents;
4761 numcreatedtextures++;
4762 out->texture = validtexture;
4764 // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4765 for (j = 0; j < out->numbrushsides; j++)
4766 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4767 out->firstbrushside[j].texture = out->texture;
4770 // make a colbrush from the brush
4772 // make a list of mplane_t structs to construct a colbrush from
4773 if (maxplanes < out->numbrushsides)
4775 maxplanes = out->numbrushsides;
4778 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4780 for (j = 0;j < out->numbrushsides;j++)
4782 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4783 planes[j].dist = out->firstbrushside[j].plane->dist;
4784 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4785 planes[j].texture = out->firstbrushside[j].texture;
4786 q3surfaceflags |= planes[j].q3surfaceflags;
4788 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4790 // this whole loop can take a while (e.g. on redstarrepublic4)
4791 CL_KeepaliveMessage(false);
4795 if (numcreatedtextures)
4796 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);
4799 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4801 // 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)
4802 sb->readcount = sb->cursize;
4805 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4807 // we currently don't use areas, they represent closable doors as vis blockers
4808 sb->readcount = sb->cursize;
4811 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4813 // we currently don't use areas, they represent closable doors as vis blockers
4814 sb->readcount = sb->cursize;
4817 static void Mod_Q2BSP_FindSubmodelBrushRange_r(model_t *mod, mnode_t *node, int *first, int *last)
4823 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4824 node = node->children[1];
4826 leaf = (mleaf_t*)node;
4827 for (i = 0;i < leaf->numleafbrushes;i++)
4829 int brushnum = leaf->firstleafbrush[i];
4830 if (*first > brushnum)
4832 if (*last < brushnum)
4837 static void Mod_Q2BSP_Load(model_t *mod, void *buffer, void *bufferend)
4840 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4842 float dist, modelyawradius, modelradius;
4843 msurface_t *surface;
4844 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4845 model_brush_lightstyleinfo_t styleinfo[256];
4847 model_brush_lightstyleinfo_t *lsidatapointer;
4850 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4852 mod->type = mod_brushq2;
4854 mod->brush.ishlbsp = false;
4855 mod->brush.isbsp2rmqe = false;
4856 mod->brush.isbsp2 = false;
4857 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4858 mod->brush.isq3bsp = false;
4859 mod->brush.skymasking = true;
4860 mod->modeldatatypestring = "Q2BSP";
4862 i = MSG_ReadLittleLong(&sb);
4863 if (i != Q2BSPMAGIC)
4864 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4866 i = MSG_ReadLittleLong(&sb);
4867 if (i != Q2BSPVERSION)
4868 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4871 for (i = 0; i < Q2HEADER_LUMPS; i++)
4873 int offset = MSG_ReadLittleLong(&sb);
4874 int size = MSG_ReadLittleLong(&sb);
4875 if (offset < 0 || offset + size > sb.cursize)
4876 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);
4877 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4880 mod->soundfromcenter = true;
4881 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4882 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4883 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4884 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4885 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4886 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4887 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4888 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4889 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4890 mod->brush.GetPVS = Mod_BSP_GetPVS;
4891 mod->brush.FatPVS = Mod_BSP_FatPVS;
4892 mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
4893 mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
4894 mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
4895 mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
4896 mod->brush.LightPoint = Mod_BSP_LightPoint;
4897 mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
4898 mod->brush.AmbientSoundLevelsForPoint = NULL;
4899 mod->brush.RoundUpToHullSize = NULL;
4900 mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
4901 mod->Draw = R_Mod_Draw;
4902 mod->DrawDepth = R_Mod_DrawDepth;
4903 mod->DrawDebug = R_Mod_DrawDebug;
4904 mod->DrawPrepass = R_Mod_DrawPrepass;
4905 mod->GetLightInfo = R_Mod_GetLightInfo;
4906 mod->CompileShadowMap = R_Mod_CompileShadowMap;
4907 mod->DrawShadowMap = R_Mod_DrawShadowMap;
4908 mod->DrawLight = R_Mod_DrawLight;
4912 mod->brush.qw_md4sum = 0;
4913 mod->brush.qw_md4sum2 = 0;
4914 for (i = 0;i < Q2HEADER_LUMPS;i++)
4917 if (i == Q2LUMP_ENTITIES)
4919 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4920 mod->brush.qw_md4sum ^= LittleLong(temp);
4921 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4923 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4926 // many of these functions are identical to Q1 loaders, so we use those where possible
4927 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4928 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4929 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4930 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4931 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4932 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4933 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4934 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4935 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4936 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4937 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4938 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4939 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4940 Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4941 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4942 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4943 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4944 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4945 Mod_BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS], NULL);
4947 for (i = 0; i < Q2HEADER_LUMPS; i++)
4948 if (lumpsb[i].readcount != lumpsb[i].cursize)
4949 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4951 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4952 // doesn't enable the cvar, just indicates that transparent water is OK
4953 loadmodel->brush.supportwateralpha = true;
4955 // we don't need the compressed pvs data anymore
4956 if (mod->brushq1.data_compressedpvs)
4957 Mem_Free(mod->brushq1.data_compressedpvs);
4958 mod->brushq1.data_compressedpvs = NULL;
4959 mod->brushq1.num_compressedpvs = 0;
4961 // the MakePortals code works fine on the q2bsp data as well
4962 if (mod_bsp_portalize.integer && cls.state != ca_dedicated)
4963 Mod_BSP_MakePortals();
4965 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
4968 if (loadmodel->brush.numsubmodels)
4969 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
4971 totalstylesurfaces = 0;
4973 for (i = 0;i < mod->brush.numsubmodels;i++)
4975 memset(stylecounts, 0, sizeof(stylecounts));
4976 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4978 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4979 for (j = 0;j < MAXLIGHTMAPS;j++)
4980 stylecounts[surface->lightmapinfo->styles[j]]++;
4982 for (k = 0;k < 255;k++)
4986 totalstylesurfaces += stylecounts[k];
4989 // bones_was_here: using a separate allocation for model_brush_lightstyleinfo_t
4990 // because on a 64-bit machine it no longer has the same alignment requirement as int.
4991 lsidatapointer = Mem_AllocType(mod->mempool, model_brush_lightstyleinfo_t, totalstyles * sizeof(model_brush_lightstyleinfo_t));
4992 datapointer = Mem_AllocType(mod->mempool, int, mod->num_surfaces * sizeof(int) + totalstylesurfaces * sizeof(int));
4993 mod->modelsurfaces_sorted = datapointer; datapointer += mod->num_surfaces;
4994 // set up the world model, then on each submodel copy from the world model
4995 // and set up the submodel with the respective model info.
4997 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4999 mnode_t *rootnode = NULL;
5000 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
5004 // duplicate the basic information
5005 dpsnprintf(name, sizeof(name), "*%i", i);
5006 mod = Mod_FindName(name, loadmodel->name);
5007 // copy the base model to this one
5009 // rename the clone back to its proper name
5010 dp_strlcpy(mod->name, name, sizeof(mod->name));
5011 mod->brush.parentmodel = loadmodel;
5012 // textures and memory belong to the main model
5013 mod->texturepool = NULL;
5014 mod->mempool = NULL;
5015 mod->brush.GetPVS = NULL;
5016 mod->brush.FatPVS = NULL;
5017 mod->brush.BoxTouchingPVS = NULL;
5018 mod->brush.BoxTouchingLeafPVS = NULL;
5019 mod->brush.BoxTouchingVisibleLeafs = NULL;
5020 mod->brush.FindBoxClusters = NULL;
5021 mod->brush.LightPoint = NULL;
5022 mod->brush.AmbientSoundLevelsForPoint = NULL;
5024 mod->brush.submodel = i;
5025 if (loadmodel->brush.submodels)
5026 loadmodel->brush.submodels[i] = mod;
5028 bm = &mod->brushq1.submodels[i];
5030 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5031 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5033 mod->submodelsurfaces_start = bm->firstface;
5034 mod->submodelsurfaces_end = bm->firstface + bm->numfaces;
5036 // set node/leaf parents for this submodel
5037 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5038 // (this happens in base3.bsp)
5039 if (bm->headnode[0] >= 0)
5040 rootnode = mod->brush.data_nodes + bm->headnode[0];
5042 rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5043 Mod_BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5045 // make the model surface list (used by shadowing/lighting)
5046 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5047 if (firstbrush <= lastbrush)
5049 mod->firstmodelbrush = firstbrush;
5050 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5054 mod->firstmodelbrush = 0;
5055 mod->nummodelbrushes = 0;
5058 VectorCopy(bm->mins, mod->normalmins);
5059 VectorCopy(bm->maxs, mod->normalmaxs);
5060 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5061 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5062 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5063 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5064 modelradius = modelyawradius + modelradius * modelradius;
5065 modelyawradius = sqrt(modelyawradius);
5066 modelradius = sqrt(modelradius);
5067 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5068 mod->yawmins[2] = mod->normalmins[2];
5069 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
5070 mod->yawmaxs[2] = mod->normalmaxs[2];
5071 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5072 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5073 mod->radius = modelradius;
5074 mod->radius2 = modelradius * modelradius;
5076 Mod_SetDrawSkyAndWater(mod);
5078 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5079 if (mod->submodelsurfaces_start < mod->submodelsurfaces_end)
5081 // build lightstyle update chains
5082 // (used to rapidly mark lightmapupdateflags on many surfaces
5083 // when d_lightstylevalue changes)
5084 memset(stylecounts, 0, sizeof(stylecounts));
5085 for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
5086 for (j = 0;j < MAXLIGHTMAPS;j++)
5087 stylecounts[mod->data_surfaces[k].lightmapinfo->styles[j]]++;
5088 mod->brushq1.num_lightstyles = 0;
5089 for (k = 0;k < 255;k++)
5093 styleinfo[mod->brushq1.num_lightstyles].style = k;
5094 styleinfo[mod->brushq1.num_lightstyles].value = 0;
5095 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5096 styleinfo[mod->brushq1.num_lightstyles].surfacelist = datapointer;datapointer += stylecounts[k];
5097 remapstyles[k] = mod->brushq1.num_lightstyles;
5098 mod->brushq1.num_lightstyles++;
5101 for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
5103 surface = mod->data_surfaces + k;
5104 for (j = 0;j < MAXLIGHTMAPS;j++)
5106 if (surface->lightmapinfo->styles[j] != 255)
5108 int r = remapstyles[surface->lightmapinfo->styles[j]];
5109 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = k;
5113 mod->brushq1.data_lightstyleinfo = lsidatapointer;lsidatapointer += mod->brushq1.num_lightstyles;
5114 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5118 Con_Printf(CON_WARN "warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5120 //mod->brushq1.num_visleafs = bm->visleafs;
5122 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5123 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5125 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5126 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5128 // generate VBOs and other shared data before cloning submodels
5134 // make the model surface list (used by shadowing/lighting)
5135 Mod_MakeSortedSurfaces(loadmodel);
5137 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);
5140 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents);
5141 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents);
5143 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5146 char key[128], value[MAX_INPUTLINE];
5148 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5149 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5150 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5153 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5154 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5155 loadmodel->brush.entities[l->filelen] = 0;
5156 data = loadmodel->brush.entities;
5157 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5158 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5159 loadmodel->brushq3.deluxemapping = false;
5160 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5164 if (!COM_ParseToken_Simple(&data, false, false, true))
5166 if (com_token[0] == '}')
5167 break; // end of worldspawn
5168 if (com_token[0] == '_')
5169 dp_strlcpy(key, com_token + 1, sizeof(key));
5171 dp_strlcpy(key, com_token, sizeof(key));
5172 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5173 key[strlen(key)-1] = 0;
5174 if (!COM_ParseToken_Simple(&data, false, false, true))
5176 dp_strlcpy(value, com_token, sizeof(value));
5177 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5179 #if _MSC_VER >= 1400
5180 #define sscanf sscanf_s
5183 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5184 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5186 VectorSet(v, 64, 64, 128);
5187 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5188 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]);
5189 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5190 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5193 else if (!strcmp("deluxeMaps", key))
5195 if (!strcmp(com_token, "1"))
5197 loadmodel->brushq3.deluxemapping = true;
5198 loadmodel->brushq3.deluxemapping_modelspace = true;
5200 else if (!strcmp(com_token, "2"))
5202 loadmodel->brushq3.deluxemapping = true;
5203 loadmodel->brushq3.deluxemapping_modelspace = false;
5210 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5216 in = (q3dtexture_t *)(mod_base + l->fileofs);
5217 if (l->filelen % sizeof(*in))
5218 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5219 count = l->filelen / sizeof(*in);
5220 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5222 loadmodel->data_textures = out;
5223 loadmodel->num_textures = count;
5224 loadmodel->num_texturesperskin = loadmodel->num_textures;
5226 for (i = 0;i < count;i++)
5228 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5229 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5230 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
5231 // restore the surfaceflags and supercontents
5232 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5233 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5237 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5243 in = (q3dplane_t *)(mod_base + l->fileofs);
5244 if (l->filelen % sizeof(*in))
5245 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5246 count = l->filelen / sizeof(*in);
5247 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5249 loadmodel->brush.data_planes = out;
5250 loadmodel->brush.num_planes = count;
5252 for (i = 0;i < count;i++, in++, out++)
5254 out->normal[0] = LittleFloat(in->normal[0]);
5255 out->normal[1] = LittleFloat(in->normal[1]);
5256 out->normal[2] = LittleFloat(in->normal[2]);
5257 out->dist = LittleFloat(in->dist);
5262 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5265 q3mbrushside_t *out;
5268 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5269 if (l->filelen % sizeof(*in))
5270 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5271 count = l->filelen / sizeof(*in);
5272 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5274 loadmodel->brush.data_brushsides = out;
5275 loadmodel->brush.num_brushsides = count;
5277 for (i = 0;i < count;i++, in++, out++)
5279 n = LittleLong(in->planeindex);
5280 if (n < 0 || n >= loadmodel->brush.num_planes)
5281 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5282 out->plane = loadmodel->brush.data_planes + n;
5283 n = LittleLong(in->textureindex);
5284 if (n < 0 || n >= loadmodel->num_textures)
5285 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5286 out->texture = loadmodel->data_textures + n;
5290 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5292 q3dbrushside_ig_t *in;
5293 q3mbrushside_t *out;
5296 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5297 if (l->filelen % sizeof(*in))
5298 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5299 count = l->filelen / sizeof(*in);
5300 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5302 loadmodel->brush.data_brushsides = out;
5303 loadmodel->brush.num_brushsides = count;
5305 for (i = 0;i < count;i++, in++, out++)
5307 n = LittleLong(in->planeindex);
5308 if (n < 0 || n >= loadmodel->brush.num_planes)
5309 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5310 out->plane = loadmodel->brush.data_planes + n;
5311 n = LittleLong(in->textureindex);
5312 if (n < 0 || n >= loadmodel->num_textures)
5313 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5314 out->texture = loadmodel->data_textures + n;
5318 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5322 int i, j, n, c, count, maxplanes, q3surfaceflags;
5323 colplanef_t *planes;
5325 in = (q3dbrush_t *)(mod_base + l->fileofs);
5326 if (l->filelen % sizeof(*in))
5327 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5328 count = l->filelen / sizeof(*in);
5329 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5331 loadmodel->brush.data_brushes = out;
5332 loadmodel->brush.num_brushes = count;
5337 for (i = 0;i < count;i++, in++, out++)
5339 n = LittleLong(in->firstbrushside);
5340 c = LittleLong(in->numbrushsides);
5341 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5342 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5343 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5344 out->numbrushsides = c;
5345 n = LittleLong(in->textureindex);
5346 if (n < 0 || n >= loadmodel->num_textures)
5347 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5348 out->texture = loadmodel->data_textures + n;
5350 // make a list of mplane_t structs to construct a colbrush from
5351 if (maxplanes < out->numbrushsides)
5353 maxplanes = out->numbrushsides;
5356 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5359 for (j = 0;j < out->numbrushsides;j++)
5361 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5362 planes[j].dist = out->firstbrushside[j].plane->dist;
5363 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5364 planes[j].texture = out->firstbrushside[j].texture;
5365 q3surfaceflags |= planes[j].q3surfaceflags;
5367 // make the colbrush from the planes
5368 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5370 // this whole loop can take a while (e.g. on redstarrepublic4)
5371 CL_KeepaliveMessage(false);
5377 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5383 in = (q3deffect_t *)(mod_base + l->fileofs);
5384 if (l->filelen % sizeof(*in))
5385 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5386 count = l->filelen / sizeof(*in);
5387 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5389 loadmodel->brushq3.data_effects = out;
5390 loadmodel->brushq3.num_effects = count;
5392 for (i = 0;i < count;i++, in++, out++)
5394 dp_strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5395 n = LittleLong(in->brushindex);
5396 if (n >= loadmodel->brush.num_brushes)
5398 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5401 out->brushindex = n;
5402 out->unknown = LittleLong(in->unknown);
5406 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5411 in = (q3dvertex_t *)(mod_base + l->fileofs);
5412 if (l->filelen % sizeof(*in))
5413 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5414 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5415 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5416 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5417 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5418 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5419 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5421 for (i = 0;i < count;i++, in++)
5423 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5424 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5425 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5426 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5427 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5428 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5429 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5430 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5431 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5432 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5433 // svector/tvector are calculated later in face loading
5434 if(mod_q3bsp_sRGBlightmaps.integer)
5436 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5437 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5438 // working like this may be odd, but matches q3map2 -gamma 2.2
5439 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5441 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5442 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5443 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5444 // we fix the brightness consistently via lightmapscale
5448 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5449 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5450 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5455 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5457 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5458 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5459 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5463 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5464 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5465 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5468 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5469 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5470 loadmodel->lit = true;
5474 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5480 in = (int *)(mod_base + l->fileofs);
5481 if (l->filelen % sizeof(int[3]))
5482 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5483 count = l->filelen / sizeof(*in);
5485 if(!loadmodel->brushq3.num_vertices)
5488 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5489 loadmodel->brushq3.num_triangles = 0;
5493 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5494 loadmodel->brushq3.num_triangles = count / 3;
5495 loadmodel->brushq3.data_element3i = out;
5497 for (i = 0;i < count;i++, in++, out++)
5499 *out = LittleLong(*in);
5500 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5502 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5508 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5510 q3dlightmap_t *input_pointer;
5528 int mergedrowsxcolumns;
5533 unsigned char *mergedpixels;
5534 unsigned char *mergeddeluxepixels;
5535 unsigned char *mergebuf;
5536 char mapname[MAX_QPATH];
5538 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5541 // defaults for q3bsp
5548 loadmodel->brushq3.lightmapsize = 128;
5550 if (cls.state == ca_dedicated)
5553 if(mod_q3bsp_nolightmaps.integer)
5559 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5560 if (developer_loading.integer)
5561 Con_Printf("Using internal lightmaps\n");
5562 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5563 if (l->filelen % sizeof(*input_pointer))
5564 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5565 count = l->filelen / sizeof(*input_pointer);
5566 for(i = 0; i < count; ++i)
5567 inpixels[i] = input_pointer[i].rgb;
5571 // no internal lightmaps
5572 // try external lightmaps
5573 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5574 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5578 Con_Printf("Using external lightmaps\n");
5580 // using EXTERNAL lightmaps instead
5581 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5582 Con_Printf("Mod_Q3BSP_LoadLightmaps: irregularly sized external lightmap in %s",loadmodel->name);
5591 for(count = 1; ; ++count)
5593 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5594 if(!inpixels[count])
5595 break; // we got all of them
5596 if(image_width != size || image_height != size)
5598 Mem_Free(inpixels[count]);
5599 inpixels[count] = NULL;
5600 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);
5606 loadmodel->brushq3.lightmapsize = size;
5607 loadmodel->brushq3.num_originallightmaps = count;
5609 // now check the surfaces to see if any of them index an odd numbered
5610 // lightmap, if so this is not a deluxemapped bsp file
5612 // also check what lightmaps are actually used, because q3map2 sometimes
5613 // (always?) makes an unused one at the end, which
5614 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5615 // reason when only one lightmap is used, which can throw off the
5616 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5617 // to see if the second lightmap is blank, if so it is not deluxemapped.
5618 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5619 // in Mod_Q3BSP_LoadEntities was failed
5620 if (!loadmodel->brushq3.deluxemapping)
5622 loadmodel->brushq3.deluxemapping = !(count & 1);
5623 loadmodel->brushq3.deluxemapping_modelspace = true;
5625 if (loadmodel->brushq3.deluxemapping)
5627 int facecount = faceslump->filelen / sizeof(q3dface_t);
5628 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5629 for (i = 0;i < facecount;i++)
5631 j = LittleLong(faces[i].lightmapindex);
5634 endlightmap = max(endlightmap, j + 1);
5635 if ((j & 1) || j + 1 >= count)
5637 loadmodel->brushq3.deluxemapping = false;
5644 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5645 // reason when only one lightmap is used, which can throw off the
5646 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5647 // to see if the second lightmap is blank, if so it is not deluxemapped.
5649 // further research has shown q3map2 sometimes creates a deluxemap and two
5650 // blank lightmaps, which must be handled properly as well
5651 if (endlightmap == 1 && count > 1)
5654 for (i = 0;i < size*size;i++)
5656 if (c[bytesperpixel*i + rgbmap[0]])
5658 if (c[bytesperpixel*i + rgbmap[1]])
5660 if (c[bytesperpixel*i + rgbmap[2]])
5665 // all pixels in the unused lightmap were black...
5666 loadmodel->brushq3.deluxemapping = false;
5671 Con_Printf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5673 // figure out what the most reasonable merge power is within limits
5675 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5676 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5678 // figure out how big the merged texture has to be
5679 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5680 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5681 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5683 mergedwidth = mergegoal;
5684 mergedheight = mergegoal;
5685 // choose non-square size (2x1 aspect) if only half the space is used;
5686 // this really only happens when the entire set fits in one texture, if
5687 // there are multiple textures, we don't worry about shrinking the last
5688 // one to fit, because the driver prefers the same texture size on
5689 // consecutive draw calls...
5690 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5693 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5694 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5695 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5696 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5697 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5698 loadmodel->brushq3.num_lightmapmergedheightpower++;
5699 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5701 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5702 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5703 powerxy = powerx+powery;
5704 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5706 mergedcolumns = 1 << powerx;
5707 mergedrows = 1 << powery;
5708 mergedrowsxcolumns = 1 << powerxy;
5710 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5711 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5712 if (loadmodel->brushq3.deluxemapping)
5713 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5715 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5716 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5717 for (i = 0;i < count;i++)
5719 // figure out which merged lightmap texture this fits into
5720 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5721 lightmapindex = i >> powerdxy;
5723 // choose the destination address
5724 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5725 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5726 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5727 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);
5729 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5730 for (j = 0;j < size;j++)
5731 for (k = 0;k < size;k++)
5733 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5734 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5735 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5736 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5739 // upload texture if this was the last tile being written to the texture
5740 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5742 if (loadmodel->brushq3.deluxemapping && (i & 1))
5743 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);
5746 if(mod_q3bsp_sRGBlightmaps.integer)
5749 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5751 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5752 // we fix the brightness consistently via lightmapscale
5755 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5756 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);
5760 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5761 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5762 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);
5768 if (mergeddeluxepixels)
5769 Mem_Free(mergeddeluxepixels);
5770 Mem_Free(mergedpixels);
5773 for(i = 0; i < count; ++i)
5774 Mem_Free(inpixels[i]);
5778 typedef struct patchtess_s
5782 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5785 float *originalvertex3f;
5788 #define PATCHTESS_SAME_LODGROUP(a,b) \
5790 (a).lodgroup[0] == (b).lodgroup[0] && \
5791 (a).lodgroup[1] == (b).lodgroup[1] && \
5792 (a).lodgroup[2] == (b).lodgroup[2] && \
5793 (a).lodgroup[3] == (b).lodgroup[3] && \
5794 (a).lodgroup[4] == (b).lodgroup[4] && \
5795 (a).lodgroup[5] == (b).lodgroup[5] \
5798 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5800 q3dface_t *in, *oldin;
5801 msurface_t *out, *oldout;
5802 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;
5803 float lightmaptcbase[2], lightmaptcscale[2];
5804 //int *originalelement3i;
5805 float *originalvertex3f;
5806 //float *originalsvector3f;
5807 //float *originaltvector3f;
5808 float *originalnormal3f;
5809 float *originalcolor4f;
5810 float *originaltexcoordtexture2f;
5811 float *originaltexcoordlightmap2f;
5812 float *surfacecollisionvertex3f;
5813 int *surfacecollisionelement3i;
5815 patchtess_t *patchtess = NULL;
5816 int patchtesscount = 0;
5819 in = (q3dface_t *)(mod_base + l->fileofs);
5820 if (l->filelen % sizeof(*in))
5821 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5822 count = l->filelen / sizeof(*in);
5823 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5825 loadmodel->data_surfaces = out;
5826 loadmodel->num_surfaces = count;
5829 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5837 for (;i < count;i++, in++, out++)
5839 // check face type first
5840 type = LittleLong(in->type);
5841 if (type != Q3FACETYPE_FLAT
5842 && type != Q3FACETYPE_PATCH
5843 && type != Q3FACETYPE_MESH
5844 && type != Q3FACETYPE_FLARE)
5846 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5850 n = LittleLong(in->textureindex);
5851 if (n < 0 || n >= loadmodel->num_textures)
5853 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5856 out->texture = loadmodel->data_textures + n;
5857 n = LittleLong(in->effectindex);
5858 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5860 if (developer_extra.integer)
5861 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5867 out->effect = loadmodel->brushq3.data_effects + n;
5869 if (cls.state != ca_dedicated)
5871 out->lightmaptexture = NULL;
5872 out->deluxemaptexture = r_texture_blanknormalmap;
5873 n = LittleLong(in->lightmapindex);
5876 else if (n >= loadmodel->brushq3.num_originallightmaps)
5878 if(loadmodel->brushq3.num_originallightmaps != 0)
5879 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5884 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5885 if (loadmodel->brushq3.deluxemapping)
5886 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5887 loadmodel->lit = true;
5891 firstvertex = LittleLong(in->firstvertex);
5892 numvertices = LittleLong(in->numvertices);
5893 firstelement = LittleLong(in->firstelement);
5894 numtriangles = LittleLong(in->numelements) / 3;
5895 if (numtriangles * 3 != LittleLong(in->numelements))
5897 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));
5900 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5902 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);
5905 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5907 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);
5912 case Q3FACETYPE_FLAT:
5913 case Q3FACETYPE_MESH:
5914 // no processing necessary
5916 case Q3FACETYPE_PATCH:
5917 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5918 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5919 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)))
5921 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5924 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5926 // convert patch to Q3FACETYPE_MESH
5927 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5928 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5929 // bound to user settings
5930 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5931 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5932 // bound to sanity settings
5933 xtess = bound(0, xtess, 1024);
5934 ytess = bound(0, ytess, 1024);
5936 // lower quality collision patches! Same procedure as before, but different cvars
5937 // convert patch to Q3FACETYPE_MESH
5938 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, mod_q3bsp_curves_subdivisions_tolerance.value);
5939 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, mod_q3bsp_curves_subdivisions_tolerance.value);
5940 // bound to user settings
5941 cxtess = bound(mod_q3bsp_curves_subdivisions_mintess.integer, cxtess, mod_q3bsp_curves_subdivisions_maxtess.integer);
5942 cytess = bound(mod_q3bsp_curves_subdivisions_mintess.integer, cytess, mod_q3bsp_curves_subdivisions_maxtess.integer);
5943 // bound to sanity settings
5944 cxtess = bound(0, cxtess, 1024);
5945 cytess = bound(0, cytess, 1024);
5947 // store it for the LOD grouping step
5948 patchtess[patchtesscount].info.xsize = patchsize[0];
5949 patchtess[patchtesscount].info.ysize = patchsize[1];
5950 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5951 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5952 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5953 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5955 patchtess[patchtesscount].surface_id = i;
5956 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5957 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5958 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5959 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5960 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5961 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5962 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5965 case Q3FACETYPE_FLARE:
5966 if (developer_extra.integer)
5967 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5971 out->num_vertices = numvertices;
5972 out->num_triangles = numtriangles;
5973 meshvertices += out->num_vertices;
5974 meshtriangles += out->num_triangles;
5977 // Fix patches tesselations so that they make no seams
5981 for(i = 0; i < patchtesscount; ++i)
5983 for(j = i+1; j < patchtesscount; ++j)
5985 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5988 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5995 // Calculate resulting number of triangles
5996 collisionvertices = 0;
5997 collisiontriangles = 0;
5998 for(i = 0; i < patchtesscount; ++i)
6000 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
6001 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
6002 numvertices = finalwidth * finalheight;
6003 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6005 oldout[patchtess[i].surface_id].num_vertices = numvertices;
6006 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
6007 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
6008 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
6010 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
6011 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
6012 numvertices = finalwidth * finalheight;
6013 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6015 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6016 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6017 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6018 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6024 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true);
6025 if (collisiontriangles)
6027 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6028 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6032 collisionvertices = 0;
6033 collisiontriangles = 0;
6034 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6036 if (out->num_vertices < 3 || out->num_triangles < 1)
6039 type = LittleLong(in->type);
6040 firstvertex = LittleLong(in->firstvertex);
6041 firstelement = LittleLong(in->firstelement);
6042 out->num_firstvertex = meshvertices;
6043 out->num_firsttriangle = meshtriangles;
6044 out->num_firstcollisiontriangle = collisiontriangles;
6047 case Q3FACETYPE_FLAT:
6048 case Q3FACETYPE_MESH:
6049 // no processing necessary, except for lightmap merging
6050 for (j = 0;j < out->num_vertices;j++)
6052 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6053 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6054 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6055 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6056 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6057 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6058 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6059 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6060 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6061 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6062 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6063 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6064 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6065 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6067 for (j = 0;j < out->num_triangles*3;j++)
6068 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6070 case Q3FACETYPE_PATCH:
6071 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6072 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6073 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6074 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6075 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6076 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6077 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6079 xtess = ytess = cxtess = cytess = -1;
6080 for(j = 0; j < patchtesscount; ++j)
6081 if(patchtess[j].surface_id == i)
6083 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6084 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6085 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6086 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6091 Con_Printf(CON_ERROR "ERROR: patch %d isn't preprocessed?!?\n", i);
6092 xtess = ytess = cxtess = cytess = 0;
6095 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6096 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6097 finalvertices = finalwidth * finalheight;
6098 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6099 type = Q3FACETYPE_MESH;
6100 // generate geometry
6101 // (note: normals are skipped because they get recalculated)
6102 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6103 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6104 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6105 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6106 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6107 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6109 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);
6111 if (developer_extra.integer)
6113 if (out->num_triangles < finaltriangles)
6114 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);
6116 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);
6118 // q3map does not put in collision brushes for curves... ugh
6119 // build the lower quality collision geometry
6120 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6121 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6122 finalvertices = finalwidth * finalheight;
6123 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6125 // store collision geometry for BIH collision tree
6126 out->num_collisionvertices = finalvertices;
6127 out->num_collisiontriangles = finaltriangles;
6128 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6129 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6130 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6131 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6132 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6133 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6135 if (developer_extra.integer)
6136 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);
6138 collisionvertices += finalvertices;
6139 collisiontriangles += out->num_collisiontriangles;
6144 meshvertices += out->num_vertices;
6145 meshtriangles += out->num_triangles;
6146 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6147 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)
6149 if (invalidelements)
6151 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);
6152 for (j = 0;j < out->num_triangles * 3;j++)
6154 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6155 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)
6156 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6160 // calculate a bounding box
6161 VectorClear(out->mins);
6162 VectorClear(out->maxs);
6163 if (out->num_vertices)
6165 if (cls.state != ca_dedicated && out->lightmaptexture)
6167 // figure out which part of the merged lightmap this fits into
6168 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6169 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6170 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6171 lightmapindex &= mergewidth * mergeheight - 1;
6172 lightmaptcscale[0] = 1.0f / mergewidth;
6173 lightmaptcscale[1] = 1.0f / mergeheight;
6174 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6175 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6176 // modify the lightmap texcoords to match this region of the merged lightmap
6177 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6179 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6180 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6183 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6184 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6185 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6187 out->mins[0] = min(out->mins[0], v[0]);
6188 out->maxs[0] = max(out->maxs[0], v[0]);
6189 out->mins[1] = min(out->mins[1], v[1]);
6190 out->maxs[1] = max(out->maxs[1], v[1]);
6191 out->mins[2] = min(out->mins[2], v[2]);
6192 out->maxs[2] = max(out->maxs[2], v[2]);
6194 out->mins[0] -= 1.0f;
6195 out->mins[1] -= 1.0f;
6196 out->mins[2] -= 1.0f;
6197 out->maxs[0] += 1.0f;
6198 out->maxs[1] += 1.0f;
6199 out->maxs[2] += 1.0f;
6201 // set lightmap styles for consistency with q1bsp
6202 //out->lightmapinfo->styles[0] = 0;
6203 //out->lightmapinfo->styles[1] = 255;
6204 //out->lightmapinfo->styles[2] = 255;
6205 //out->lightmapinfo->styles[3] = 255;
6210 for (;i < count;i++, out++)
6212 if(out->num_vertices && out->num_triangles)
6214 if(out->num_vertices == 0)
6216 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6217 if(out->num_triangles == 0)
6218 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6220 else if(out->num_triangles == 0)
6221 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)",
6222 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6223 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6224 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6227 // for per pixel lighting
6228 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);
6230 // generate ushort elements array if possible
6231 if (loadmodel->surfmesh.data_element3s)
6232 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6233 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6235 // free the no longer needed vertex data
6236 loadmodel->brushq3.num_vertices = 0;
6237 if (loadmodel->brushq3.data_vertex3f)
6238 Mem_Free(loadmodel->brushq3.data_vertex3f);
6239 loadmodel->brushq3.data_vertex3f = NULL;
6240 loadmodel->brushq3.data_normal3f = NULL;
6241 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6242 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6243 loadmodel->brushq3.data_color4f = NULL;
6244 // free the no longer needed triangle data
6245 loadmodel->brushq3.num_triangles = 0;
6246 if (loadmodel->brushq3.data_element3i)
6247 Mem_Free(loadmodel->brushq3.data_element3i);
6248 loadmodel->brushq3.data_element3i = NULL;
6251 Mem_Free(patchtess);
6254 static void Mod_Q3BSP_LoadModels(lump_t *l)
6258 int i, j, n, c, count;
6260 in = (q3dmodel_t *)(mod_base + l->fileofs);
6261 if (l->filelen % sizeof(*in))
6262 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6263 count = l->filelen / sizeof(*in);
6264 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6266 loadmodel->brushq3.data_models = out;
6267 loadmodel->brushq3.num_models = count;
6269 for (i = 0;i < count;i++, in++, out++)
6271 for (j = 0;j < 3;j++)
6273 out->mins[j] = LittleFloat(in->mins[j]);
6274 out->maxs[j] = LittleFloat(in->maxs[j]);
6276 n = LittleLong(in->firstface);
6277 c = LittleLong(in->numfaces);
6278 if (n < 0 || n + c > loadmodel->num_surfaces)
6279 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6282 n = LittleLong(in->firstbrush);
6283 c = LittleLong(in->numbrushes);
6284 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6285 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6286 out->firstbrush = n;
6287 out->numbrushes = c;
6291 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6297 in = (int *)(mod_base + l->fileofs);
6298 if (l->filelen % sizeof(*in))
6299 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6300 count = l->filelen / sizeof(*in);
6301 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6303 loadmodel->brush.data_leafbrushes = out;
6304 loadmodel->brush.num_leafbrushes = count;
6306 for (i = 0;i < count;i++, in++, out++)
6308 n = LittleLong(*in);
6309 if (n < 0 || n >= loadmodel->brush.num_brushes)
6310 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6315 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6321 in = (int *)(mod_base + l->fileofs);
6322 if (l->filelen % sizeof(*in))
6323 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6324 count = l->filelen / sizeof(*in);
6325 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6327 loadmodel->brush.data_leafsurfaces = out;
6328 loadmodel->brush.num_leafsurfaces = count;
6330 for (i = 0;i < count;i++, in++, out++)
6332 n = LittleLong(*in);
6333 if (n < 0 || n >= loadmodel->num_surfaces)
6334 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6339 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6343 int i, j, n, c, count;
6345 in = (q3dleaf_t *)(mod_base + l->fileofs);
6346 if (l->filelen % sizeof(*in))
6347 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6348 count = l->filelen / sizeof(*in);
6349 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6351 loadmodel->brush.data_leafs = out;
6352 loadmodel->brush.num_leafs = count;
6354 for (i = 0;i < count;i++, in++, out++)
6358 out->clusterindex = LittleLong(in->clusterindex);
6359 out->areaindex = LittleLong(in->areaindex);
6360 for (j = 0;j < 3;j++)
6362 // yes the mins/maxs are ints
6363 out->mins[j] = LittleLong(in->mins[j]) - 1;
6364 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6366 n = LittleLong(in->firstleafface);
6367 c = LittleLong(in->numleaffaces);
6368 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6369 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6370 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6371 out->numleafsurfaces = c;
6372 n = LittleLong(in->firstleafbrush);
6373 c = LittleLong(in->numleafbrushes);
6374 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6375 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6376 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6377 out->numleafbrushes = c;
6381 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6387 in = (q3dnode_t *)(mod_base + l->fileofs);
6388 if (l->filelen % sizeof(*in))
6389 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6390 count = l->filelen / sizeof(*in);
6392 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6393 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6395 loadmodel->brush.data_nodes = out;
6396 loadmodel->brush.num_nodes = count;
6398 for (i = 0;i < count;i++, in++, out++)
6401 n = LittleLong(in->planeindex);
6402 if (n < 0 || n >= loadmodel->brush.num_planes)
6403 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6404 out->plane = loadmodel->brush.data_planes + n;
6405 for (j = 0;j < 2;j++)
6407 n = LittleLong(in->childrenindex[j]);
6410 if (n >= loadmodel->brush.num_nodes)
6411 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6412 out->children[j] = loadmodel->brush.data_nodes + n;
6417 if (n >= loadmodel->brush.num_leafs)
6418 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6419 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6422 for (j = 0;j < 3;j++)
6424 // yes the mins/maxs are ints
6425 out->mins[j] = LittleLong(in->mins[j]) - 1;
6426 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6430 // set the parent pointers
6431 Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6434 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6437 q3dlightgrid_t *out;
6441 unsigned char *texturergba, *texturelayer[3], *texturepadding[2];
6442 double lightgridmatrix[4][4];
6444 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6445 if (l->filelen % sizeof(*in))
6446 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6447 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6448 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6449 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6450 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6451 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6452 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6453 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6454 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6455 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6456 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6457 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6458 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6459 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6460 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]);
6461 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]);
6463 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6466 if (l->filelen < count * (int)sizeof(*in))
6468 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]);
6469 return; // ignore the grid if we cannot understand it
6471 if (l->filelen != count * (int)sizeof(*in))
6472 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);
6473 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6474 loadmodel->brushq3.data_lightgrid = out;
6475 loadmodel->brushq3.num_lightgrid = count;
6476 // no swapping or validation necessary
6477 memcpy(out, in, count * (int)sizeof(*out));
6479 if(mod_q3bsp_sRGBlightmaps.integer)
6481 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6483 // we fix the brightness consistently via lightmapscale
6487 for(i = 0; i < count; ++i)
6489 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6490 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6491 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6492 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6493 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6494 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6500 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6502 for(i = 0; i < count; ++i)
6504 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6505 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6506 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6507 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6508 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6509 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6518 if (mod_q3bsp_lightgrid_texture.integer)
6520 // build a texture to hold the data for per-pixel sampling
6521 // this has 3 different kinds of data stacked in it:
6523 // bent-normal light color
6524 // bent-normal light dir
6526 texturesize[0] = loadmodel->brushq3.num_lightgrid_isize[0];
6527 texturesize[1] = loadmodel->brushq3.num_lightgrid_isize[1];
6528 texturesize[2] = (loadmodel->brushq3.num_lightgrid_isize[2] + 2) * 3;
6529 texturergba = (unsigned char*)Mem_Alloc(loadmodel->mempool, texturesize[0] * texturesize[1] * texturesize[2] * sizeof(char[4]));
6530 texturelayer[0] = texturergba + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6531 texturelayer[1] = texturelayer[0] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6532 texturelayer[2] = texturelayer[1] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6533 // the light dir layer needs padding above/below it that is a neutral unsigned normal (127,127,127,255)
6534 texturepadding[0] = texturelayer[2] - loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6535 texturepadding[1] = texturelayer[2] + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2] * 4;
6536 for (i = 0; i < texturesize[0] * texturesize[1]; i++)
6538 texturepadding[0][i * 4] = texturepadding[1][i * 4] = 127;
6539 texturepadding[0][i * 4 + 1] = texturepadding[1][i * 4 + 1] = 127;
6540 texturepadding[0][i * 4 + 2] = texturepadding[1][i * 4 + 2] = 127;
6541 texturepadding[0][i * 4 + 3] = texturepadding[1][i * 4 + 3] = 255;
6543 for (i = 0; i < count; i++)
6545 texturelayer[0][i * 4 + 0] = out[i].ambientrgb[0];
6546 texturelayer[0][i * 4 + 1] = out[i].ambientrgb[1];
6547 texturelayer[0][i * 4 + 2] = out[i].ambientrgb[2];
6548 texturelayer[0][i * 4 + 3] = 255;
6549 texturelayer[1][i * 4 + 0] = out[i].diffusergb[0];
6550 texturelayer[1][i * 4 + 1] = out[i].diffusergb[1];
6551 texturelayer[1][i * 4 + 2] = out[i].diffusergb[2];
6552 texturelayer[1][i * 4 + 3] = 255;
6553 // this uses the mod_md3_sin table because the values are
6554 // already in the 0-255 range, the 64+ bias fetches a cosine
6555 // instead of a sine value
6556 texturelayer[2][i * 4 + 0] = (char)((mod_md3_sin[64 + out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6557 texturelayer[2][i * 4 + 1] = (char)((mod_md3_sin[out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6558 texturelayer[2][i * 4 + 2] = (char)((mod_md3_sin[64 + out[i].diffusepitch]) * 127 + 127);
6559 texturelayer[2][i * 4 + 3] = 255;
6564 for (z = 0; z < loadmodel->brushq3.num_lightgrid_isize[2]; z++)
6566 for (y = 0; y < loadmodel->brushq3.num_lightgrid_isize[1]; y++)
6568 for (x = 0; x < loadmodel->brushq3.num_lightgrid_isize[0]; x++)
6570 i = (z * texturesize[1] + y) * texturesize[0] + x;
6571 texturelayer[0][i * 4 + 0] = x * 256 / loadmodel->brushq3.num_lightgrid_isize[0];
6572 texturelayer[0][i * 4 + 1] = y * 256 / loadmodel->brushq3.num_lightgrid_isize[1];
6573 texturelayer[0][i * 4 + 2] = z * 256 / loadmodel->brushq3.num_lightgrid_isize[2];
6578 loadmodel->brushq3.lightgridtexturesize[0] = texturesize[0];
6579 loadmodel->brushq3.lightgridtexturesize[1] = texturesize[1];
6580 loadmodel->brushq3.lightgridtexturesize[2] = texturesize[2];
6581 memset(lightgridmatrix[0], 0, sizeof(lightgridmatrix));
6582 lightgridmatrix[0][0] = loadmodel->brushq3.num_lightgrid_scale[0] / texturesize[0];
6583 lightgridmatrix[1][1] = loadmodel->brushq3.num_lightgrid_scale[1] / texturesize[1];
6584 lightgridmatrix[2][2] = loadmodel->brushq3.num_lightgrid_scale[2] / texturesize[2];
6585 lightgridmatrix[0][3] = -(loadmodel->brushq3.num_lightgrid_imins[0] - 0.5f) / texturesize[0];
6586 lightgridmatrix[1][3] = -(loadmodel->brushq3.num_lightgrid_imins[1] - 0.5f) / texturesize[1];
6587 lightgridmatrix[2][3] = -(loadmodel->brushq3.num_lightgrid_imins[2] - 1.5f) / texturesize[2];
6588 lightgridmatrix[3][3] = 1;
6589 Matrix4x4_FromArrayDoubleD3D(&loadmodel->brushq3.lightgridworldtotexturematrix, lightgridmatrix);
6590 loadmodel->brushq3.lightgridtexture = R_LoadTexture3D(loadmodel->texturepool, "lightgrid", texturesize[0], texturesize[1], texturesize[2], texturergba, TEXTYPE_RGBA, TEXF_CLAMP, 0, NULL);
6591 Mem_Free(texturergba);
6596 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6601 if (l->filelen == 0)
6604 // unvised maps often have cluster indices even without pvs, so check
6605 // leafs to find real number of clusters
6606 loadmodel->brush.num_pvsclusters = 1;
6607 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6608 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6611 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6612 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6613 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6614 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6618 in = (q3dpvs_t *)(mod_base + l->fileofs);
6620 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6622 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6623 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6624 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6625 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6626 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6627 if (l->filelen < totalchains + (int)sizeof(*in))
6628 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);
6630 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6631 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6634 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6636 int i, j, k, index[3];
6637 float transformed[3], blend1, blend2, blend, stylescale = 1;
6638 q3dlightgrid_t *a, *s;
6640 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6641 // LadyHavoc: FIXME: is this true?
6642 stylescale = 1; // added while render
6643 //stylescale = r_refdef.scene.rtlightstylevalue[0];
6645 if (!model->brushq3.num_lightgrid)
6647 ambientcolor[0] = stylescale;
6648 ambientcolor[1] = stylescale;
6649 ambientcolor[2] = stylescale;
6653 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6654 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6655 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6656 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6657 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6658 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6659 index[0] = (int)floor(transformed[0]);
6660 index[1] = (int)floor(transformed[1]);
6661 index[2] = (int)floor(transformed[2]);
6662 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6664 // now lerp the values
6665 VectorClear(diffusenormal);
6666 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6667 for (k = 0;k < 2;k++)
6669 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6670 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6672 for (j = 0;j < 2;j++)
6674 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6675 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6677 for (i = 0;i < 2;i++)
6679 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6680 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6682 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6683 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6684 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6685 // this uses the mod_md3_sin table because the values are
6686 // already in the 0-255 range, the 64+ bias fetches a cosine
6687 // instead of a sine value
6688 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6689 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6690 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6691 //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)));
6696 // normalize the light direction before turning
6697 VectorNormalize(diffusenormal);
6698 //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]);
6701 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3], double endpos[3])
6704 double midf, mid[3];
6710 // find the point distances
6711 mplane_t *plane = node->plane;
6712 if (plane->type < 3)
6714 t1 = p1[plane->type] - plane->dist;
6715 t2 = p2[plane->type] - plane->dist;
6719 t1 = DotProduct (plane->normal, p1) - plane->dist;
6720 t2 = DotProduct (plane->normal, p2) - plane->dist;
6727 node = node->children[1];
6736 node = node->children[0];
6742 midf = t1 / (t1 - t2);
6743 VectorLerp(p1, midf, p2, mid);
6745 // recurse both sides, front side first
6746 // return 2 if empty is followed by solid (hit something)
6747 // do not return 2 if both are solid or both empty,
6748 // or if start is solid and end is empty
6749 // as these degenerate cases usually indicate the eye is in solid and
6750 // should see the target point anyway
6751 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid, endpos);
6754 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2, endpos);
6757 VectorCopy(mid, endpos);
6760 return ((mleaf_t *)node)->clusterindex < 0;
6763 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)
6765 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6768 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
6769 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
6773 double tracestart[3], traceend[3], traceendpos[3];
6774 VectorCopy(start, tracestart);
6775 VectorCopy(end, traceend);
6776 VectorCopy(end, traceendpos);
6777 Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend, traceendpos);
6778 return BoxesOverlap(traceendpos, traceendpos, acceptmins, acceptmaxs);
6782 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)
6785 const bih_leaf_t *leaf;
6786 const bih_node_t *node;
6787 const colbrushf_t *brush;
6790 int nodestackpos = 0;
6791 int nodestack[1024];
6793 memset(trace, 0, sizeof(*trace));
6794 trace->fraction = 1;
6795 trace->hitsupercontentsmask = hitsupercontentsmask;
6796 trace->skipsupercontentsmask = skipsupercontentsmask;
6797 trace->skipmaterialflagsmask = skipmaterialflagsmask;
6799 bih = &model->collision_bih;
6803 nodenum = bih->rootnode;
6804 nodestack[nodestackpos++] = nodenum;
6805 while (nodestackpos)
6807 nodenum = nodestack[--nodestackpos];
6808 node = bih->nodes + nodenum;
6810 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6813 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6815 axis = node->type - BIH_SPLITX;
6816 if (start[axis] >= node->frontmin)
6817 nodestack[nodestackpos++] = node->front;
6818 if (start[axis] <= node->backmax)
6819 nodestack[nodestackpos++] = node->back;
6821 else if (node->type == BIH_UNORDERED)
6823 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6825 leaf = bih->leafs + node->children[axis];
6827 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6833 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6834 Collision_TracePointBrushFloat(trace, start, brush);
6836 case BIH_COLLISIONTRIANGLE:
6837 // collision triangle - skipped because they have no volume
6839 case BIH_RENDERTRIANGLE:
6840 // render triangle - skipped because they have no volume
6848 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)
6850 const bih_leaf_t *leaf;
6851 const bih_node_t *node;
6852 const colbrushf_t *brush;
6854 const texture_t *texture;
6855 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6856 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6857 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6862 if (VectorCompare(start, end))
6864 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6868 nodenum = bih->rootnode;
6870 memset(trace, 0, sizeof(*trace));
6871 trace->fraction = 1;
6872 trace->hitsupercontentsmask = hitsupercontentsmask;
6873 trace->skipsupercontentsmask = skipsupercontentsmask;
6874 trace->skipmaterialflagsmask = skipmaterialflagsmask;
6877 nodestackline[nodestackpos][0] = start[0];
6878 nodestackline[nodestackpos][1] = start[1];
6879 nodestackline[nodestackpos][2] = start[2];
6880 nodestackline[nodestackpos][3] = end[0];
6881 nodestackline[nodestackpos][4] = end[1];
6882 nodestackline[nodestackpos][5] = end[2];
6883 nodestack[nodestackpos++] = nodenum;
6884 while (nodestackpos)
6886 nodenum = nodestack[--nodestackpos];
6887 node = bih->nodes + nodenum;
6888 VectorCopy(nodestackline[nodestackpos], nodestart);
6889 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6890 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6891 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6892 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6893 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6894 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6895 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6896 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs) && !collision_bih_fullrecursion.integer)
6898 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6900 // recurse children of the split
6901 axis = node->type - BIH_SPLITX;
6902 d1 = node->backmax - nodestart[axis];
6903 d2 = node->backmax - nodeend[axis];
6904 d3 = nodestart[axis] - node->frontmin;
6905 d4 = nodeend[axis] - node->frontmin;
6906 if (collision_bih_fullrecursion.integer)
6907 d1 = d2 = d3 = d4 = 1; // force full recursion
6908 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6910 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;
6911 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;
6912 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;
6913 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6914 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;
6915 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;
6916 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;
6917 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6918 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;
6919 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;
6920 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;
6921 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6922 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6923 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6924 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6925 case 15: /* <<<< */ break;
6928 else if (node->type == BIH_UNORDERED)
6930 // calculate sweep bounds for this node
6931 // copy node bounds into local variables
6932 VectorCopy(node->mins, nodebigmins);
6933 VectorCopy(node->maxs, nodebigmaxs);
6934 // clip line to this node bounds
6935 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); }
6936 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); }
6937 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); }
6938 // some of the line intersected the enlarged node box
6939 // calculate sweep bounds for this node
6940 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6941 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6942 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6943 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6944 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6945 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6946 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6948 leaf = bih->leafs + node->children[axis];
6949 // TODO: This is very expensive in Steel Storm. Framerate halved during even light combat.
6950 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6955 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6956 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6958 case BIH_COLLISIONTRIANGLE:
6959 if (!mod_q3bsp_curves_collisions.integer)
6961 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6962 texture = model->data_textures + leaf->textureindex;
6963 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);
6965 case BIH_RENDERTRIANGLE:
6966 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6967 texture = model->data_textures + leaf->textureindex;
6968 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);
6976 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)
6978 if (VectorCompare(start, end))
6980 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6983 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->collision_bih);
6986 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)
6989 const bih_leaf_t *leaf;
6990 const bih_node_t *node;
6991 const colbrushf_t *brush;
6993 const texture_t *texture;
6994 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6995 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6996 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6997 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6999 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
7001 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
7002 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7004 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7008 bih = &model->collision_bih;
7011 nodenum = bih->rootnode;
7013 // box trace, performed as brush trace
7014 memset(trace, 0, sizeof(*trace));
7015 trace->fraction = 1;
7016 trace->hitsupercontentsmask = hitsupercontentsmask;
7017 trace->skipsupercontentsmask = skipsupercontentsmask;
7018 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7020 // calculate tracebox-like parameters for efficient culling
7021 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7022 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7023 VectorSubtract(thisbrush_start->mins, start, startmins);
7024 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7025 VectorSubtract(thisbrush_end->mins, end, endmins);
7026 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7027 mins[0] = min(startmins[0], endmins[0]);
7028 mins[1] = min(startmins[1], endmins[1]);
7029 mins[2] = min(startmins[2], endmins[2]);
7030 maxs[0] = max(startmaxs[0], endmaxs[0]);
7031 maxs[1] = max(startmaxs[1], endmaxs[1]);
7032 maxs[2] = max(startmaxs[2], endmaxs[2]);
7035 nodestackline[nodestackpos][0] = start[0];
7036 nodestackline[nodestackpos][1] = start[1];
7037 nodestackline[nodestackpos][2] = start[2];
7038 nodestackline[nodestackpos][3] = end[0];
7039 nodestackline[nodestackpos][4] = end[1];
7040 nodestackline[nodestackpos][5] = end[2];
7041 nodestack[nodestackpos++] = nodenum;
7042 while (nodestackpos)
7044 nodenum = nodestack[--nodestackpos];
7045 node = bih->nodes + nodenum;
7046 VectorCopy(nodestackline[nodestackpos], nodestart);
7047 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7048 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7049 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7050 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7051 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7052 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7053 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7054 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7056 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7058 // recurse children of the split
7059 axis = node->type - BIH_SPLITX;
7060 d1 = node->backmax - nodestart[axis] - mins[axis];
7061 d2 = node->backmax - nodeend[axis] - mins[axis];
7062 d3 = nodestart[axis] - node->frontmin + maxs[axis];
7063 d4 = nodeend[axis] - node->frontmin + maxs[axis];
7064 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7066 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;
7067 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;
7068 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;
7069 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7070 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;
7071 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;
7072 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;
7073 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7074 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;
7075 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;
7076 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;
7077 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7078 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7079 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7080 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7081 case 15: /* <<<< */ break;
7084 else if (node->type == BIH_UNORDERED)
7086 // calculate sweep bounds for this node
7087 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7088 VectorSubtract(node->mins, maxs, nodebigmins);
7089 VectorSubtract(node->maxs, mins, nodebigmaxs);
7090 // clip line to this node bounds
7091 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); }
7092 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); }
7093 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); }
7094 // some of the line intersected the enlarged node box
7095 // calculate sweep bounds for this node
7096 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7097 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7098 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7099 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7100 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7101 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7102 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7104 leaf = bih->leafs + node->children[axis];
7105 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7110 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7111 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7113 case BIH_COLLISIONTRIANGLE:
7114 if (!mod_q3bsp_curves_collisions.integer)
7116 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7117 texture = model->data_textures + leaf->textureindex;
7118 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);
7120 case BIH_RENDERTRIANGLE:
7121 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7122 texture = model->data_textures + leaf->textureindex;
7123 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);
7131 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)
7133 colboxbrushf_t thisbrush_start, thisbrush_end;
7134 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7136 // box trace, performed as brush trace
7137 VectorAdd(start, boxmins, boxstartmins);
7138 VectorAdd(start, boxmaxs, boxstartmaxs);
7139 VectorAdd(end, boxmins, boxendmins);
7140 VectorAdd(end, boxmaxs, boxendmaxs);
7141 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7142 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7143 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7147 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7150 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0, 0);
7151 return trace.startsupercontents;
7154 qbool Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
7157 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
7158 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
7161 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)
7164 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7166 int hitsupercontents;
7167 VectorSet(end, start[0], start[1], model->normalmins[2]);
7169 memset(trace, 0, sizeof(*trace));
7170 trace->fraction = 1;
7171 trace->hitsupercontentsmask = hitsupercontentsmask;
7172 trace->skipsupercontentsmask = skipsupercontentsmask;
7173 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7175 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7176 hitsupercontents = trace->hitsupercontents;
7177 memset(trace, 0, sizeof(*trace));
7178 trace->fraction = 1;
7179 trace->hitsupercontentsmask = hitsupercontentsmask;
7180 trace->skipsupercontentsmask = skipsupercontentsmask;
7181 trace->skipmaterialflagsmask = skipmaterialflagsmask;
7182 trace->startsupercontents = hitsupercontents;
7186 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7189 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7192 VectorSet(end, start[0], start[1], model->normalmins[2]);
7193 memset(&trace, 0, sizeof(trace));
7195 trace.hitsupercontentsmask = hitsupercontentsmask;
7196 trace.skipsupercontentsmask = skipsupercontentsmask;
7197 trace.skipmaterialflagsmask = skipmaterialflagsmask;
7198 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7199 return trace.hitsupercontents;
7205 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)
7207 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->render_bih);
7211 bih_t *Mod_MakeCollisionBIH(model_t *model, qbool userendersurfaces, bih_t *out)
7219 int nummodelbrushes = model->nummodelbrushes;
7221 const int *collisionelement3i;
7222 const float *collisionvertex3f;
7223 const int *renderelement3i;
7224 const float *rendervertex3f;
7225 bih_leaf_t *bihleafs;
7226 bih_node_t *bihnodes;
7228 int *temp_leafsortscratch;
7229 const msurface_t *surface;
7230 const q3mbrush_t *brush;
7232 // find out how many BIH leaf nodes we need
7234 if (userendersurfaces)
7236 for (j = model->submodelsurfaces_start;j < model->submodelsurfaces_end;j++)
7237 bihnumleafs += model->data_surfaces[j].num_triangles;
7241 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7242 if (brush->colbrushf)
7244 for (j = model->submodelsurfaces_start;j < model->submodelsurfaces_end;j++)
7246 if (model->data_surfaces[j].texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7247 bihnumleafs += model->data_surfaces[j].num_triangles + model->data_surfaces[j].num_collisiontriangles;
7249 bihnumleafs += model->data_surfaces[j].num_collisiontriangles;
7256 // allocate the memory for the BIH leaf nodes
7257 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7259 // now populate the BIH leaf nodes
7262 // add render surfaces
7263 renderelement3i = model->surfmesh.data_element3i;
7264 rendervertex3f = model->surfmesh.data_vertex3f;
7265 for (j = model->submodelsurfaces_start; j < model->submodelsurfaces_end; j++)
7267 surface = model->data_surfaces + j;
7268 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7270 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7272 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7273 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7274 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7275 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7276 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7277 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7278 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7279 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7280 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7281 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7286 if (!userendersurfaces)
7288 // add collision brushes
7289 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7291 if (!brush->colbrushf)
7293 bihleafs[bihleafindex].type = BIH_BRUSH;
7294 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7295 bihleafs[bihleafindex].surfaceindex = -1;
7296 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7297 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7298 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7302 // add collision surfaces
7303 collisionelement3i = model->brush.data_collisionelement3i;
7304 collisionvertex3f = model->brush.data_collisionvertex3f;
7305 for (j = model->submodelsurfaces_start; j < model->submodelsurfaces_end; j++)
7307 surface = model->data_surfaces + j;
7308 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7310 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7311 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7312 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7313 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7314 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7315 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7316 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7317 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7318 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7319 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7325 // allocate buffers for the produced and temporary data
7326 bihmaxnodes = bihnumleafs + 1;
7327 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7328 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7329 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7332 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7334 // we're done with the temporary data
7335 Mem_Free(temp_leafsort);
7337 // resize the BIH nodes array if it over-allocated
7338 if (out->maxnodes > out->numnodes)
7340 out->maxnodes = out->numnodes;
7341 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7347 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents)
7349 int supercontents = 0;
7350 if (nativecontents & CONTENTSQ3_SOLID)
7351 supercontents |= SUPERCONTENTS_SOLID;
7352 if (nativecontents & CONTENTSQ3_WATER)
7353 supercontents |= SUPERCONTENTS_WATER;
7354 if (nativecontents & CONTENTSQ3_SLIME)
7355 supercontents |= SUPERCONTENTS_SLIME;
7356 if (nativecontents & CONTENTSQ3_LAVA)
7357 supercontents |= SUPERCONTENTS_LAVA;
7358 if (nativecontents & CONTENTSQ3_BODY)
7359 supercontents |= SUPERCONTENTS_BODY;
7360 if (nativecontents & CONTENTSQ3_CORPSE)
7361 supercontents |= SUPERCONTENTS_CORPSE;
7362 if (nativecontents & CONTENTSQ3_NODROP)
7363 supercontents |= SUPERCONTENTS_NODROP;
7364 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7365 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7366 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7367 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7368 if (nativecontents & CONTENTSQ3_DONOTENTER)
7369 supercontents |= SUPERCONTENTS_DONOTENTER;
7370 if (nativecontents & CONTENTSQ3_BOTCLIP)
7371 supercontents |= SUPERCONTENTS_BOTCLIP;
7372 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7373 supercontents |= SUPERCONTENTS_OPAQUE;
7374 return supercontents;
7377 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents)
7379 int nativecontents = 0;
7380 if (supercontents & SUPERCONTENTS_SOLID)
7381 nativecontents |= CONTENTSQ3_SOLID;
7382 if (supercontents & SUPERCONTENTS_WATER)
7383 nativecontents |= CONTENTSQ3_WATER;
7384 if (supercontents & SUPERCONTENTS_SLIME)
7385 nativecontents |= CONTENTSQ3_SLIME;
7386 if (supercontents & SUPERCONTENTS_LAVA)
7387 nativecontents |= CONTENTSQ3_LAVA;
7388 if (supercontents & SUPERCONTENTS_BODY)
7389 nativecontents |= CONTENTSQ3_BODY;
7390 if (supercontents & SUPERCONTENTS_CORPSE)
7391 nativecontents |= CONTENTSQ3_CORPSE;
7392 if (supercontents & SUPERCONTENTS_NODROP)
7393 nativecontents |= CONTENTSQ3_NODROP;
7394 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7395 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7396 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7397 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7398 if (supercontents & SUPERCONTENTS_DONOTENTER)
7399 nativecontents |= CONTENTSQ3_DONOTENTER;
7400 if (supercontents & SUPERCONTENTS_BOTCLIP)
7401 nativecontents |= CONTENTSQ3_BOTCLIP;
7402 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7403 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7404 return nativecontents;
7407 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7412 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7413 node = node->children[1];
7415 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7416 if (loadmodel->brush.num_leafs < numleafs)
7417 loadmodel->brush.num_leafs = numleafs;
7420 static void Mod_Q3BSP_Load(model_t *mod, void *buffer, void *bufferend)
7423 q3dheader_t *header;
7424 float corner[3], yawradius, modelradius;
7426 mod->modeldatatypestring = "Q3BSP";
7428 mod->type = mod_brushq3;
7429 mod->brush.ishlbsp = false;
7430 mod->brush.isbsp2rmqe = false;
7431 mod->brush.isbsp2 = false;
7432 mod->brush.isq2bsp = false;
7433 mod->brush.isq3bsp = true;
7434 mod->brush.skymasking = true;
7435 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7438 header = (q3dheader_t *)buffer;
7439 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7440 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7442 i = LittleLong(header->version);
7443 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7444 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7446 mod->soundfromcenter = true;
7447 mod->TraceBox = Mod_CollisionBIH_TraceBox;
7448 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
7449 mod->TraceLine = Mod_CollisionBIH_TraceLine;
7450 mod->TracePoint = Mod_CollisionBIH_TracePoint;
7451 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
7452 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7453 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7454 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7455 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7456 mod->brush.GetPVS = Mod_BSP_GetPVS;
7457 mod->brush.FatPVS = Mod_BSP_FatPVS;
7458 mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
7459 mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
7460 mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
7461 mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
7462 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7463 mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
7464 mod->brush.AmbientSoundLevelsForPoint = NULL;
7465 mod->brush.RoundUpToHullSize = NULL;
7466 mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
7467 mod->Draw = R_Mod_Draw;
7468 mod->DrawDepth = R_Mod_DrawDepth;
7469 mod->DrawDebug = R_Mod_DrawDebug;
7470 mod->DrawPrepass = R_Mod_DrawPrepass;
7471 mod->GetLightInfo = R_Mod_GetLightInfo;
7472 mod->CompileShadowMap = R_Mod_CompileShadowMap;
7473 mod->DrawShadowMap = R_Mod_DrawShadowMap;
7474 mod->DrawLight = R_Mod_DrawLight;
7476 mod_base = (unsigned char *)header;
7478 // swap all the lumps
7479 header->ident = LittleLong(header->ident);
7480 header->version = LittleLong(header->version);
7481 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7482 for (i = 0;i < lumps;i++)
7484 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7485 if((char *) bufferend < (char *) buffer + j)
7486 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7487 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7488 if((char *) bufferend < (char *) buffer + j)
7489 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7492 * NO, do NOT clear them!
7493 * they contain actual data referenced by other stuff.
7494 * Instead, before using the advertisements lump, check header->versio
7496 * Sorry, but otherwise it breaks memory of the first lump.
7497 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7499 header->lumps[i].fileofs = 0;
7500 header->lumps[i].filelen = 0;
7504 mod->brush.qw_md4sum = 0;
7505 mod->brush.qw_md4sum2 = 0;
7506 for (i = 0;i < lumps;i++)
7508 if (i == Q3LUMP_ENTITIES)
7510 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7511 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7513 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7515 // all this checksumming can take a while, so let's send keepalives here too
7516 CL_KeepaliveMessage(false);
7519 // allocate a texture pool if we need it
7520 if (mod->texturepool == NULL)
7521 mod->texturepool = R_AllocTexturePool();
7523 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7524 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7525 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7526 if (header->version == Q3BSPVERSION_IG)
7527 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7529 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7530 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7531 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7532 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7533 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7534 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7535 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7536 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7537 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7538 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7539 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7540 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7541 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7542 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7543 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7545 // the MakePortals code works fine on the q3bsp data as well
7546 if (mod_bsp_portalize.integer && cls.state != ca_dedicated)
7547 Mod_BSP_MakePortals();
7549 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7550 loadmodel->brush.supportwateralpha = true;
7552 loadmodel->brush.num_leafs = 0;
7553 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7555 if (loadmodel->brush.numsubmodels)
7556 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
7559 mod->modelsurfaces_sorted = (int*)Mem_Alloc(loadmodel->mempool, mod->num_surfaces * sizeof(*mod->modelsurfaces_sorted));
7560 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7565 // duplicate the basic information
7566 dpsnprintf(name, sizeof(name), "*%i", i);
7567 mod = Mod_FindName(name, loadmodel->name);
7568 // copy the base model to this one
7570 // rename the clone back to its proper name
7571 dp_strlcpy(mod->name, name, sizeof(mod->name));
7572 mod->brush.parentmodel = loadmodel;
7573 // textures and memory belong to the main model
7574 mod->texturepool = NULL;
7575 mod->mempool = NULL;
7576 mod->brush.GetPVS = NULL;
7577 mod->brush.FatPVS = NULL;
7578 mod->brush.BoxTouchingPVS = NULL;
7579 mod->brush.BoxTouchingLeafPVS = NULL;
7580 mod->brush.BoxTouchingVisibleLeafs = NULL;
7581 mod->brush.FindBoxClusters = NULL;
7582 mod->brush.LightPoint = NULL;
7583 mod->brush.AmbientSoundLevelsForPoint = NULL;
7585 mod->brush.submodel = i;
7586 if (loadmodel->brush.submodels)
7587 loadmodel->brush.submodels[i] = mod;
7589 // make the model surface list (used by shadowing/lighting)
7590 mod->submodelsurfaces_start = mod->brushq3.data_models[i].firstface;
7591 mod->submodelsurfaces_end = mod->brushq3.data_models[i].firstface + mod->brushq3.data_models[i].numfaces;
7592 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7593 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7595 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7596 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7597 // enlarge the bounding box to enclose all geometry of this model,
7598 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7599 // which can in turn mess up the farclip (as well as culling when
7600 // outside the level - an unimportant concern)
7602 //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]);
7603 for (j = mod->submodelsurfaces_start;j < mod->submodelsurfaces_end;j++)
7605 const msurface_t *surface = mod->data_surfaces + j;
7606 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7608 if (!surface->num_vertices)
7610 for (k = 0;k < surface->num_vertices;k++, v += 3)
7612 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7613 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7614 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7615 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7616 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7617 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7620 //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]);
7621 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7622 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7623 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7624 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7625 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7626 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7627 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7628 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7629 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7630 mod->yawmins[2] = mod->normalmins[2];
7631 mod->yawmaxs[2] = mod->normalmaxs[2];
7632 mod->radius = modelradius;
7633 mod->radius2 = modelradius * modelradius;
7635 Mod_SetDrawSkyAndWater(mod);
7636 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7637 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7639 // generate VBOs and other shared data before cloning submodels
7645 // make the model surface list (used by shadowing/lighting)
7646 Mod_MakeSortedSurfaces(loadmodel);
7648 if (mod_q3bsp_sRGBlightmaps.integer)
7650 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7652 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7653 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7654 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7655 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7656 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7658 else // if this is NOT set, regular rendering looks right by this requirement anyway
7661 // we want color 1 to do the same as without sRGB
7662 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7663 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7666 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7667 // we need to undo that
7668 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7672 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);
7675 void Mod_IBSP_Load(model_t *mod, void *buffer, void *bufferend)
7677 int i = LittleLong(((int *)buffer)[1]);
7678 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7679 Mod_Q3BSP_Load(mod,buffer, bufferend);
7680 else if (i == Q2BSPVERSION)
7681 Mod_Q2BSP_Load(mod,buffer, bufferend);
7683 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7686 static void Mod_VBSP_LoadEntities(sizebuf_t *sb)
7688 loadmodel->brush.entities = NULL;
7691 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
7692 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
7693 loadmodel->brush.entities[sb->cursize] = 0;
7696 static void Mod_VBSP_LoadVertexes(sizebuf_t *sb)
7700 int structsize = 12;
7702 if (sb->cursize % structsize)
7703 Host_Error("Mod_VBSP_LoadVertexes: funny lump size in %s",loadmodel->name);
7704 count = sb->cursize / structsize;
7705 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
7707 loadmodel->brushq1.vertexes = out;
7708 loadmodel->brushq1.numvertexes = count;
7710 for ( i=0 ; i<count ; i++, out++)
7712 out->position[0] = MSG_ReadLittleFloat(sb);
7713 out->position[1] = MSG_ReadLittleFloat(sb);
7714 out->position[2] = MSG_ReadLittleFloat(sb);
7718 static void Mod_VBSP_LoadEdges(sizebuf_t *sb)
7724 if (sb->cursize % structsize)
7725 Host_Error("Mod_VBSP_LoadEdges: funny lump size in %s",loadmodel->name);
7726 count = sb->cursize / structsize;
7727 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
7729 loadmodel->brushq1.edges = out;
7730 loadmodel->brushq1.numedges = count;
7732 for ( i=0 ; i<count ; i++, out++)
7734 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
7735 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
7737 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
7739 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);
7740 if(!loadmodel->brushq1.numvertexes)
7741 Host_Error("Mod_VBSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
7749 static void Mod_VBSP_LoadSurfedges(sizebuf_t *sb)
7754 if (sb->cursize % structsize)
7755 Host_Error("Mod_VBSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
7756 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
7757 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
7759 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
7760 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
7763 static void Mod_VBSP_LoadTextures(sizebuf_t *sb)
7765 Con_Printf(CON_WARN "Mod_VBSP_LoadTextures: Don't know how to do this yet\n");
7768 static void Mod_VBSP_LoadPlanes(sizebuf_t *sb)
7772 int structsize = 20;
7774 if (sb->cursize % structsize)
7775 Host_Error("Mod_VBSP_LoadPlanes: funny lump size in %s", loadmodel->name);
7776 loadmodel->brush.num_planes = sb->cursize / structsize;
7777 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
7779 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
7781 out->normal[0] = MSG_ReadLittleFloat(sb);
7782 out->normal[1] = MSG_ReadLittleFloat(sb);
7783 out->normal[2] = MSG_ReadLittleFloat(sb);
7784 out->dist = MSG_ReadLittleFloat(sb);
7785 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
7790 static void Mod_VBSP_LoadTexinfo(sizebuf_t *sb)
7793 int i, j, k, count, miptex;
7794 int structsize = 72;
7796 if (sb->cursize % structsize)
7797 Host_Error("Mod_VBSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
7798 count = sb->cursize / structsize;
7799 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
7801 loadmodel->brushq1.texinfo = out;
7802 loadmodel->brushq1.numtexinfo = count;
7804 for (i = 0;i < count;i++, out++)
7806 for (k = 0;k < 2;k++)
7807 for (j = 0;j < 4;j++)
7808 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
7810 for (k = 0;k < 2;k++)
7811 for (j = 0;j < 4;j++)
7812 MSG_ReadLittleFloat(sb); // TODO lightmapVecs
7814 out->q1flags = MSG_ReadLittleLong(sb);
7815 miptex = MSG_ReadLittleLong(sb);
7817 if (out->q1flags & TEX_SPECIAL)
7819 // if texture chosen is NULL or the shader needs a lightmap,
7820 // force to notexture water shader
7821 out->textureindex = loadmodel->num_textures - 1;
7825 // if texture chosen is NULL, force to notexture
7826 out->textureindex = loadmodel->num_textures - 2;
7828 // see if the specified miptex is valid and try to use it instead
7829 if (loadmodel->data_textures)
7831 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
7832 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
7834 out->textureindex = miptex;
7839 static void Mod_VBSP_LoadFaces(sizebuf_t *sb)
7841 msurface_t *surface;
7842 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
7843 float texmins[2], texmaxs[2], val;
7844 rtexture_t *lightmaptexture, *deluxemaptexture;
7846 int structsize = 56;
7848 if (sb->cursize % structsize)
7849 Host_Error("Mod_VBSP_LoadFaces: funny lump size in %s",loadmodel->name);
7850 count = sb->cursize / structsize;
7851 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
7852 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
7854 loadmodel->num_surfaces = count;
7856 loadmodel->brushq1.firstrender = true;
7857 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
7861 for (surfacenum = 0;surfacenum < count;surfacenum++)
7863 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
7864 totalverts += numedges;
7865 totaltris += numedges - 2;
7868 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
7870 lightmaptexture = NULL;
7871 deluxemaptexture = r_texture_blanknormalmap;
7873 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
7874 totallightmapsamples = 0;
7878 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
7880 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
7881 planenum = (unsigned short)MSG_ReadLittleShort(sb);
7882 /*side = */MSG_ReadLittleShort(sb); // TODO support onNode?
7883 firstedge = MSG_ReadLittleLong(sb);
7884 numedges = (unsigned short)MSG_ReadLittleShort(sb);
7885 texinfoindex = (unsigned short)MSG_ReadLittleShort(sb);
7886 MSG_ReadLittleLong(sb); // skipping over dispinfo and surfaceFogVolumeID, both short
7887 for (i = 0;i < MAXLIGHTMAPS;i++)
7888 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
7889 lightmapoffset = MSG_ReadLittleLong(sb);
7891 // FIXME: validate edges, texinfo, etc?
7892 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)
7893 Host_Error("Mod_VBSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
7894 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
7895 Host_Error("Mod_VBSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
7896 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
7897 Host_Error("Mod_VBSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
7899 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
7900 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
7902 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
7903 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
7904 lightmapoffset = -1;
7906 //surface->flags = surface->texture->flags;
7907 //if (LittleShort(in->side))
7908 // surface->flags |= SURF_PLANEBACK;
7909 //surface->plane = loadmodel->brush.data_planes + planenum;
7911 surface->num_firstvertex = totalverts;
7912 surface->num_vertices = numedges;
7913 surface->num_firsttriangle = totaltris;
7914 surface->num_triangles = numedges - 2;
7915 totalverts += numedges;
7916 totaltris += numedges - 2;
7918 // convert edges back to a normal polygon
7919 for (i = 0;i < surface->num_vertices;i++)
7921 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
7923 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
7925 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
7927 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
7928 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
7929 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
7930 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
7931 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
7932 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
7933 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
7934 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
7937 for (i = 0;i < surface->num_triangles;i++)
7939 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
7940 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
7941 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
7944 // compile additional data about the surface geometry
7945 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);
7946 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);
7947 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
7949 // generate surface extents information
7950 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
7951 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
7952 for (i = 1;i < surface->num_vertices;i++)
7954 for (j = 0;j < 2;j++)
7956 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
7957 texmins[j] = min(texmins[j], val);
7958 texmaxs[j] = max(texmaxs[j], val);
7961 for (i = 0;i < 2;i++)
7963 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
7964 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
7967 smax = surface->lightmapinfo->extents[0] >> 4;
7968 tmax = surface->lightmapinfo->extents[1] >> 4;
7969 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
7970 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
7973 surface->lightmaptexture = NULL;
7974 surface->deluxemaptexture = r_texture_blanknormalmap;
7975 if (lightmapoffset == -1)
7977 surface->lightmapinfo->samples = NULL;
7979 // give non-lightmapped water a 1x white lightmap
7980 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
7982 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
7983 surface->lightmapinfo->styles[0] = 0;
7984 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
7989 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
7991 // check if we should apply a lightmap to this
7992 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
7994 if (ssize > 256 || tsize > 256)
7995 Host_Error("Bad surface extents");
7997 if (lightmapsize < ssize)
7998 lightmapsize = ssize;
7999 if (lightmapsize < tsize)
8000 lightmapsize = tsize;
8002 totallightmapsamples += ssize*tsize;
8004 // force lightmap upload on first time seeing the surface
8006 // additionally this is used by the later code to see if a
8007 // lightmap is needed on this surface (rather than duplicating the
8009 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
8010 loadmodel->lit = true;
8014 // small maps (such as ammo boxes especially) don't need big lightmap
8015 // textures, so this code tries to guess a good size based on
8016 // totallightmapsamples (size of the lightmaps lump basically), as well as
8017 // trying to max out the size if there is a lot of lightmap data to store
8018 // additionally, never choose a lightmapsize that is smaller than the
8019 // largest surface encountered (as it would fail)
8021 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
8024 // now that we've decided the lightmap texture size, we can do the rest
8025 if (cls.state != ca_dedicated)
8027 int stainmapsize = 0;
8028 mod_alloclightmap_state_t allocState;
8030 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
8031 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
8033 int iu, iv, lightmapx = 0, lightmapy = 0;
8034 float u, v, ubase, vbase, uscale, vscale;
8036 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
8039 smax = surface->lightmapinfo->extents[0] >> 4;
8040 tmax = surface->lightmapinfo->extents[1] >> 4;
8041 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
8042 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
8043 stainmapsize += ssize * tsize * 3;
8045 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
8047 // allocate a texture pool if we need it
8048 if (loadmodel->texturepool == NULL)
8049 loadmodel->texturepool = R_AllocTexturePool();
8050 // could not find room, make a new lightmap
8051 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
8052 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
8053 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
8054 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);
8055 if (loadmodel->brushq1.nmaplightdata)
8056 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);
8058 Mod_AllocLightmap_Reset(&allocState);
8059 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
8061 surface->lightmaptexture = lightmaptexture;
8062 surface->deluxemaptexture = deluxemaptexture;
8063 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
8064 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
8066 uscale = 1.0f / (float)lightmapsize;
8067 vscale = 1.0f / (float)lightmapsize;
8068 ubase = lightmapx * uscale;
8069 vbase = lightmapy * vscale;
8071 for (i = 0;i < surface->num_vertices;i++)
8073 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);
8074 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);
8075 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
8076 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
8077 // LadyHavoc: calc lightmap data offset for vertex lighting to use
8080 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
8084 if (cl_stainmaps.integer)
8086 // allocate stainmaps for permanent marks on walls and clear white
8087 unsigned char *stainsamples = NULL;
8088 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
8089 memset(stainsamples, 255, stainmapsize);
8091 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
8093 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
8095 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
8096 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
8097 surface->lightmapinfo->stainsamples = stainsamples;
8098 stainsamples += ssize * tsize * 3;
8103 // generate ushort elements array if possible
8104 if (loadmodel->surfmesh.data_element3s)
8105 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8106 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8110 // Cloudwalk: Wasn't sober when I wrote this. I screamed and ran away at the face loader
8111 void Mod_VBSP_Load(model_t *mod, void *buffer, void *bufferend)
8113 static cvar_t *testing = NULL; // TEMPORARY
8116 sizebuf_t lumpsb[HL2HEADER_LUMPS];
8118 if(!testing || !testing->integer)
8121 testing = Cvar_Get(&cvars_all, "mod_bsp_vbsptest", "0", CF_CLIENT | CF_SERVER, "uhhh");
8122 Host_Error("Mod_VBSP_Load: not yet fully implemented. Change the now-generated \"mod_bsp_vbsptest\" to 1 if you wish to test this");
8127 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
8129 mod->type = mod_brushhl2;
8131 MSG_ReadLittleLong(&sb);
8132 MSG_ReadLittleLong(&sb); // TODO version check
8134 mod->modeldatatypestring = "VBSP";
8137 for (i = 0; i < HL2HEADER_LUMPS; i++)
8139 int offset = MSG_ReadLittleLong(&sb);
8140 int size = MSG_ReadLittleLong(&sb);
8141 MSG_ReadLittleLong(&sb); // TODO support version
8142 MSG_ReadLittleLong(&sb); // TODO support ident
8143 if (offset < 0 || offset + size > sb.cursize)
8144 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);
8145 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
8148 MSG_ReadLittleLong(&sb); // TODO support revision field
8150 mod->soundfromcenter = true;
8151 mod->TraceBox = Mod_CollisionBIH_TraceBox;
8152 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
8153 mod->TraceLine = Mod_CollisionBIH_TraceLine;
8154 mod->TracePoint = Mod_CollisionBIH_TracePoint;
8155 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
8156 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8157 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight; // probably not correct
8158 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents; // probably not correct
8159 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents; // probably not correct
8160 mod->brush.GetPVS = Mod_BSP_GetPVS;
8161 mod->brush.FatPVS = Mod_BSP_FatPVS;
8162 mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
8163 mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
8164 mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
8165 mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
8166 mod->brush.LightPoint = Mod_Q3BSP_LightPoint; // probably not correct
8167 mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
8168 mod->brush.AmbientSoundLevelsForPoint = NULL;
8169 mod->brush.RoundUpToHullSize = NULL;
8170 mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
8171 mod->Draw = R_Mod_Draw;
8172 mod->DrawDepth = R_Mod_DrawDepth;
8173 mod->DrawDebug = R_Mod_DrawDebug;
8174 mod->DrawPrepass = R_Mod_DrawPrepass;
8175 mod->GetLightInfo = R_Mod_GetLightInfo;
8176 mod->CompileShadowMap = R_Mod_CompileShadowMap;
8177 mod->DrawShadowMap = R_Mod_DrawShadowMap;
8178 mod->DrawLight = R_Mod_DrawLight;
8180 // allocate a texture pool if we need it
8181 if (mod->texturepool == NULL)
8182 mod->texturepool = R_AllocTexturePool();
8184 Mod_VBSP_LoadEntities(&lumpsb[HL2LUMP_ENTITIES]);
8185 Mod_VBSP_LoadVertexes(&lumpsb[HL2LUMP_VERTEXES]);
8186 Mod_VBSP_LoadEdges(&lumpsb[HL2LUMP_EDGES]);
8187 Mod_VBSP_LoadSurfedges(&lumpsb[HL2LUMP_SURFEDGES]);
8188 Mod_VBSP_LoadTextures(&lumpsb[HL2LUMP_TEXDATA/*?*/]);
8189 //Mod_VBSP_LoadLighting(&lumpsb[HL2LUMP_LIGHTING]);
8190 Mod_VBSP_LoadPlanes(&lumpsb[HL2LUMP_PLANES]);
8191 Mod_VBSP_LoadTexinfo(&lumpsb[HL2LUMP_TEXINFO]);
8194 Mod_VBSP_LoadFaces(&lumpsb[HL2LUMP_FACES]);
8198 void Mod_MAP_Load(model_t *mod, void *buffer, void *bufferend)
8200 Host_Error("Mod_MAP_Load: not yet implemented");
8203 typedef struct objvertex_s
8214 static unsigned char nobsp_pvs[1] = {1};
8216 void Mod_OBJ_Load(model_t *mod, void *buffer, void *bufferend)
8218 const char *textbase = (char *)buffer, *text = textbase;
8222 char materialname[MAX_QPATH];
8223 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8224 int index1, index2, index3;
8225 objvertex_t vfirst, vprev, vcurrent;
8228 int numtriangles = 0;
8229 int maxtriangles = 0;
8230 objvertex_t *vertices = NULL;
8232 int maxtextures = 0, numtextures = 0, textureindex = 0;
8233 int maxv = 0, numv = 1;
8234 int maxvt = 0, numvt = 1;
8235 int maxvn = 0, numvn = 1;
8236 char *texturenames = NULL;
8237 float dist, modelradius, modelyawradius, yawradius;
8238 float *obj_v = NULL;
8239 float *obj_vt = NULL;
8240 float *obj_vn = NULL;
8244 objvertex_t *thisvertex = NULL;
8245 int vertexhashindex;
8246 int *vertexhashtable = NULL;
8247 objvertex_t *vertexhashdata = NULL;
8248 objvertex_t *vdata = NULL;
8249 int vertexhashsize = 0;
8250 int vertexhashcount = 0;
8251 skinfile_t *skinfiles = NULL;
8252 unsigned char *data = NULL;
8253 int *submodelfirstsurface;
8254 msurface_t *tempsurface;
8255 msurface_t *tempsurfaces;
8257 memset(&vfirst, 0, sizeof(vfirst));
8258 memset(&vprev, 0, sizeof(vprev));
8259 memset(&vcurrent, 0, sizeof(vcurrent));
8261 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8263 loadmodel->modeldatatypestring = "OBJ";
8265 loadmodel->type = mod_obj;
8266 loadmodel->soundfromcenter = true;
8267 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8268 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8269 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8270 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8271 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8272 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8273 loadmodel->brush.TraceLineOfSight = NULL;
8274 loadmodel->brush.SuperContentsFromNativeContents = NULL;
8275 loadmodel->brush.NativeContentsFromSuperContents = NULL;
8276 loadmodel->brush.GetPVS = NULL;
8277 loadmodel->brush.FatPVS = NULL;
8278 loadmodel->brush.BoxTouchingPVS = NULL;
8279 loadmodel->brush.BoxTouchingLeafPVS = NULL;
8280 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8281 loadmodel->brush.FindBoxClusters = NULL;
8282 loadmodel->brush.LightPoint = NULL;
8283 loadmodel->brush.FindNonSolidLocation = NULL;
8284 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8285 loadmodel->brush.RoundUpToHullSize = NULL;
8286 loadmodel->brush.PointInLeaf = NULL;
8287 loadmodel->Draw = R_Mod_Draw;
8288 loadmodel->DrawDepth = R_Mod_DrawDepth;
8289 loadmodel->DrawDebug = R_Mod_DrawDebug;
8290 loadmodel->DrawPrepass = R_Mod_DrawPrepass;
8291 loadmodel->GetLightInfo = R_Mod_GetLightInfo;
8292 loadmodel->CompileShadowMap = R_Mod_CompileShadowMap;
8293 loadmodel->DrawShadowMap = R_Mod_DrawShadowMap;
8294 loadmodel->DrawLight = R_Mod_DrawLight;
8296 skinfiles = Mod_LoadSkinFiles();
8297 if (loadmodel->numskins < 1)
8298 loadmodel->numskins = 1;
8300 // make skinscenes for the skins (no groups)
8301 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8302 for (i = 0;i < loadmodel->numskins;i++)
8304 loadmodel->skinscenes[i].firstframe = i;
8305 loadmodel->skinscenes[i].framecount = 1;
8306 loadmodel->skinscenes[i].loop = true;
8307 loadmodel->skinscenes[i].framerate = 10;
8313 // we always have model 0, i.e. the first "submodel"
8314 loadmodel->brush.numsubmodels = 1;
8316 // parse the OBJ text now
8319 static char emptyarg[1] = "";
8324 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8325 line[linelen] = text[linelen];
8327 for (argc = 0;argc < 4;argc++)
8328 argv[argc] = emptyarg;
8331 while (*s == ' ' || *s == '\t')
8341 while (*s == ' ' || *s == '\t')
8351 if (argv[0][0] == '#')
8353 if (!strcmp(argv[0], "v"))
8357 maxv = max(maxv * 2, 1024);
8358 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8360 if(mod_obj_orientation.integer)
8362 obj_v[numv*3+0] = atof(argv[1]);
8363 obj_v[numv*3+2] = atof(argv[2]);
8364 obj_v[numv*3+1] = atof(argv[3]);
8368 obj_v[numv*3+0] = atof(argv[1]);
8369 obj_v[numv*3+1] = atof(argv[2]);
8370 obj_v[numv*3+2] = atof(argv[3]);
8374 else if (!strcmp(argv[0], "vt"))
8378 maxvt = max(maxvt * 2, 1024);
8379 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8381 obj_vt[numvt*2+0] = atof(argv[1]);
8382 obj_vt[numvt*2+1] = 1-atof(argv[2]);
8385 else if (!strcmp(argv[0], "vn"))
8389 maxvn = max(maxvn * 2, 1024);
8390 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8392 if(mod_obj_orientation.integer)
8394 obj_vn[numvn*3+0] = atof(argv[1]);
8395 obj_vn[numvn*3+2] = atof(argv[2]);
8396 obj_vn[numvn*3+1] = atof(argv[3]);
8400 obj_vn[numvn*3+0] = atof(argv[1]);
8401 obj_vn[numvn*3+1] = atof(argv[2]);
8402 obj_vn[numvn*3+2] = atof(argv[3]);
8406 else if (!strcmp(argv[0], "f"))
8410 if (maxtextures <= numtextures)
8412 maxtextures = max(maxtextures * 2, 256);
8413 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8415 textureindex = numtextures++;
8416 dp_strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8418 for (j = 1;j < argc;j++)
8420 index1 = atoi(argv[j]);
8421 while(argv[j][0] && argv[j][0] != '/')
8425 index2 = atoi(argv[j]);
8426 while(argv[j][0] && argv[j][0] != '/')
8430 index3 = atoi(argv[j]);
8431 // negative refers to a recent vertex
8432 // zero means not specified
8433 // positive means an absolute vertex index
8435 index1 = numv - index1;
8437 index2 = numvt - index2;
8439 index3 = numvn - index3;
8440 vcurrent.nextindex = -1;
8441 vcurrent.textureindex = textureindex;
8442 vcurrent.submodelindex = submodelindex;
8443 if (obj_v && index1 >= 0 && index1 < numv)
8444 VectorCopy(obj_v + 3*index1, vcurrent.v);
8445 if (obj_vt && index2 >= 0 && index2 < numvt)
8446 Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8447 if (obj_vn && index3 >= 0 && index3 < numvn)
8448 VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8449 if (numtriangles == 0)
8451 VectorCopy(vcurrent.v, mins);
8452 VectorCopy(vcurrent.v, maxs);
8456 mins[0] = min(mins[0], vcurrent.v[0]);
8457 mins[1] = min(mins[1], vcurrent.v[1]);
8458 mins[2] = min(mins[2], vcurrent.v[2]);
8459 maxs[0] = max(maxs[0], vcurrent.v[0]);
8460 maxs[1] = max(maxs[1], vcurrent.v[1]);
8461 maxs[2] = max(maxs[2], vcurrent.v[2]);
8467 if (maxtriangles <= numtriangles)
8469 maxtriangles = max(maxtriangles * 2, 32768);
8470 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8472 if(mod_obj_orientation.integer)
8474 vertices[numtriangles*3+0] = vfirst;
8475 vertices[numtriangles*3+1] = vprev;
8476 vertices[numtriangles*3+2] = vcurrent;
8480 vertices[numtriangles*3+0] = vfirst;
8481 vertices[numtriangles*3+2] = vprev;
8482 vertices[numtriangles*3+1] = vcurrent;
8489 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8491 submodelindex = atof(argv[1]);
8492 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8494 else if (!strcmp(argv[0], "usemtl"))
8496 for (i = 0;i < numtextures;i++)
8497 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8499 if (i < numtextures)
8503 if (maxtextures <= numtextures)
8505 maxtextures = max(maxtextures * 2, 256);
8506 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8508 textureindex = numtextures++;
8509 dp_strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8514 // now that we have the OBJ data loaded as-is, we can convert it
8516 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8517 VectorCopy(mins, loadmodel->normalmins);
8518 VectorCopy(maxs, loadmodel->normalmaxs);
8519 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8520 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8521 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8522 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8523 modelradius = modelyawradius + modelradius * modelradius;
8524 modelyawradius = sqrt(modelyawradius);
8525 modelradius = sqrt(modelradius);
8526 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8527 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8528 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8529 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8530 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8531 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8532 loadmodel->radius = modelradius;
8533 loadmodel->radius2 = modelradius * modelradius;
8535 // allocate storage for triangles
8536 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8537 // allocate vertex hash structures to build an optimal vertex subset
8538 vertexhashsize = numtriangles*2;
8539 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8540 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8541 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8542 vertexhashcount = 0;
8544 // gather surface stats for assigning vertex/triangle ranges
8548 loadmodel->num_surfaces = 0;
8549 // allocate storage for the worst case number of surfaces, later we resize
8550 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8551 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8552 tempsurface = tempsurfaces;
8553 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8555 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8556 for (textureindex = 0;textureindex < numtextures;textureindex++)
8558 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8560 thisvertex = vertices + vertexindex;
8561 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8564 // skip the surface creation if there are no triangles for it
8565 if (vertexindex == numtriangles*3)
8567 // create a surface for these vertices
8568 surfacevertices = 0;
8569 surfaceelements = 0;
8570 // we hack in a texture index in the surface to be fixed up later...
8571 tempsurface->texture = (texture_t *)((size_t)textureindex);
8572 // calculate bounds as we go
8573 VectorCopy(thisvertex->v, tempsurface->mins);
8574 VectorCopy(thisvertex->v, tempsurface->maxs);
8575 for (;vertexindex < numtriangles*3;vertexindex++)
8577 thisvertex = vertices + vertexindex;
8578 if (thisvertex->submodelindex != submodelindex)
8580 if (thisvertex->textureindex != textureindex)
8582 // add vertex to surface bounds
8583 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8584 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8585 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8586 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8587 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8588 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8589 // add the vertex if it is not found in the merged set, and
8590 // get its index (triangle element) for the surface
8591 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8592 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8594 vdata = vertexhashdata + i;
8595 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8600 i = vertexhashcount++;
8601 vdata = vertexhashdata + i;
8602 *vdata = *thisvertex;
8603 vdata->nextindex = vertexhashtable[vertexhashindex];
8604 vertexhashtable[vertexhashindex] = i;
8607 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8610 surfacetriangles = surfaceelements / 3;
8611 tempsurface->num_vertices = surfacevertices;
8612 tempsurface->num_triangles = surfacetriangles;
8613 tempsurface->num_firstvertex = firstvertex;
8614 tempsurface->num_firsttriangle = firsttriangle;
8615 firstvertex += tempsurface->num_vertices;
8616 firsttriangle += tempsurface->num_triangles;
8618 loadmodel->num_surfaces++;
8621 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8622 numvertices = firstvertex;
8623 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8624 tempsurfaces = NULL;
8626 // allocate storage for final mesh data
8627 loadmodel->num_textures = numtextures * loadmodel->numskins;
8628 loadmodel->num_texturesperskin = numtextures;
8629 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 *));
8630 loadmodel->brush.submodels = (model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(model_t *);
8631 loadmodel->modelsurfaces_sorted = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8632 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8633 loadmodel->surfmesh.num_vertices = numvertices;
8634 loadmodel->surfmesh.num_triangles = numtriangles;
8635 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8636 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8637 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8638 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8639 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8641 if (loadmodel->surfmesh.num_vertices <= 65536) {
8642 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8645 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8647 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8648 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8649 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8652 // load the textures
8653 for (textureindex = 0;textureindex < numtextures;textureindex++)
8654 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8655 Mod_FreeSkinFiles(skinfiles);
8657 // set the surface textures to their real values now that we loaded them...
8658 for (i = 0;i < loadmodel->num_surfaces;i++)
8659 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8663 Mem_Free(texturenames);
8667 Mem_Free(vertexhashtable);
8668 Mem_Free(vertexhashdata);
8670 // compute all the mesh information that was not loaded from the file
8671 if (loadmodel->surfmesh.data_element3s)
8672 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8673 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8674 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8675 // generate normals if the file did not have them
8676 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8677 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);
8678 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);
8680 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8681 loadmodel->brush.num_visleafs = 1;
8682 loadmodel->brush.num_leafs = 1;
8683 loadmodel->brush.num_nodes = 0;
8684 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8685 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8686 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8687 loadmodel->brush.num_pvsclusters = 1;
8688 loadmodel->brush.num_pvsclusterbytes = 1;
8689 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8690 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8691 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8692 loadmodel->brush.data_leafsurfaces = loadmodel->modelsurfaces_sorted;
8693 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8694 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8695 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8696 loadmodel->brush.data_leafs->clusterindex = 0;
8697 loadmodel->brush.data_leafs->areaindex = 0;
8698 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8699 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8700 loadmodel->brush.data_leafs->numleafbrushes = 0;
8701 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8702 loadmodel->brush.supportwateralpha = true;
8704 if (loadmodel->brush.numsubmodels)
8705 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
8708 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8713 // duplicate the basic information
8714 dpsnprintf(name, sizeof(name), "*%i", i);
8715 mod = Mod_FindName(name, loadmodel->name);
8716 // copy the base model to this one
8718 // rename the clone back to its proper name
8719 dp_strlcpy(mod->name, name, sizeof(mod->name));
8720 mod->brush.parentmodel = loadmodel;
8721 // textures and memory belong to the main model
8722 mod->texturepool = NULL;
8723 mod->mempool = NULL;
8724 mod->brush.GetPVS = NULL;
8725 mod->brush.FatPVS = NULL;
8726 mod->brush.BoxTouchingPVS = NULL;
8727 mod->brush.BoxTouchingLeafPVS = NULL;
8728 mod->brush.BoxTouchingVisibleLeafs = NULL;
8729 mod->brush.FindBoxClusters = NULL;
8730 mod->brush.LightPoint = NULL;
8731 mod->brush.AmbientSoundLevelsForPoint = NULL;
8733 mod->brush.submodel = i;
8734 if (loadmodel->brush.submodels)
8735 loadmodel->brush.submodels[i] = mod;
8737 // make the model surface list (used by shadowing/lighting)
8738 mod->submodelsurfaces_start = submodelfirstsurface[i];
8739 mod->submodelsurfaces_end = submodelfirstsurface[i+1];
8740 mod->firstmodelbrush = 0;
8741 mod->nummodelbrushes = 0;
8743 VectorClear(mod->normalmins);
8744 VectorClear(mod->normalmaxs);
8746 for (j = mod->submodelsurfaces_start;j < mod->submodelsurfaces_end;j++)
8748 const msurface_t *surface = mod->data_surfaces + j;
8749 const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8751 if (!surface->num_vertices)
8756 VectorCopy(v3f, mod->normalmins);
8757 VectorCopy(v3f, mod->normalmaxs);
8759 for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8761 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8762 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8763 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8764 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8765 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8766 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8769 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8770 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8771 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8772 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8773 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8774 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8775 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8776 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8777 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8778 mod->yawmins[2] = mod->normalmins[2];
8779 mod->yawmaxs[2] = mod->normalmaxs[2];
8780 mod->radius = modelradius;
8781 mod->radius2 = modelradius * modelradius;
8783 Mod_SetDrawSkyAndWater(mod);
8785 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8786 mod->render_bih = mod->collision_bih;
8788 // generate VBOs and other shared data before cloning submodels
8793 Mem_Free(submodelfirstsurface);
8795 // make the model surface list (used by shadowing/lighting)
8796 Mod_MakeSortedSurfaces(loadmodel);
8798 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);