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_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
31 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
42 cvar_t r_fxaa = {CVAR_SAVE, "r_fxaa", "0", "fast approximate anti aliasing"};
43 cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
44 cvar_t mod_obj_orientation = {0, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
45 cvar_t mod_q2bsp_littransparentsurfaces = {0, "mod_q2bsp_littransparentsurfaces", "0", "allows lighting on rain in 3v3gloom3 and other cases of transparent surfaces that have lightmaps that were ignored by quake2"};
46 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
47 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
48 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
49 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
50 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
51 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
52 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
53 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
54 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
55 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
56 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
57 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
58 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
59 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
60 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
61 cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
63 cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
64 cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
65 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
67 static texture_t mod_q1bsp_texture_solid;
68 static texture_t mod_q1bsp_texture_sky;
69 static texture_t mod_q1bsp_texture_lava;
70 static texture_t mod_q1bsp_texture_slime;
71 static texture_t mod_q1bsp_texture_water;
73 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end);
75 void Mod_BrushInit(void)
77 // Cvar_RegisterVariable(&r_subdivide_size);
78 Cvar_RegisterVariable(&mod_bsp_portalize);
79 Cvar_RegisterVariable(&r_novis);
80 Cvar_RegisterVariable(&r_nosurftextures);
81 Cvar_RegisterVariable(&r_subdivisions_tolerance);
82 Cvar_RegisterVariable(&r_subdivisions_mintess);
83 Cvar_RegisterVariable(&r_subdivisions_maxtess);
84 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
85 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
86 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
87 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
88 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
89 Cvar_RegisterVariable(&r_trippy);
90 Cvar_RegisterVariable(&r_fxaa);
91 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
92 Cvar_RegisterVariable(&mod_obj_orientation);
93 Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
94 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
95 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
96 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
97 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
98 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
99 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
100 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
101 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
102 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
103 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
104 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
105 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
106 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
107 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
108 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
109 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
110 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
111 Cvar_RegisterVariable(&mod_collision_bih);
112 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
114 // these games were made for older DP engines and are no longer
115 // maintained; use this hack to show their textures properly
116 if(gamemode == GAME_NEXUIZ)
117 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
119 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
120 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
121 mod_q1bsp_texture_solid.surfaceflags = 0;
122 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
124 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
125 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
126 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
127 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
129 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
130 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
131 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
132 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
134 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
135 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
136 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
137 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
139 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
140 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
141 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
142 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
145 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
152 // LordHavoc: modified to start at first clip node,
153 // in other words: first node of the (sub)model
154 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
156 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
158 return (mleaf_t *)node;
161 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
165 leaf = Mod_Q1BSP_PointInLeaf(model, p);
168 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
171 memcpy(out, leaf->ambient_sound_level, i);
177 memset(out, 0, outsize);
180 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
183 int nodestackindex = 0;
184 mnode_t *node, *nodestack[1024];
185 if (!model->brush.num_pvsclusters)
187 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
193 // node - recurse down the BSP tree
194 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
198 return -1; // ERROR: NAN bounding box!
199 // box is on one side of plane, take that path
200 node = node->children[sides-1];
204 // box crosses plane, take one path and remember the other
205 if (nodestackindex < 1024)
206 nodestack[nodestackindex++] = node->children[0];
207 node = node->children[1];
213 // leaf - add clusterindex to list
214 if (numclusters < maxclusters)
215 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
219 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
223 if (nodestackindex < 1024)
224 nodestack[nodestackindex++] = node->children[0];
225 node = node->children[1];
230 // leaf - add clusterindex to list
231 if (numclusters < maxclusters)
232 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
237 // try another path we didn't take earlier
238 if (nodestackindex == 0)
240 node = nodestack[--nodestackindex];
242 // return number of clusters found (even if more than the maxclusters)
246 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
248 int nodestackindex = 0;
249 mnode_t *node, *nodestack[1024];
250 if (!model->brush.num_pvsclusters)
252 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
258 // node - recurse down the BSP tree
259 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
263 return -1; // ERROR: NAN bounding box!
264 // box is on one side of plane, take that path
265 node = node->children[sides-1];
269 // box crosses plane, take one path and remember the other
270 if (nodestackindex < 1024)
271 nodestack[nodestackindex++] = node->children[0];
272 node = node->children[1];
278 // leaf - check cluster bit
279 int clusterindex = ((mleaf_t *)node)->clusterindex;
280 if (CHECKPVSBIT(pvs, clusterindex))
282 // it is visible, return immediately with the news
287 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
291 if (nodestackindex < 1024)
292 nodestack[nodestackindex++] = node->children[0];
293 node = node->children[1];
298 // leaf - check cluster bit
299 int clusterindex = ((mleaf_t *)node)->clusterindex;
300 if (CHECKPVSBIT(pvs, clusterindex))
302 // it is visible, return immediately with the news
308 // nothing to see here, try another path we didn't take earlier
309 if (nodestackindex == 0)
311 node = nodestack[--nodestackindex];
317 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
319 int nodestackindex = 0;
320 mnode_t *node, *nodestack[1024];
321 if (!model->brush.num_leafs)
323 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
329 // node - recurse down the BSP tree
330 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
334 return -1; // ERROR: NAN bounding box!
335 // box is on one side of plane, take that path
336 node = node->children[sides-1];
340 // box crosses plane, take one path and remember the other
341 if (nodestackindex < 1024)
342 nodestack[nodestackindex++] = node->children[0];
343 node = node->children[1];
349 // leaf - check cluster bit
350 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
351 if (CHECKPVSBIT(pvs, clusterindex))
353 // it is visible, return immediately with the news
358 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
362 if (nodestackindex < 1024)
363 nodestack[nodestackindex++] = node->children[0];
364 node = node->children[1];
369 // leaf - check cluster bit
370 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
371 if (CHECKPVSBIT(pvs, clusterindex))
373 // it is visible, return immediately with the news
379 // nothing to see here, try another path we didn't take earlier
380 if (nodestackindex == 0)
382 node = nodestack[--nodestackindex];
388 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
390 int nodestackindex = 0;
391 mnode_t *node, *nodestack[1024];
392 if (!model->brush.num_leafs)
394 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
400 // node - recurse down the BSP tree
401 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
405 return -1; // ERROR: NAN bounding box!
406 // box is on one side of plane, take that path
407 node = node->children[sides-1];
411 // box crosses plane, take one path and remember the other
412 if (nodestackindex < 1024)
413 nodestack[nodestackindex++] = node->children[0];
414 node = node->children[1];
420 // leaf - check if it is visible
421 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
423 // it is visible, return immediately with the news
428 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
432 if (nodestackindex < 1024)
433 nodestack[nodestackindex++] = node->children[0];
434 node = node->children[1];
439 // leaf - check if it is visible
440 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
442 // it is visible, return immediately with the news
448 // nothing to see here, try another path we didn't take earlier
449 if (nodestackindex == 0)
451 node = nodestack[--nodestackindex];
457 typedef struct findnonsolidlocationinfo_s
460 vec3_t absmin, absmax;
466 findnonsolidlocationinfo_t;
468 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
471 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
473 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
474 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
475 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
476 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
477 VectorSubtract(vert[1], vert[0], edge[0]);
478 VectorSubtract(vert[2], vert[1], edge[1]);
479 CrossProduct(edge[1], edge[0], facenormal);
480 if (facenormal[0] || facenormal[1] || facenormal[2])
482 VectorNormalize(facenormal);
483 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
484 if (f <= info->bestdist && f >= -info->bestdist)
486 VectorSubtract(vert[0], vert[2], edge[2]);
487 VectorNormalize(edge[0]);
488 VectorNormalize(edge[1]);
489 VectorNormalize(edge[2]);
490 CrossProduct(facenormal, edge[0], edgenormal[0]);
491 CrossProduct(facenormal, edge[1], edgenormal[1]);
492 CrossProduct(facenormal, edge[2], edgenormal[2]);
494 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
495 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
496 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
498 // we got lucky, the center is within the face
499 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
503 if (info->bestdist > dist)
505 info->bestdist = dist;
506 VectorScale(facenormal, (info->radius - -dist), info->nudge);
511 if (info->bestdist > dist)
513 info->bestdist = dist;
514 VectorScale(facenormal, (info->radius - dist), info->nudge);
520 // check which edge or vertex the center is nearest
521 for (i = 0;i < 3;i++)
523 f = DotProduct(info->center, edge[i]);
524 if (f >= DotProduct(vert[0], edge[i])
525 && f <= DotProduct(vert[1], edge[i]))
528 VectorMA(info->center, -f, edge[i], point);
529 dist = sqrt(DotProduct(point, point));
530 if (info->bestdist > dist)
532 info->bestdist = dist;
533 VectorScale(point, (info->radius / dist), info->nudge);
535 // skip both vertex checks
536 // (both are further away than this edge)
541 // not on edge, check first vertex of edge
542 VectorSubtract(info->center, vert[i], point);
543 dist = sqrt(DotProduct(point, point));
544 if (info->bestdist > dist)
546 info->bestdist = dist;
547 VectorScale(point, (info->radius / dist), info->nudge);
556 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
558 int surfacenum, k, *mark;
560 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
562 surface = info->model->data_surfaces + *mark;
563 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
565 if(surface->deprecatedq3num_bboxstride > 0)
568 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
569 for(i = 0; i < cnt; ++i)
571 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
573 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
575 tri = i * surface->deprecatedq3num_bboxstride + k;
576 if(tri >= surface->num_triangles)
578 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
585 for (k = 0;k < surface->num_triangles;k++)
587 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
594 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
598 float f = PlaneDiff(info->center, node->plane);
599 if (f >= -info->bestdist)
600 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
601 if (f <= info->bestdist)
602 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
606 if (((mleaf_t *)node)->numleafsurfaces)
607 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
611 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
614 findnonsolidlocationinfo_t info;
620 VectorCopy(in, info.center);
621 info.radius = radius;
626 VectorClear(info.nudge);
627 info.bestdist = radius;
628 VectorCopy(info.center, info.absmin);
629 VectorCopy(info.center, info.absmax);
630 info.absmin[0] -= info.radius + 1;
631 info.absmin[1] -= info.radius + 1;
632 info.absmin[2] -= info.radius + 1;
633 info.absmax[0] += info.radius + 1;
634 info.absmax[1] += info.radius + 1;
635 info.absmax[2] += info.radius + 1;
636 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
637 VectorAdd(info.center, info.nudge, info.center);
639 while (info.bestdist < radius && ++i < 10);
640 VectorCopy(info.center, out);
643 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
645 switch(nativecontents)
650 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
652 return SUPERCONTENTS_WATER;
654 return SUPERCONTENTS_SLIME;
656 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
658 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
663 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
665 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
666 return CONTENTS_SOLID;
667 if (supercontents & SUPERCONTENTS_SKY)
669 if (supercontents & SUPERCONTENTS_LAVA)
670 return CONTENTS_LAVA;
671 if (supercontents & SUPERCONTENTS_SLIME)
672 return CONTENTS_SLIME;
673 if (supercontents & SUPERCONTENTS_WATER)
674 return CONTENTS_WATER;
675 return CONTENTS_EMPTY;
678 typedef struct RecursiveHullCheckTraceInfo_s
680 // the hull we're tracing through
683 // the trace structure to fill in
686 // start, end, and end - start (in model space)
691 RecursiveHullCheckTraceInfo_t;
693 // 1/32 epsilon to keep floating point happy
694 #define DIST_EPSILON (0.03125)
696 #define HULLCHECKSTATE_EMPTY 0
697 #define HULLCHECKSTATE_SOLID 1
698 #define HULLCHECKSTATE_DONE 2
700 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
702 // status variables, these don't need to be saved on the stack when
703 // recursing... but are because this should be thread-safe
704 // (note: tracing against a bbox is not thread-safe, yet)
709 // variables that need to be stored on the stack when recursing
714 // keep looping until we hit a leaf
717 // find the point distances
718 node = t->hull->clipnodes + num;
719 plane = t->hull->planes + node->planenum;
721 // axial planes can be calculated more quickly without the DotProduct
724 t1 = p1[plane->type] - plane->dist;
725 t2 = p2[plane->type] - plane->dist;
729 t1 = DotProduct (plane->normal, p1) - plane->dist;
730 t2 = DotProduct (plane->normal, p2) - plane->dist;
733 // negative plane distances indicate children[1] (behind plane)
737 // if the line starts and ends on the same side of the plane, recurse
738 // into that child instantly
739 if (p1side == p2side)
741 #if COLLISIONPARANOID >= 3
747 // loop back and process the start child
748 num = node->children[p1side];
752 // find the midpoint where the line crosses the plane, use the
753 // original line for best accuracy
754 #if COLLISIONPARANOID >= 3
759 t1 = t->start[plane->type] - plane->dist;
760 t2 = t->end[plane->type] - plane->dist;
764 t1 = DotProduct (plane->normal, t->start) - plane->dist;
765 t2 = DotProduct (plane->normal, t->end) - plane->dist;
767 midf = t1 / (t1 - t2);
768 midf = bound(p1f, midf, p2f);
769 VectorMA(t->start, midf, t->dist, mid);
771 // we now have a mid point, essentially splitting the line into
772 // the segments in the near child and the far child, we can now
773 // recurse those in order and get their results
775 // recurse both sides, front side first
776 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
777 // if this side is not empty, return what it is (solid or done)
778 if (ret != HULLCHECKSTATE_EMPTY)
781 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
782 // if other side is not solid, return what it is (empty or done)
783 if (ret != HULLCHECKSTATE_SOLID)
786 // front is air and back is solid, this is the impact point...
788 // copy the plane information, flipping it if needed
791 t->trace->plane.dist = -plane->dist;
792 VectorNegate (plane->normal, t->trace->plane.normal);
796 t->trace->plane.dist = plane->dist;
797 VectorCopy (plane->normal, t->trace->plane.normal);
800 // calculate the return fraction which is nudged off the surface a bit
801 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
802 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
803 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
804 t->trace->fraction = bound(0, midf, 1);
806 #if COLLISIONPARANOID >= 3
809 return HULLCHECKSTATE_DONE;
813 // we reached a leaf contents
816 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
817 if (!t->trace->startfound)
819 t->trace->startfound = true;
820 t->trace->startsupercontents |= num;
822 if (num & SUPERCONTENTS_LIQUIDSMASK)
823 t->trace->inwater = true;
825 t->trace->inopen = true;
826 if (num & SUPERCONTENTS_SOLID)
827 t->trace->hittexture = &mod_q1bsp_texture_solid;
828 else if (num & SUPERCONTENTS_SKY)
829 t->trace->hittexture = &mod_q1bsp_texture_sky;
830 else if (num & SUPERCONTENTS_LAVA)
831 t->trace->hittexture = &mod_q1bsp_texture_lava;
832 else if (num & SUPERCONTENTS_SLIME)
833 t->trace->hittexture = &mod_q1bsp_texture_slime;
835 t->trace->hittexture = &mod_q1bsp_texture_water;
836 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
837 t->trace->hitsupercontents = num;
838 if (num & t->trace->hitsupercontentsmask)
840 // if the first leaf is solid, set startsolid
841 if (t->trace->allsolid)
842 t->trace->startsolid = true;
843 #if COLLISIONPARANOID >= 3
846 return HULLCHECKSTATE_SOLID;
850 t->trace->allsolid = false;
851 #if COLLISIONPARANOID >= 3
854 return HULLCHECKSTATE_EMPTY;
858 //#if COLLISIONPARANOID < 2
859 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
862 mclipnode_t *nodes = t->hull->clipnodes;
863 mplane_t *planes = t->hull->planes;
865 VectorCopy(t->start, point);
868 plane = planes + nodes[num].planenum;
869 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
871 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
872 t->trace->startsupercontents |= num;
873 if (num & SUPERCONTENTS_LIQUIDSMASK)
874 t->trace->inwater = true;
876 t->trace->inopen = true;
877 if (num & t->trace->hitsupercontentsmask)
879 t->trace->allsolid = t->trace->startsolid = true;
880 return HULLCHECKSTATE_SOLID;
884 t->trace->allsolid = t->trace->startsolid = false;
885 return HULLCHECKSTATE_EMPTY;
890 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask)
892 RecursiveHullCheckTraceInfo_t rhc;
894 memset(&rhc, 0, sizeof(rhc));
895 memset(trace, 0, sizeof(trace_t));
897 rhc.trace->fraction = 1;
898 rhc.trace->allsolid = true;
899 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
900 VectorCopy(start, rhc.start);
901 VectorCopy(start, rhc.end);
902 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
905 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask);
907 static void Mod_Q1BSP_TraceLine(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask)
909 RecursiveHullCheckTraceInfo_t rhc;
911 if (VectorCompare(start, end))
913 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
917 // sometimes we want to traceline against polygons so we can report the texture that was hit rather than merely a contents, but using this method breaks one of negke's maps so it must be a cvar check...
918 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
920 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
924 memset(&rhc, 0, sizeof(rhc));
925 memset(trace, 0, sizeof(trace_t));
927 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
928 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
929 rhc.trace->fraction = 1;
930 rhc.trace->allsolid = true;
931 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
932 VectorCopy(start, rhc.start);
933 VectorCopy(end, rhc.end);
934 VectorSubtract(rhc.end, rhc.start, rhc.dist);
935 #if COLLISIONPARANOID >= 2
936 Con_Printf("t(%f %f %f,%f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2]);
937 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
942 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
943 memset(&testtrace, 0, sizeof(trace_t));
944 rhc.trace = &testtrace;
945 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
946 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
947 rhc.trace->fraction = 1;
948 rhc.trace->allsolid = true;
949 VectorCopy(test, rhc.start);
950 VectorCopy(test, rhc.end);
951 VectorClear(rhc.dist);
952 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
953 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
954 if (!trace->startsolid && testtrace.startsolid)
955 Con_Printf(" - ended in solid!\n");
959 if (VectorLength2(rhc.dist))
960 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
962 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
966 static void Mod_Q1BSP_TraceBox(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask)
968 // this function currently only supports same size start and end
970 RecursiveHullCheckTraceInfo_t rhc;
972 if (VectorCompare(boxmins, boxmaxs))
974 if (VectorCompare(start, end))
975 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
977 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
981 memset(&rhc, 0, sizeof(rhc));
982 memset(trace, 0, sizeof(trace_t));
984 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
985 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
986 rhc.trace->fraction = 1;
987 rhc.trace->allsolid = true;
988 VectorSubtract(boxmaxs, boxmins, boxsize);
990 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
991 else if (model->brush.ishlbsp)
993 // LordHavoc: this has to have a minor tolerance (the .1) because of
994 // minor float precision errors from the box being transformed around
995 if (boxsize[0] < 32.1)
997 if (boxsize[2] < 54) // pick the nearest of 36 or 72
998 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
1000 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1003 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1007 // LordHavoc: this has to have a minor tolerance (the .1) because of
1008 // minor float precision errors from the box being transformed around
1009 if (boxsize[0] < 32.1)
1010 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1012 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1014 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1015 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1016 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1017 #if COLLISIONPARANOID >= 2
1018 Con_Printf("t(%f %f %f,%f %f %f,%i %f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2], rhc.hull - model->brushq1.hulls, rhc.hull->clip_mins[0], rhc.hull->clip_mins[1], rhc.hull->clip_mins[2]);
1019 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1024 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1025 memset(&testtrace, 0, sizeof(trace_t));
1026 rhc.trace = &testtrace;
1027 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1028 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1029 rhc.trace->fraction = 1;
1030 rhc.trace->allsolid = true;
1031 VectorCopy(test, rhc.start);
1032 VectorCopy(test, rhc.end);
1033 VectorClear(rhc.dist);
1034 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1035 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1036 if (!trace->startsolid && testtrace.startsolid)
1037 Con_Printf(" - ended in solid!\n");
1041 if (VectorLength2(rhc.dist))
1042 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1044 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1048 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1050 int num = model->brushq1.hulls[0].firstclipnode;
1052 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1053 mplane_t *planes = model->brushq1.hulls[0].planes;
1056 plane = planes + nodes[num].planenum;
1057 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1059 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1062 void Collision_ClipTrace_Box(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1066 colplanef_t cbox_planes[6];
1068 cbox.hasaabbplanes = true;
1069 cbox.supercontents = boxsupercontents;
1072 cbox.numtriangles = 0;
1073 cbox.planes = cbox_planes;
1075 cbox.elements = NULL;
1083 cbox_planes[0].normal[0] = 1;cbox_planes[0].normal[1] = 0;cbox_planes[0].normal[2] = 0;cbox_planes[0].dist = cmaxs[0] - mins[0];
1084 cbox_planes[1].normal[0] = -1;cbox_planes[1].normal[1] = 0;cbox_planes[1].normal[2] = 0;cbox_planes[1].dist = maxs[0] - cmins[0];
1085 cbox_planes[2].normal[0] = 0;cbox_planes[2].normal[1] = 1;cbox_planes[2].normal[2] = 0;cbox_planes[2].dist = cmaxs[1] - mins[1];
1086 cbox_planes[3].normal[0] = 0;cbox_planes[3].normal[1] = -1;cbox_planes[3].normal[2] = 0;cbox_planes[3].dist = maxs[1] - cmins[1];
1087 cbox_planes[4].normal[0] = 0;cbox_planes[4].normal[1] = 0;cbox_planes[4].normal[2] = 1;cbox_planes[4].dist = cmaxs[2] - mins[2];
1088 cbox_planes[5].normal[0] = 0;cbox_planes[5].normal[1] = 0;cbox_planes[5].normal[2] = -1;cbox_planes[5].dist = maxs[2] - cmins[2];
1089 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1090 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1091 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1092 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1093 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1094 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1095 memset(trace, 0, sizeof(trace_t));
1096 trace->hitsupercontentsmask = hitsupercontentsmask;
1097 trace->skipsupercontentsmask = skipsupercontentsmask;
1098 trace->fraction = 1;
1099 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1101 RecursiveHullCheckTraceInfo_t rhc;
1102 static hull_t box_hull;
1103 static mclipnode_t box_clipnodes[6];
1104 static mplane_t box_planes[6];
1105 // fill in a default trace
1106 memset(&rhc, 0, sizeof(rhc));
1107 memset(trace, 0, sizeof(trace_t));
1108 //To keep everything totally uniform, bounding boxes are turned into small
1109 //BSP trees instead of being compared directly.
1110 // create a temp hull from bounding box sizes
1111 box_planes[0].dist = cmaxs[0] - mins[0];
1112 box_planes[1].dist = cmins[0] - maxs[0];
1113 box_planes[2].dist = cmaxs[1] - mins[1];
1114 box_planes[3].dist = cmins[1] - maxs[1];
1115 box_planes[4].dist = cmaxs[2] - mins[2];
1116 box_planes[5].dist = cmins[2] - maxs[2];
1117 #if COLLISIONPARANOID >= 3
1118 Con_Printf("box_planes %f:%f %f:%f %f:%f\ncbox %f %f %f:%f %f %f\nbox %f %f %f:%f %f %f\n", box_planes[0].dist, box_planes[1].dist, box_planes[2].dist, box_planes[3].dist, box_planes[4].dist, box_planes[5].dist, cmins[0], cmins[1], cmins[2], cmaxs[0], cmaxs[1], cmaxs[2], mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
1121 if (box_hull.clipnodes == NULL)
1125 //Set up the planes and clipnodes so that the six floats of a bounding box
1126 //can just be stored out and get a proper hull_t structure.
1128 box_hull.clipnodes = box_clipnodes;
1129 box_hull.planes = box_planes;
1130 box_hull.firstclipnode = 0;
1131 box_hull.lastclipnode = 5;
1133 for (i = 0;i < 6;i++)
1135 box_clipnodes[i].planenum = i;
1139 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1141 box_clipnodes[i].children[side^1] = i + 1;
1143 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1145 box_planes[i].type = i>>1;
1146 box_planes[i].normal[i>>1] = 1;
1150 // trace a line through the generated clipping hull
1151 //rhc.boxsupercontents = boxsupercontents;
1152 rhc.hull = &box_hull;
1154 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1155 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1156 rhc.trace->fraction = 1;
1157 rhc.trace->allsolid = true;
1158 VectorCopy(start, rhc.start);
1159 VectorCopy(end, rhc.end);
1160 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1161 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1162 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1163 if (rhc.trace->startsupercontents)
1164 rhc.trace->startsupercontents = boxsupercontents;
1168 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1170 memset(trace, 0, sizeof(trace_t));
1171 trace->fraction = 1;
1172 trace->hitsupercontentsmask = hitsupercontentsmask;
1173 trace->skipsupercontentsmask = skipsupercontentsmask;
1174 if (BoxesOverlap(start, start, cmins, cmaxs))
1176 trace->startsupercontents |= boxsupercontents;
1177 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1179 trace->startsolid = true;
1180 trace->allsolid = true;
1185 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1188 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
1189 return trace.fraction == 1;
1192 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(dp_model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1196 float mid, distz = endz - startz;
1200 switch (node->plane->type)
1203 node = node->children[x < node->plane->dist];
1204 continue; // loop back and process the new node
1206 node = node->children[y < node->plane->dist];
1207 continue; // loop back and process the new node
1209 side = startz < node->plane->dist;
1210 if ((endz < node->plane->dist) == side)
1212 node = node->children[side];
1213 continue; // loop back and process the new node
1215 // found an intersection
1216 mid = node->plane->dist;
1219 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1220 front += startz * node->plane->normal[2];
1221 back += endz * node->plane->normal[2];
1222 side = front < node->plane->dist;
1223 if ((back < node->plane->dist) == side)
1225 node = node->children[side];
1226 continue; // loop back and process the new node
1228 // found an intersection
1229 mid = startz + distz * (front - node->plane->dist) / (front - back);
1233 // go down front side
1234 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1235 return true; // hit something
1237 // check for impact on this node
1238 if (node->numsurfaces)
1241 int dsi, dti, lmwidth, lmheight;
1243 msurface_t *surface;
1244 unsigned char *lightmap;
1245 int maps, line3, size3;
1248 float scale, w, w00, w01, w10, w11;
1250 surface = model->data_surfaces + node->firstsurface;
1251 for (i = 0;i < node->numsurfaces;i++, surface++)
1253 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1254 continue; // no lightmaps
1256 // location we want to sample in the lightmap
1257 ds = ((x * surface->lightmapinfo->texinfo->vecs[0][0] + y * surface->lightmapinfo->texinfo->vecs[0][1] + mid * surface->lightmapinfo->texinfo->vecs[0][2] + surface->lightmapinfo->texinfo->vecs[0][3]) - surface->lightmapinfo->texturemins[0]) * 0.0625f;
1258 dt = ((x * surface->lightmapinfo->texinfo->vecs[1][0] + y * surface->lightmapinfo->texinfo->vecs[1][1] + mid * surface->lightmapinfo->texinfo->vecs[1][2] + surface->lightmapinfo->texinfo->vecs[1][3]) - surface->lightmapinfo->texturemins[1]) * 0.0625f;
1261 // thanks to jitspoe for pointing out that this int cast was
1262 // rounding toward zero, so we floor it
1263 dsi = (int)floor(ds);
1264 dti = (int)floor(dt);
1265 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1266 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1269 // we have to tolerate a position of lmwidth-1 for some rare
1270 // cases - in which case the sampling position still gets
1271 // clamped but the color gets interpolated to that edge.
1272 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1274 // in the rare cases where we're sampling slightly off
1275 // the polygon, clamp the sampling position (we can still
1276 // interpolate outside it, where it becomes extrapolation)
1281 if (dsi > lmwidth-2)
1283 if (dti > lmheight-2)
1286 // calculate bilinear interpolation factors
1287 // and also multiply by fixedpoint conversion factors to
1288 // compensate for lightmaps being 0-255 (as 0-2), we use
1289 // r_refdef.scene.rtlightstylevalue here which is already
1290 // 0.000-2.148 range
1291 // (if we used r_refdef.scene.lightstylevalue this
1292 // divisor would be 32768 rather than 128)
1295 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1296 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1297 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1298 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1300 // values for pointer math
1301 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1302 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1304 // look up the pixel
1305 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1307 // bilinear filter each lightmap style, and sum them
1308 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1310 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1311 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1312 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1313 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1314 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1318 return true; // success
1323 // go down back side
1324 node = node->children[side ^ 1];
1326 distz = endz - startz;
1327 // loop back and process the new node
1330 // did not hit anything
1334 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1336 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1337 VectorSet(diffusenormal, 0, 0, 1);
1339 if (!model->brushq1.lightdata)
1341 VectorSet(ambientcolor, 1, 1, 1);
1342 VectorSet(diffusecolor, 0, 0, 0);
1346 Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2] + 0.125, p[2] - 65536);
1349 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1354 const msurface_t *surface;
1359 float edgenormal[3];
1366 surface = model->data_surfaces + node->firstsurface;
1367 for (i = 0;i < node->numsurfaces;i++, surface++)
1369 // skip surfaces whose bounding box does not include the point
1370 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1372 // skip faces with contents we don't care about
1373 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1375 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1376 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1378 // get the surface normal - since it is flat we know any vertex normal will suffice
1379 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1381 if (DotProduct(t->dist, normal) > 0)
1383 // iterate edges and see if the point is outside one of them
1384 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1386 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1387 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1388 VectorSubtract(v0, v1, edgedir);
1389 CrossProduct(edgedir, normal, edgenormal);
1390 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1393 // if the point is outside one of the edges, it is not within the surface
1394 if (j < surface->num_vertices)
1397 // we hit a surface, this is the impact point...
1398 VectorCopy(normal, t->trace->plane.normal);
1399 t->trace->plane.dist = DotProduct(normal, p);
1401 // calculate the return fraction which is nudged off the surface a bit
1402 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1403 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1404 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1405 t->trace->fraction = bound(0, midf, 1);
1407 t->trace->hittexture = surface->texture->currentframe;
1408 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1409 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1410 return surface->texture->currentframe;
1415 static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
1417 const mplane_t *plane;
1420 double midf, mid[3];
1421 const mleaf_t *leaf;
1425 plane = node->plane;
1426 if (plane->type < 3)
1428 t1 = p1[plane->type] - plane->dist;
1429 t2 = p2[plane->type] - plane->dist;
1433 t1 = DotProduct (plane->normal, p1) - plane->dist;
1434 t2 = DotProduct (plane->normal, p2) - plane->dist;
1440 node = node->children[1];
1449 node = node->children[0];
1455 // the line intersects, find intersection point
1456 // LordHavoc: this uses the original trace for maximum accuracy
1457 if (plane->type < 3)
1459 t1 = t->start[plane->type] - plane->dist;
1460 t2 = t->end[plane->type] - plane->dist;
1464 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1465 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1468 midf = t1 / (t1 - t2);
1469 VectorMA(t->start, midf, t->dist, mid);
1471 // recurse both sides, front side first, return if we hit a surface
1472 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1473 return HULLCHECKSTATE_DONE;
1475 // test each surface on the node
1476 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1477 if (t->trace->hittexture)
1478 return HULLCHECKSTATE_DONE;
1480 // recurse back side
1481 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1483 leaf = (const mleaf_t *)node;
1484 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1485 if (!t->trace->startfound)
1487 t->trace->startfound = true;
1488 t->trace->startsupercontents |= side;
1490 if (side & SUPERCONTENTS_LIQUIDSMASK)
1491 t->trace->inwater = true;
1493 t->trace->inopen = true;
1494 if (side & t->trace->hitsupercontentsmask)
1496 // if the first leaf is solid, set startsolid
1497 if (t->trace->allsolid)
1498 t->trace->startsolid = true;
1499 return HULLCHECKSTATE_SOLID;
1503 t->trace->allsolid = false;
1504 return HULLCHECKSTATE_EMPTY;
1508 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask)
1510 RecursiveHullCheckTraceInfo_t rhc;
1512 memset(&rhc, 0, sizeof(rhc));
1513 memset(trace, 0, sizeof(trace_t));
1515 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1516 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1517 rhc.trace->fraction = 1;
1518 rhc.trace->allsolid = true;
1519 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1520 VectorCopy(start, rhc.start);
1521 VectorCopy(end, rhc.end);
1522 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1523 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1524 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1527 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1530 unsigned char *outstart = out;
1531 while (out < outend)
1535 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1545 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1548 for (c = *in++;c > 0;c--)
1552 Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1563 R_Q1BSP_LoadSplitSky
1565 A sky texture is 256*128, with the right side being a masked overlay
1568 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1573 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1574 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1576 // allocate a texture pool if we need it
1577 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1578 loadmodel->texturepool = R_AllocTexturePool();
1580 if (bytesperpixel == 4)
1582 for (y = 0;y < h;y++)
1584 for (x = 0;x < w;x++)
1586 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1587 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1593 // make an average value for the back to avoid
1594 // a fringe on the top level
1603 for (y = 0;y < h;y++)
1605 for (x = 0;x < w;x++)
1607 p = src[x*width+y+w];
1608 r += palette_rgb[p][0];
1609 g += palette_rgb[p][1];
1610 b += palette_rgb[p][2];
1613 bgra.b[2] = r/(w*h);
1614 bgra.b[1] = g/(w*h);
1615 bgra.b[0] = b/(w*h);
1617 for (y = 0;y < h;y++)
1619 for (x = 0;x < w;x++)
1621 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1623 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1628 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1629 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1630 Mem_Free(solidpixels);
1631 Mem_Free(alphapixels);
1634 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1636 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1637 skinframe_t *skinframe;
1638 texture_t *tx, *tx2, *anims[10], *altanims[10];
1639 texture_t backuptex;
1640 unsigned char *data, *mtdata;
1642 char mapname[MAX_QPATH], name[MAX_QPATH];
1643 unsigned char zeroopaque[4], zerotrans[4];
1646 Vector4Set(zeroopaque, 0, 0, 0, 255);
1647 Vector4Set(zerotrans, 0, 0, 0, 128);
1649 loadmodel->data_textures = NULL;
1651 // add two slots for notexture walls and notexture liquids
1654 nummiptex = MSG_ReadLittleLong(sb);
1655 loadmodel->num_textures = nummiptex + 2;
1656 loadmodel->num_texturesperskin = loadmodel->num_textures;
1660 loadmodel->num_textures = 2;
1661 loadmodel->num_texturesperskin = loadmodel->num_textures;
1664 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1666 // fill out all slots with notexture
1667 if (cls.state != ca_dedicated)
1668 skinframe = R_SkinFrame_LoadMissing();
1671 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1673 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1676 tx->basealpha = 1.0f;
1677 if (cls.state != ca_dedicated)
1679 tx->numskinframes = 1;
1680 tx->skinframerate = 1;
1681 tx->skinframes[0] = skinframe;
1682 tx->currentskinframe = tx->skinframes[0];
1684 tx->basematerialflags = MATERIALFLAG_WALL;
1685 if (i == loadmodel->num_textures - 1)
1687 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1688 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1689 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1693 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1694 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1696 tx->currentframe = tx;
1698 // clear water settings
1701 tx->refractfactor = 1;
1702 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1703 tx->reflectfactor = 1;
1704 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1705 tx->r_water_wateralpha = 1;
1706 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1707 tx->offsetscale = 1;
1709 tx->specularscalemod = 1;
1710 tx->specularpowermod = 1;
1711 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1712 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1713 // JUST GREP FOR "specularscalemod = 1".
1718 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1722 s = loadmodel->name;
1723 if (!strncasecmp(s, "maps/", 5))
1725 FS_StripExtension(s, mapname, sizeof(mapname));
1727 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1728 // LordHavoc: mostly rewritten map texture loader
1729 for (i = 0;i < nummiptex;i++)
1731 doffset = MSG_ReadLittleLong(sb);
1732 if (r_nosurftextures.integer)
1736 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1740 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1742 // copy name, but only up to 16 characters
1743 // (the output buffer can hold more than this, but the input buffer is
1745 for (j = 0;j < 16;j++)
1746 name[j] = MSG_ReadByte(&miptexsb);
1748 // pretty up the buffer (replacing any trailing garbage with 0)
1749 for (j = (int)strlen(name);j < 16;j++)
1754 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1755 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1758 mtwidth = MSG_ReadLittleLong(&miptexsb);
1759 mtheight = MSG_ReadLittleLong(&miptexsb);
1761 j = MSG_ReadLittleLong(&miptexsb);
1765 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1767 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1770 mtdata = miptexsb.data + j;
1773 if ((mtwidth & 15) || (mtheight & 15))
1774 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1776 // LordHavoc: force all names to lowercase
1777 for (j = 0;name[j];j++)
1778 if (name[j] >= 'A' && name[j] <= 'Z')
1779 name[j] += 'a' - 'A';
1781 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1782 backuptex = loadmodel->data_textures[i];
1783 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1785 loadmodel->data_textures[i] = backuptex;
1787 tx = loadmodel->data_textures + i;
1788 strlcpy(tx->name, name, sizeof(tx->name));
1789 tx->width = mtwidth;
1790 tx->height = mtheight;
1791 tx->basealpha = 1.0f;
1793 if (tx->name[0] == '*')
1795 if (!strncmp(tx->name, "*lava", 5))
1797 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1798 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1800 else if (!strncmp(tx->name, "*slime", 6))
1802 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1803 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1807 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1808 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1811 else if (!strncmp(tx->name, "sky", 3))
1813 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1814 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1815 // for the surface traceline we need to hit this surface as a solid...
1816 tx->supercontents |= SUPERCONTENTS_SOLID;
1820 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1821 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1824 if (cls.state != ca_dedicated)
1826 // LordHavoc: HL sky textures are entirely different than quake
1827 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1829 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1831 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1832 if (data && image_width == image_height * 2)
1834 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1837 else if (mtdata != NULL)
1838 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1842 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);
1844 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);
1846 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1849 // did not find external texture, load it from the bsp or wad3
1850 if (loadmodel->brush.ishlbsp)
1852 // internal texture overrides wad
1853 unsigned char *pixels, *freepixels;
1854 pixels = freepixels = NULL;
1856 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1858 pixels = freepixels = W_GetTextureBGRA(tx->name);
1861 tx->width = image_width;
1862 tx->height = image_height;
1863 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1866 Mem_Free(freepixels);
1868 else if (mtdata) // texture included
1869 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1871 // if skinframe is still NULL the "missing" texture will be used
1873 tx->skinframes[0] = skinframe;
1875 // LordHavoc: some Tenebrae textures get replaced by black
1876 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1877 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1878 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1879 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1882 tx->basematerialflags = MATERIALFLAG_WALL;
1883 if (tx->name[0] == '*')
1885 // LordHavoc: some turbulent textures should not be affected by wateralpha
1886 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1887 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1888 else if (!strncmp(tx->name,"*lava",5)
1889 || !strncmp(tx->name,"*teleport",9)
1890 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1891 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1893 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1894 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1895 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1897 else if (tx->name[0] == '{') // fence textures
1899 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1901 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1903 // replace the texture with black
1904 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1906 else if (!strncmp(tx->name, "sky", 3))
1907 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1908 else if (!strcmp(tx->name, "caulk"))
1909 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1910 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1911 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1913 // start out with no animation
1914 tx->currentframe = tx;
1915 tx->currentskinframe = tx->skinframes[0];
1916 tx->currentmaterialflags = tx->basematerialflags;
1919 // sequence the animations
1920 for (i = 0;i < nummiptex;i++)
1922 tx = loadmodel->data_textures + i;
1923 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1926 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1928 Con_Printf("Bad animating texture %s\n", tx->name);
1931 if (tx->anim_total[0] || tx->anim_total[1])
1932 continue; // already sequenced
1934 // find the number of frames in the animation
1935 memset(anims, 0, sizeof(anims));
1936 memset(altanims, 0, sizeof(altanims));
1938 for (j = i;j < nummiptex;j++)
1940 tx2 = loadmodel->data_textures + j;
1941 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1945 if (num >= '0' && num <= '9')
1946 anims[num - '0'] = tx2;
1947 else if (num >= 'a' && num <= 'j')
1948 altanims[num - 'a'] = tx2;
1949 // No need to warn otherwise - we already did above.
1953 for (j = 0;j < 10;j++)
1960 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1963 for (j = 0;j < max;j++)
1967 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1971 for (j = 0;j < altmax;j++)
1975 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1982 // If we have exactly one frame, something's wrong.
1983 if (max + altmax <= 1)
1985 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
1990 // if there is no alternate animation, duplicate the primary
1991 // animation into the alternate
1993 for (k = 0;k < 10;k++)
1994 altanims[k] = anims[k];
2000 Con_Printf("Missing frame 0 of %s\n", tx->name);
2002 // however, we can handle this by duplicating the alternate animation into the primary
2004 for (k = 0;k < 10;k++)
2005 anims[k] = altanims[k];
2009 // link together the primary animation
2010 for (j = 0;j < max;j++)
2013 tx2->animated = 1; // q1bsp
2014 tx2->anim_total[0] = max;
2015 tx2->anim_total[1] = altmax;
2016 for (k = 0;k < 10;k++)
2018 tx2->anim_frames[0][k] = anims[k];
2019 tx2->anim_frames[1][k] = altanims[k];
2023 // if there really is an alternate anim...
2024 if (anims[0] != altanims[0])
2026 // link together the alternate animation
2027 for (j = 0;j < altmax;j++)
2030 tx2->animated = 1; // q1bsp
2031 // the primary/alternate are reversed here
2032 tx2->anim_total[0] = altmax;
2033 tx2->anim_total[1] = max;
2034 for (k = 0;k < 10;k++)
2036 tx2->anim_frames[0][k] = altanims[k];
2037 tx2->anim_frames[1][k] = anims[k];
2044 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2047 unsigned char *in, *out, *data, d;
2048 char litfilename[MAX_QPATH];
2049 char dlitfilename[MAX_QPATH];
2050 fs_offset_t filesize;
2051 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2053 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2054 for (i = 0;i < sb->cursize;i++)
2055 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2057 else // LordHavoc: bsp version 29 (normal white lighting)
2059 // LordHavoc: hope is not lost yet, check for a .lit file to load
2060 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2061 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2062 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2063 strlcat (litfilename, ".lit", sizeof (litfilename));
2064 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2065 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2068 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2070 i = LittleLong(((int *)data)[1]);
2073 if (developer_loading.integer)
2074 Con_Printf("loaded %s\n", litfilename);
2075 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2076 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2078 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2081 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2083 i = LittleLong(((int *)data)[1]);
2086 if (developer_loading.integer)
2087 Con_Printf("loaded %s\n", dlitfilename);
2088 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2089 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2090 loadmodel->brushq3.deluxemapping_modelspace = false;
2091 loadmodel->brushq3.deluxemapping = true;
2100 Con_Printf("Unknown .lit file version (%d)\n", i);
2102 else if (filesize == 8)
2103 Con_Print("Empty .lit file, ignoring\n");
2105 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2112 // LordHavoc: oh well, expand the white lighting data
2115 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2117 out = loadmodel->brushq1.lightdata;
2118 for (i = 0;i < sb->cursize;i++)
2128 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2130 loadmodel->brushq1.num_compressedpvs = 0;
2131 loadmodel->brushq1.data_compressedpvs = NULL;
2134 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2135 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2136 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2139 // used only for HalfLife maps
2140 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2142 char key[128], value[4096];
2146 if (!COM_ParseToken_Simple(&data, false, false, true))
2148 if (com_token[0] != '{')
2152 if (!COM_ParseToken_Simple(&data, false, false, true))
2154 if (com_token[0] == '}')
2155 break; // end of worldspawn
2156 if (com_token[0] == '_')
2157 strlcpy(key, com_token + 1, sizeof(key));
2159 strlcpy(key, com_token, sizeof(key));
2160 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2161 key[strlen(key)-1] = 0;
2162 if (!COM_ParseToken_Simple(&data, false, false, true))
2164 dpsnprintf(value, sizeof(value), "%s", com_token);
2165 if (!strcmp("wad", key)) // for HalfLife maps
2167 if (loadmodel->brush.ishlbsp)
2170 for (i = 0;i < (int)sizeof(value);i++)
2171 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2173 if (i < (int)sizeof(value) && value[i])
2175 for (;i < (int)sizeof(value);i++)
2177 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2178 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2180 else if (value[i] == ';' || value[i] == 0)
2184 W_LoadTextureWadFile(&value[j], false);
2196 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2198 loadmodel->brush.entities = NULL;
2201 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2202 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2203 loadmodel->brush.entities[sb->cursize] = 0;
2204 if (loadmodel->brush.ishlbsp)
2205 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2209 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2213 int structsize = 12;
2215 if (sb->cursize % structsize)
2216 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2217 count = sb->cursize / structsize;
2218 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2220 loadmodel->brushq1.vertexes = out;
2221 loadmodel->brushq1.numvertexes = count;
2223 for ( i=0 ; i<count ; i++, out++)
2225 out->position[0] = MSG_ReadLittleFloat(sb);
2226 out->position[1] = MSG_ReadLittleFloat(sb);
2227 out->position[2] = MSG_ReadLittleFloat(sb);
2231 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2235 int structsize = (48+4*hullinfo->filehulls);
2237 if (sb->cursize % structsize)
2238 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2240 count = sb->cursize / structsize;
2241 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2243 loadmodel->brushq1.submodels = out;
2244 loadmodel->brush.numsubmodels = count;
2246 for (i = 0; i < count; i++, out++)
2248 // spread out the mins / maxs by a pixel
2249 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2250 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2251 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2252 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2253 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2254 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2255 out->origin[0] = MSG_ReadLittleFloat(sb);
2256 out->origin[1] = MSG_ReadLittleFloat(sb);
2257 out->origin[2] = MSG_ReadLittleFloat(sb);
2258 for (j = 0; j < hullinfo->filehulls; j++)
2259 out->headnode[j] = MSG_ReadLittleLong(sb);
2260 out->visleafs = MSG_ReadLittleLong(sb);
2261 out->firstface = MSG_ReadLittleLong(sb);
2262 out->numfaces = MSG_ReadLittleLong(sb);
2266 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2270 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2272 if (sb->cursize % structsize)
2273 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2274 count = sb->cursize / structsize;
2275 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2277 loadmodel->brushq1.edges = out;
2278 loadmodel->brushq1.numedges = count;
2280 for ( i=0 ; i<count ; i++, out++)
2282 if (loadmodel->brush.isbsp2)
2284 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2285 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2289 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2290 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2292 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2294 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);
2295 if(!loadmodel->brushq1.numvertexes)
2296 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2304 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2307 int i, j, k, count, miptex;
2308 int structsize = 40;
2310 if (sb->cursize % structsize)
2311 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2312 count = sb->cursize / structsize;
2313 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2315 loadmodel->brushq1.texinfo = out;
2316 loadmodel->brushq1.numtexinfo = count;
2318 for (i = 0;i < count;i++, out++)
2320 for (k = 0;k < 2;k++)
2321 for (j = 0;j < 4;j++)
2322 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2324 miptex = MSG_ReadLittleLong(sb);
2325 out->q1flags = MSG_ReadLittleLong(sb);
2327 if (out->q1flags & TEX_SPECIAL)
2329 // if texture chosen is NULL or the shader needs a lightmap,
2330 // force to notexture water shader
2331 out->textureindex = loadmodel->num_textures - 1;
2335 // if texture chosen is NULL, force to notexture
2336 out->textureindex = loadmodel->num_textures - 2;
2338 // see if the specified miptex is valid and try to use it instead
2339 if (loadmodel->data_textures)
2341 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2342 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2344 out->textureindex = miptex;
2350 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2355 mins[0] = mins[1] = mins[2] = 9999;
2356 maxs[0] = maxs[1] = maxs[2] = -9999;
2358 for (i = 0;i < numverts;i++)
2360 for (j = 0;j < 3;j++, v++)
2370 #define MAX_SUBDIVPOLYTRIANGLES 4096
2371 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2373 static int subdivpolyverts, subdivpolytriangles;
2374 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2375 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2377 static int subdivpolylookupvert(vec3_t v)
2380 for (i = 0;i < subdivpolyverts;i++)
2381 if (subdivpolyvert[i][0] == v[0]
2382 && subdivpolyvert[i][1] == v[1]
2383 && subdivpolyvert[i][2] == v[2])
2385 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2386 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2387 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2388 return subdivpolyverts++;
2391 static void SubdividePolygon(int numverts, float *verts)
2393 int i, i1, i2, i3, f, b, c, p;
2394 vec3_t mins, maxs, front[256], back[256];
2395 float m, *pv, *cv, dist[256], frac;
2398 Host_Error("SubdividePolygon: ran out of verts in buffer");
2400 BoundPoly(numverts, verts, mins, maxs);
2402 for (i = 0;i < 3;i++)
2404 m = (mins[i] + maxs[i]) * 0.5;
2405 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2406 if (maxs[i] - m < 8)
2408 if (m - mins[i] < 8)
2412 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2413 dist[c] = cv[i] - m;
2416 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2420 VectorCopy(pv, front[f]);
2425 VectorCopy(pv, back[b]);
2428 if (dist[p] == 0 || dist[c] == 0)
2430 if ((dist[p] > 0) != (dist[c] > 0) )
2433 frac = dist[p] / (dist[p] - dist[c]);
2434 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2435 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2436 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2442 SubdividePolygon(f, front[0]);
2443 SubdividePolygon(b, back[0]);
2447 i1 = subdivpolylookupvert(verts);
2448 i2 = subdivpolylookupvert(verts + 3);
2449 for (i = 2;i < numverts;i++)
2451 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2453 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2457 i3 = subdivpolylookupvert(verts + i * 3);
2458 subdivpolyindex[subdivpolytriangles][0] = i1;
2459 subdivpolyindex[subdivpolytriangles][1] = i2;
2460 subdivpolyindex[subdivpolytriangles][2] = i3;
2462 subdivpolytriangles++;
2466 //Breaks a polygon up along axial 64 unit
2467 //boundaries so that turbulent and sky warps
2468 //can be done reasonably.
2469 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2475 subdivpolytriangles = 0;
2476 subdivpolyverts = 0;
2477 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2478 if (subdivpolytriangles < 1)
2479 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2481 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2482 mesh->num_vertices = subdivpolyverts;
2483 mesh->num_triangles = subdivpolytriangles;
2484 mesh->vertex = (surfvertex_t *)(mesh + 1);
2485 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2486 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2488 for (i = 0;i < mesh->num_triangles;i++)
2489 for (j = 0;j < 3;j++)
2490 mesh->index[i*3+j] = subdivpolyindex[i][j];
2492 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2494 VectorCopy(subdivpolyvert[i], v->v);
2495 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2496 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2501 extern cvar_t gl_max_lightmapsize;
2502 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2504 msurface_t *surface;
2505 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2506 float texmins[2], texmaxs[2], val;
2507 rtexture_t *lightmaptexture, *deluxemaptexture;
2509 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2511 if (sb->cursize % structsize)
2512 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2513 count = sb->cursize / structsize;
2514 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2515 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2517 loadmodel->num_surfaces = count;
2519 loadmodel->brushq1.firstrender = true;
2520 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2524 for (surfacenum = 0;surfacenum < count;surfacenum++)
2526 if (loadmodel->brush.isbsp2)
2527 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2529 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2530 totalverts += numedges;
2531 totaltris += numedges - 2;
2534 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2536 lightmaptexture = NULL;
2537 deluxemaptexture = r_texture_blanknormalmap;
2539 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2540 totallightmapsamples = 0;
2544 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2546 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2547 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2548 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2549 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2550 firstedge = MSG_ReadLittleLong(sb);
2551 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2552 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2553 for (i = 0;i < MAXLIGHTMAPS;i++)
2554 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2555 lightmapoffset = MSG_ReadLittleLong(sb);
2557 // FIXME: validate edges, texinfo, etc?
2558 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)
2559 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2560 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2561 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2562 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2563 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2565 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2566 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2568 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2569 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2570 lightmapoffset = -1;
2572 //surface->flags = surface->texture->flags;
2573 //if (LittleShort(in->side))
2574 // surface->flags |= SURF_PLANEBACK;
2575 //surface->plane = loadmodel->brush.data_planes + planenum;
2577 surface->num_firstvertex = totalverts;
2578 surface->num_vertices = numedges;
2579 surface->num_firsttriangle = totaltris;
2580 surface->num_triangles = numedges - 2;
2581 totalverts += numedges;
2582 totaltris += numedges - 2;
2584 // convert edges back to a normal polygon
2585 for (i = 0;i < surface->num_vertices;i++)
2587 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2589 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2591 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2593 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2594 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2595 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2596 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2597 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2598 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2599 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2600 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2603 for (i = 0;i < surface->num_triangles;i++)
2605 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2606 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2607 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2610 // compile additional data about the surface geometry
2611 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);
2612 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);
2613 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2615 // generate surface extents information
2616 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2617 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2618 for (i = 1;i < surface->num_vertices;i++)
2620 for (j = 0;j < 2;j++)
2622 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2623 texmins[j] = min(texmins[j], val);
2624 texmaxs[j] = max(texmaxs[j], val);
2627 for (i = 0;i < 2;i++)
2629 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2630 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2633 smax = surface->lightmapinfo->extents[0] >> 4;
2634 tmax = surface->lightmapinfo->extents[1] >> 4;
2635 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2636 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2639 surface->lightmaptexture = NULL;
2640 surface->deluxemaptexture = r_texture_blanknormalmap;
2641 if (lightmapoffset == -1)
2643 surface->lightmapinfo->samples = NULL;
2645 // give non-lightmapped water a 1x white lightmap
2646 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2648 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2649 surface->lightmapinfo->styles[0] = 0;
2650 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2654 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
2655 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2656 else // LordHavoc: white lighting (bsp version 29)
2658 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2659 if (loadmodel->brushq1.nmaplightdata)
2660 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2663 // check if we should apply a lightmap to this
2664 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2666 if (ssize > 256 || tsize > 256)
2667 Host_Error("Bad surface extents");
2669 if (lightmapsize < ssize)
2670 lightmapsize = ssize;
2671 if (lightmapsize < tsize)
2672 lightmapsize = tsize;
2674 totallightmapsamples += ssize*tsize;
2676 // force lightmap upload on first time seeing the surface
2678 // additionally this is used by the later code to see if a
2679 // lightmap is needed on this surface (rather than duplicating the
2681 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2682 loadmodel->lit = true;
2686 // small maps (such as ammo boxes especially) don't need big lightmap
2687 // textures, so this code tries to guess a good size based on
2688 // totallightmapsamples (size of the lightmaps lump basically), as well as
2689 // trying to max out the size if there is a lot of lightmap data to store
2690 // additionally, never choose a lightmapsize that is smaller than the
2691 // largest surface encountered (as it would fail)
2693 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2696 // now that we've decided the lightmap texture size, we can do the rest
2697 if (cls.state != ca_dedicated)
2699 int stainmapsize = 0;
2700 mod_alloclightmap_state_t allocState;
2702 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2703 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2705 int iu, iv, lightmapx = 0, lightmapy = 0;
2706 float u, v, ubase, vbase, uscale, vscale;
2708 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2711 smax = surface->lightmapinfo->extents[0] >> 4;
2712 tmax = surface->lightmapinfo->extents[1] >> 4;
2713 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2714 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2715 stainmapsize += ssize * tsize * 3;
2717 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2719 // allocate a texture pool if we need it
2720 if (loadmodel->texturepool == NULL)
2721 loadmodel->texturepool = R_AllocTexturePool();
2722 // could not find room, make a new lightmap
2723 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2724 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2725 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2726 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);
2727 if (loadmodel->brushq1.nmaplightdata)
2728 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);
2730 Mod_AllocLightmap_Reset(&allocState);
2731 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2733 surface->lightmaptexture = lightmaptexture;
2734 surface->deluxemaptexture = deluxemaptexture;
2735 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2736 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2738 uscale = 1.0f / (float)lightmapsize;
2739 vscale = 1.0f / (float)lightmapsize;
2740 ubase = lightmapx * uscale;
2741 vbase = lightmapy * vscale;
2743 for (i = 0;i < surface->num_vertices;i++)
2745 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);
2746 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);
2747 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2748 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2749 // LordHavoc: calc lightmap data offset for vertex lighting to use
2752 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2756 if (cl_stainmaps.integer)
2758 // allocate stainmaps for permanent marks on walls and clear white
2759 unsigned char *stainsamples = NULL;
2760 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2761 memset(stainsamples, 255, stainmapsize);
2763 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2765 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2767 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2768 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2769 surface->lightmapinfo->stainsamples = stainsamples;
2770 stainsamples += ssize * tsize * 3;
2775 // generate ushort elements array if possible
2776 if (loadmodel->surfmesh.data_element3s)
2777 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2778 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2781 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2784 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2785 node->parent = parent;
2788 // this is a node, recurse to children
2789 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2790 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2791 // combine supercontents of children
2792 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2797 mleaf_t *leaf = (mleaf_t *)node;
2798 // if this is a leaf, calculate supercontents mask from all collidable
2799 // primitives in the leaf (brushes and collision surfaces)
2800 // also flag if the leaf contains any collision surfaces
2801 leaf->combinedsupercontents = 0;
2802 // combine the supercontents values of all brushes in this leaf
2803 for (j = 0;j < leaf->numleafbrushes;j++)
2804 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2805 // check if this leaf contains any collision surfaces (q3 patches)
2806 for (j = 0;j < leaf->numleafsurfaces;j++)
2808 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2809 if (surface->num_collisiontriangles)
2811 leaf->containscollisionsurfaces = true;
2812 leaf->combinedsupercontents |= surface->texture->supercontents;
2818 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2820 int i, j, count, p, child[2];
2822 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2824 if (sb->cursize % structsize)
2825 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2826 count = sb->cursize / structsize;
2828 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2829 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2831 loadmodel->brush.data_nodes = out;
2832 loadmodel->brush.num_nodes = count;
2834 for ( i=0 ; i<count ; i++, out++)
2836 p = MSG_ReadLittleLong(sb);
2837 out->plane = loadmodel->brush.data_planes + p;
2839 if (loadmodel->brush.isbsp2rmqe)
2841 child[0] = MSG_ReadLittleLong(sb);
2842 child[1] = MSG_ReadLittleLong(sb);
2843 out->mins[0] = MSG_ReadLittleShort(sb);
2844 out->mins[1] = MSG_ReadLittleShort(sb);
2845 out->mins[2] = MSG_ReadLittleShort(sb);
2846 out->maxs[0] = MSG_ReadLittleShort(sb);
2847 out->maxs[1] = MSG_ReadLittleShort(sb);
2848 out->maxs[2] = MSG_ReadLittleShort(sb);
2849 out->firstsurface = MSG_ReadLittleLong(sb);
2850 out->numsurfaces = MSG_ReadLittleLong(sb);
2852 else if (loadmodel->brush.isbsp2)
2854 child[0] = MSG_ReadLittleLong(sb);
2855 child[1] = MSG_ReadLittleLong(sb);
2856 out->mins[0] = MSG_ReadLittleFloat(sb);
2857 out->mins[1] = MSG_ReadLittleFloat(sb);
2858 out->mins[2] = MSG_ReadLittleFloat(sb);
2859 out->maxs[0] = MSG_ReadLittleFloat(sb);
2860 out->maxs[1] = MSG_ReadLittleFloat(sb);
2861 out->maxs[2] = MSG_ReadLittleFloat(sb);
2862 out->firstsurface = MSG_ReadLittleLong(sb);
2863 out->numsurfaces = MSG_ReadLittleLong(sb);
2867 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2868 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2869 if (child[0] >= count)
2871 if (child[1] >= count)
2874 out->mins[0] = MSG_ReadLittleShort(sb);
2875 out->mins[1] = MSG_ReadLittleShort(sb);
2876 out->mins[2] = MSG_ReadLittleShort(sb);
2877 out->maxs[0] = MSG_ReadLittleShort(sb);
2878 out->maxs[1] = MSG_ReadLittleShort(sb);
2879 out->maxs[2] = MSG_ReadLittleShort(sb);
2881 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2882 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2885 for (j=0 ; j<2 ; j++)
2887 // LordHavoc: this code supports broken bsp files produced by
2888 // arguire qbsp which can produce more than 32768 nodes, any value
2889 // below count is assumed to be a node number, any other value is
2890 // assumed to be a leaf number
2894 if (p < loadmodel->brush.num_nodes)
2895 out->children[j] = loadmodel->brush.data_nodes + p;
2898 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2899 // map it to the solid leaf
2900 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2905 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2907 if (p < loadmodel->brush.num_leafs)
2908 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2911 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2912 // map it to the solid leaf
2913 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2919 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2922 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2925 int i, j, count, p, firstmarksurface, nummarksurfaces;
2926 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2928 if (sb->cursize % structsize)
2929 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2930 count = sb->cursize / structsize;
2931 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2933 loadmodel->brush.data_leafs = out;
2934 loadmodel->brush.num_leafs = count;
2935 // get visleafs from the submodel data
2936 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2937 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2938 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2939 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2941 // FIXME: this function could really benefit from some error checking
2942 for ( i=0 ; i<count ; i++, out++)
2944 out->contents = MSG_ReadLittleLong(sb);
2946 out->clusterindex = i - 1;
2947 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2948 out->clusterindex = -1;
2950 p = MSG_ReadLittleLong(sb);
2951 // ignore visofs errors on leaf 0 (solid)
2952 if (p >= 0 && out->clusterindex >= 0)
2954 if (p >= loadmodel->brushq1.num_compressedpvs)
2955 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2957 Mod_Q1BSP_DecompressVis(loadmodel->brushq1.data_compressedpvs + p, loadmodel->brushq1.data_compressedpvs + loadmodel->brushq1.num_compressedpvs, loadmodel->brush.data_pvsclusters + out->clusterindex * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (out->clusterindex + 1) * loadmodel->brush.num_pvsclusterbytes);
2960 if (loadmodel->brush.isbsp2rmqe)
2962 out->mins[0] = MSG_ReadLittleShort(sb);
2963 out->mins[1] = MSG_ReadLittleShort(sb);
2964 out->mins[2] = MSG_ReadLittleShort(sb);
2965 out->maxs[0] = MSG_ReadLittleShort(sb);
2966 out->maxs[1] = MSG_ReadLittleShort(sb);
2967 out->maxs[2] = MSG_ReadLittleShort(sb);
2969 firstmarksurface = MSG_ReadLittleLong(sb);
2970 nummarksurfaces = MSG_ReadLittleLong(sb);
2972 else if (loadmodel->brush.isbsp2)
2974 out->mins[0] = MSG_ReadLittleFloat(sb);
2975 out->mins[1] = MSG_ReadLittleFloat(sb);
2976 out->mins[2] = MSG_ReadLittleFloat(sb);
2977 out->maxs[0] = MSG_ReadLittleFloat(sb);
2978 out->maxs[1] = MSG_ReadLittleFloat(sb);
2979 out->maxs[2] = MSG_ReadLittleFloat(sb);
2981 firstmarksurface = MSG_ReadLittleLong(sb);
2982 nummarksurfaces = MSG_ReadLittleLong(sb);
2986 out->mins[0] = MSG_ReadLittleShort(sb);
2987 out->mins[1] = MSG_ReadLittleShort(sb);
2988 out->mins[2] = MSG_ReadLittleShort(sb);
2989 out->maxs[0] = MSG_ReadLittleShort(sb);
2990 out->maxs[1] = MSG_ReadLittleShort(sb);
2991 out->maxs[2] = MSG_ReadLittleShort(sb);
2993 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2994 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2997 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2999 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3000 out->numleafsurfaces = nummarksurfaces;
3004 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3005 out->firstleafsurface = NULL;
3006 out->numleafsurfaces = 0;
3009 for (j = 0;j < 4;j++)
3010 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3014 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
3018 const unsigned char *pvs;
3019 // if there's no vis data, assume supported (because everything is visible all the time)
3020 if (!loadmodel->brush.data_pvsclusters)
3022 // check all liquid leafs to see if they can see into empty leafs, if any
3023 // can we can assume this map supports r_wateralpha
3024 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3026 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3028 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3029 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3030 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3037 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3042 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3044 if (sb->cursize % structsize)
3045 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3046 count = sb->cursize / structsize;
3047 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3049 loadmodel->brushq1.clipnodes = out;
3050 loadmodel->brushq1.numclipnodes = count;
3052 for (i = 1; i < MAX_MAP_HULLS; i++)
3054 hull = &loadmodel->brushq1.hulls[i];
3055 hull->clipnodes = out;
3056 hull->firstclipnode = 0;
3057 hull->lastclipnode = count-1;
3058 hull->planes = loadmodel->brush.data_planes;
3059 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3060 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3061 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3062 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3063 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3064 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3065 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3068 for (i=0 ; i<count ; i++, out++)
3070 out->planenum = MSG_ReadLittleLong(sb);
3071 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3072 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3073 if (loadmodel->brush.isbsp2)
3075 out->children[0] = MSG_ReadLittleLong(sb);
3076 out->children[1] = MSG_ReadLittleLong(sb);
3077 if (out->children[0] >= count)
3078 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3079 if (out->children[1] >= count)
3080 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3084 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3085 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3086 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3087 if (out->children[0] >= count)
3088 out->children[0] -= 65536;
3089 if (out->children[1] >= count)
3090 out->children[1] -= 65536;
3095 //Duplicate the drawing hull structure as a clipping hull
3096 static void Mod_Q1BSP_MakeHull0(void)
3103 hull = &loadmodel->brushq1.hulls[0];
3105 in = loadmodel->brush.data_nodes;
3106 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3108 hull->clipnodes = out;
3109 hull->firstclipnode = 0;
3110 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3111 hull->planes = loadmodel->brush.data_planes;
3113 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3115 out->planenum = in->plane - loadmodel->brush.data_planes;
3116 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3117 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3121 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3124 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3126 if (sb->cursize % structsize)
3127 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3128 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3129 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3131 if (loadmodel->brush.isbsp2)
3133 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3135 j = MSG_ReadLittleLong(sb);
3136 if (j < 0 || j >= loadmodel->num_surfaces)
3137 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3138 loadmodel->brush.data_leafsurfaces[i] = j;
3143 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3145 j = (unsigned short) MSG_ReadLittleShort(sb);
3146 if (j >= loadmodel->num_surfaces)
3147 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3148 loadmodel->brush.data_leafsurfaces[i] = j;
3153 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3158 if (sb->cursize % structsize)
3159 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3160 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3161 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3163 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3164 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3168 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3172 int structsize = 20;
3174 if (sb->cursize % structsize)
3175 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3176 loadmodel->brush.num_planes = sb->cursize / structsize;
3177 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3179 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3181 out->normal[0] = MSG_ReadLittleFloat(sb);
3182 out->normal[1] = MSG_ReadLittleFloat(sb);
3183 out->normal[2] = MSG_ReadLittleFloat(sb);
3184 out->dist = MSG_ReadLittleFloat(sb);
3185 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3190 static void Mod_Q1BSP_LoadMapBrushes(void)
3194 int submodel, numbrushes;
3195 qboolean firstbrush;
3196 char *text, *maptext;
3197 char mapfilename[MAX_QPATH];
3198 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3199 strlcat (mapfilename, ".map", sizeof (mapfilename));
3200 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3204 if (!COM_ParseToken_Simple(&data, false, false, true))
3209 if (!COM_ParseToken_Simple(&data, false, false, true))
3211 if (com_token[0] != '{')
3217 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3220 if (!COM_ParseToken_Simple(&data, false, false, true))
3222 if (com_token[0] == '}')
3223 break; // end of entity
3224 if (com_token[0] == '{')
3231 if (submodel > loadmodel->brush.numsubmodels)
3233 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3237 model = loadmodel->brush.submodels[submodel];
3244 if (!COM_ParseToken_Simple(&data, false, false, true))
3246 if (com_token[0] == '}')
3247 break; // end of brush
3248 // each brush face should be this format:
3249 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3250 // FIXME: support hl .map format
3251 for (pointnum = 0;pointnum < 3;pointnum++)
3253 COM_ParseToken_Simple(&data, false, false, true);
3254 for (componentnum = 0;componentnum < 3;componentnum++)
3256 COM_ParseToken_Simple(&data, false, false, true);
3257 point[pointnum][componentnum] = atof(com_token);
3259 COM_ParseToken_Simple(&data, false, false, true);
3261 COM_ParseToken_Simple(&data, false, false, true);
3262 strlcpy(facetexture, com_token, sizeof(facetexture));
3263 COM_ParseToken_Simple(&data, false, false, true);
3264 //scroll_s = atof(com_token);
3265 COM_ParseToken_Simple(&data, false, false, true);
3266 //scroll_t = atof(com_token);
3267 COM_ParseToken_Simple(&data, false, false, true);
3268 //rotate = atof(com_token);
3269 COM_ParseToken_Simple(&data, false, false, true);
3270 //scale_s = atof(com_token);
3271 COM_ParseToken_Simple(&data, false, false, true);
3272 //scale_t = atof(com_token);
3273 TriangleNormal(point[0], point[1], point[2], planenormal);
3274 VectorNormalizeDouble(planenormal);
3275 planedist = DotProduct(point[0], planenormal);
3276 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3286 #define MAX_PORTALPOINTS 64
3288 typedef struct portal_s
3291 mnode_t *nodes[2]; // [0] = front side of plane
3292 struct portal_s *next[2];
3294 double points[3*MAX_PORTALPOINTS];
3295 struct portal_s *chain; // all portals are linked into a list
3299 static memexpandablearray_t portalarray;
3301 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3303 // process only nodes (leafs already had their box calculated)
3307 // calculate children first
3308 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3309 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3311 // make combined bounding box from children
3312 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3313 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3314 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3315 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3316 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3317 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3320 static void Mod_Q1BSP_FinalizePortals(void)
3322 int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3326 mleaf_t *leaf, *endleaf;
3328 // tally up portal and point counts and recalculate bounding boxes for all
3329 // leafs (because qbsp is very sloppy)
3330 leaf = loadmodel->brush.data_leafs;
3331 endleaf = leaf + loadmodel->brush.num_leafs;
3332 if (mod_recalculatenodeboxes.integer)
3334 for (;leaf < endleaf;leaf++)
3336 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3337 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3342 for (portalindex = 0;portalindex < portalrange;portalindex++)
3344 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3347 // note: this check must match the one below or it will usually corrupt memory
3348 // 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
3349 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3352 numpoints += p->numpoints * 2;
3355 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3356 loadmodel->brush.num_portals = numportals;
3357 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3358 loadmodel->brush.num_portalpoints = numpoints;
3359 // clear all leaf portal chains
3360 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3361 loadmodel->brush.data_leafs[i].portals = NULL;
3362 // process all portals in the global portal chain, while freeing them
3363 portal = loadmodel->brush.data_portals;
3364 point = loadmodel->brush.data_portalpoints;
3365 for (portalindex = 0;portalindex < portalrange;portalindex++)
3367 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3370 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3372 // note: this check must match the one above or it will usually corrupt memory
3373 // 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
3374 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3376 // first make the back to front portal(forward portal)
3377 portal->points = point;
3378 portal->numpoints = p->numpoints;
3379 portal->plane.dist = p->plane.dist;
3380 VectorCopy(p->plane.normal, portal->plane.normal);
3381 portal->here = (mleaf_t *)p->nodes[1];
3382 portal->past = (mleaf_t *)p->nodes[0];
3384 for (j = 0;j < portal->numpoints;j++)
3386 VectorCopy(p->points + j*3, point->position);
3389 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3390 PlaneClassify(&portal->plane);
3392 // link into leaf's portal chain
3393 portal->next = portal->here->portals;
3394 portal->here->portals = portal;
3396 // advance to next portal
3399 // then make the front to back portal(backward portal)
3400 portal->points = point;
3401 portal->numpoints = p->numpoints;
3402 portal->plane.dist = -p->plane.dist;
3403 VectorNegate(p->plane.normal, portal->plane.normal);
3404 portal->here = (mleaf_t *)p->nodes[0];
3405 portal->past = (mleaf_t *)p->nodes[1];
3407 for (j = portal->numpoints - 1;j >= 0;j--)
3409 VectorCopy(p->points + j*3, point->position);
3412 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3413 PlaneClassify(&portal->plane);
3415 // link into leaf's portal chain
3416 portal->next = portal->here->portals;
3417 portal->here->portals = portal;
3419 // advance to next portal
3422 // add the portal's polygon points to the leaf bounding boxes
3423 if (mod_recalculatenodeboxes.integer)
3425 for (i = 0;i < 2;i++)
3427 leaf = (mleaf_t *)p->nodes[i];
3428 for (j = 0;j < p->numpoints;j++)
3430 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3431 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3432 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3433 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3434 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3435 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3441 // now recalculate the node bounding boxes from the leafs
3442 if (mod_recalculatenodeboxes.integer)
3443 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3451 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3454 Host_Error("AddPortalToNodes: NULL front node");
3456 Host_Error("AddPortalToNodes: NULL back node");
3457 if (p->nodes[0] || p->nodes[1])
3458 Host_Error("AddPortalToNodes: already included");
3459 // 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
3461 p->nodes[0] = front;
3462 p->next[0] = (portal_t *)front->portals;
3463 front->portals = (mportal_t *)p;
3466 p->next[1] = (portal_t *)back->portals;
3467 back->portals = (mportal_t *)p;
3472 RemovePortalFromNode
3475 static void RemovePortalFromNodes(portal_t *portal)
3479 void **portalpointer;
3481 for (i = 0;i < 2;i++)
3483 node = portal->nodes[i];
3485 portalpointer = (void **) &node->portals;
3488 t = (portal_t *)*portalpointer;
3490 Host_Error("RemovePortalFromNodes: portal not in leaf");
3494 if (portal->nodes[0] == node)
3496 *portalpointer = portal->next[0];
3497 portal->nodes[0] = NULL;
3499 else if (portal->nodes[1] == node)
3501 *portalpointer = portal->next[1];
3502 portal->nodes[1] = NULL;
3505 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3509 if (t->nodes[0] == node)
3510 portalpointer = (void **) &t->next[0];
3511 else if (t->nodes[1] == node)
3512 portalpointer = (void **) &t->next[1];
3514 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3519 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3520 static double *portalpointsbuffer;
3521 static int portalpointsbufferoffset;
3522 static int portalpointsbuffersize;
3523 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3526 mnode_t *front, *back, *other_node;
3527 mplane_t clipplane, *plane;
3528 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3529 int numfrontpoints, numbackpoints;
3530 double *frontpoints, *backpoints;
3532 // if a leaf, we're done
3536 // get some space for our clipping operations to use
3537 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3539 portalpointsbuffersize = portalpointsbufferoffset * 2;
3540 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3542 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3543 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3544 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3545 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3547 plane = node->plane;
3549 front = node->children[0];
3550 back = node->children[1];
3552 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3554 // create the new portal by generating a polygon for the node plane,
3555 // and clipping it by all of the other portals(which came from nodes above this one)
3556 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3557 nodeportal->plane = *plane;
3559 // 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)
3560 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);
3561 nodeportal->numpoints = 4;
3562 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3563 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3565 clipplane = portal->plane;
3566 if (portal->nodes[0] == portal->nodes[1])
3567 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3568 if (portal->nodes[0] == node)
3570 else if (portal->nodes[1] == node)
3572 clipplane.dist = -clipplane.dist;
3573 VectorNegate(clipplane.normal, clipplane.normal);
3578 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3579 side = 0; // hush warning
3582 for (i = 0;i < nodeportal->numpoints*3;i++)
3583 frontpoints[i] = nodeportal->points[i];
3584 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);
3585 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3589 if (nodeportal->numpoints < 3)
3591 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3592 nodeportal->numpoints = 0;
3594 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3596 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3597 nodeportal->numpoints = 0;
3600 AddPortalToNodes(nodeportal, front, back);
3602 // split the portals of this node along this node's plane and assign them to the children of this node
3603 // (migrating the portals downward through the tree)
3604 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3606 if (portal->nodes[0] == portal->nodes[1])
3607 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3608 if (portal->nodes[0] == node)
3610 else if (portal->nodes[1] == node)
3614 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3615 side = 0; // hush warning
3617 nextportal = portal->next[side];
3618 if (!portal->numpoints)
3621 other_node = portal->nodes[!side];
3622 RemovePortalFromNodes(portal);
3624 // cut the portal into two portals, one on each side of the node plane
3625 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);
3627 if (!numfrontpoints)
3630 AddPortalToNodes(portal, back, other_node);
3632 AddPortalToNodes(portal, other_node, back);
3638 AddPortalToNodes(portal, front, other_node);
3640 AddPortalToNodes(portal, other_node, front);
3644 // the portal is split
3645 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3646 temp = splitportal->chain;
3647 *splitportal = *portal;
3648 splitportal->chain = temp;
3649 for (i = 0;i < numbackpoints*3;i++)
3650 splitportal->points[i] = backpoints[i];
3651 splitportal->numpoints = numbackpoints;
3652 for (i = 0;i < numfrontpoints*3;i++)
3653 portal->points[i] = frontpoints[i];
3654 portal->numpoints = numfrontpoints;
3658 AddPortalToNodes(portal, front, other_node);
3659 AddPortalToNodes(splitportal, back, other_node);
3663 AddPortalToNodes(portal, other_node, front);
3664 AddPortalToNodes(splitportal, other_node, back);
3668 Mod_Q1BSP_RecursiveNodePortals(front);
3669 Mod_Q1BSP_RecursiveNodePortals(back);
3671 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3674 static void Mod_Q1BSP_MakePortals(void)
3676 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3677 portalpointsbufferoffset = 0;
3678 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3679 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3680 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3681 Mem_Free(portalpointsbuffer);
3682 portalpointsbuffer = NULL;
3683 portalpointsbufferoffset = 0;
3684 portalpointsbuffersize = 0;
3685 Mod_Q1BSP_FinalizePortals();
3686 Mem_ExpandableArray_FreeArray(&portalarray);
3689 //Returns PVS data for a given point
3690 //(note: can return NULL)
3691 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3694 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3696 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3697 if (((mleaf_t *)node)->clusterindex >= 0)
3698 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3703 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
3707 float d = PlaneDiff(org, node->plane);
3709 node = node->children[0];
3710 else if (d < -radius)
3711 node = node->children[1];
3714 // go down both sides
3715 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3716 node = node->children[1];
3719 // if this leaf is in a cluster, accumulate the pvs bits
3720 if (((mleaf_t *)node)->clusterindex >= 0)
3723 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3724 for (i = 0;i < pvsbytes;i++)
3725 pvsbuffer[i] |= pvs[i];
3729 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3730 //of the given point.
3731 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3733 int bytes = model->brush.num_pvsclusterbytes;
3734 bytes = min(bytes, pvsbufferlength);
3735 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3737 memset(pvsbuffer, 0xFF, bytes);
3741 memset(pvsbuffer, 0, bytes);
3742 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3746 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3751 VectorSubtract(inmaxs, inmins, size);
3752 if (cmodel->brush.ishlbsp)
3755 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3756 else if (size[0] <= 32)
3758 if (size[2] < 54) // pick the nearest of 36 or 72
3759 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3761 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3764 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3769 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3770 else if (size[0] <= 32)
3771 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3773 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3775 VectorCopy(inmins, outmins);
3776 VectorAdd(inmins, hull->clip_size, outmaxs);
3779 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3782 int numshadowmeshtriangles = 0;
3783 msurface_t *surface;
3784 if (cls.state == ca_dedicated)
3786 // make a single combined shadow mesh to allow optimized shadow volume creation
3788 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3790 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3791 numshadowmeshtriangles += surface->num_triangles;
3793 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3794 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3795 if (surface->num_triangles > 0)
3796 Mod_ShadowMesh_AddMesh(mod->mempool, mod->brush.shadowmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
3797 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3798 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3799 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3801 return numshadowmeshtriangles;
3804 void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_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);
3806 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3809 sizebuf_t lumpsb[HEADER_LUMPS];
3811 float dist, modelyawradius, modelradius;
3812 msurface_t *surface;
3813 hullinfo_t hullinfo;
3814 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3815 model_brush_lightstyleinfo_t styleinfo[256];
3816 unsigned char *datapointer;
3819 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3821 mod->type = mod_brushq1;
3823 mod->brush.ishlbsp = false;
3824 mod->brush.isbsp2rmqe = false;
3825 mod->brush.isbsp2 = false;
3826 mod->brush.isq2bsp = false;
3827 mod->brush.isq3bsp = false;
3828 mod->brush.skymasking = true;
3829 i = MSG_ReadLittleLong(&sb);
3833 mod->modeldatatypestring = "Q1BSP";
3836 mod->brush.ishlbsp = true;
3837 mod->modeldatatypestring = "HLBSP";
3839 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3840 mod->brush.isbsp2 = true;
3841 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3842 mod->modeldatatypestring = "Q1BSP2rmqe";
3844 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3845 mod->brush.isbsp2 = true;
3846 mod->modeldatatypestring = "Q1BSP2";
3849 mod->modeldatatypestring = "Unknown BSP";
3850 Host_Error("Mod_Q1BSP_Load: %s has wrong version number %i: supported versions are 29 (Quake), 30 (Half-Life), \"BSP2\" or \"2PSB\" (rmqe)", mod->name, i);
3854 // fill in hull info
3855 VectorClear (hullinfo.hullsizes[0][0]);
3856 VectorClear (hullinfo.hullsizes[0][1]);
3857 if (mod->brush.ishlbsp)
3859 hullinfo.filehulls = 4;
3860 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3861 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3862 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3863 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3864 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3865 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3869 hullinfo.filehulls = 4;
3870 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3871 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3872 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3873 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3877 for (i = 0; i < HEADER_LUMPS; i++)
3879 int offset = MSG_ReadLittleLong(&sb);
3880 int size = MSG_ReadLittleLong(&sb);
3881 if (offset < 0 || offset + size > sb.cursize)
3882 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);
3883 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3886 mod->soundfromcenter = true;
3887 mod->TraceBox = Mod_Q1BSP_TraceBox;
3888 mod->TraceLine = Mod_Q1BSP_TraceLine;
3889 mod->TracePoint = Mod_Q1BSP_TracePoint;
3890 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3891 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3892 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3893 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3894 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3895 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3896 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3897 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3898 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3899 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3900 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3901 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3902 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3903 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3904 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3905 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3906 mod->Draw = R_Q1BSP_Draw;
3907 mod->DrawDepth = R_Q1BSP_DrawDepth;
3908 mod->DrawDebug = R_Q1BSP_DrawDebug;
3909 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3910 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3911 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3912 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3913 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3914 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3915 mod->DrawLight = R_Q1BSP_DrawLight;
3919 mod->brush.qw_md4sum = 0;
3920 mod->brush.qw_md4sum2 = 0;
3921 for (i = 0;i < HEADER_LUMPS;i++)
3924 if (i == LUMP_ENTITIES)
3926 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3927 mod->brush.qw_md4sum ^= LittleLong(temp);
3928 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3930 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3933 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3934 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3935 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3936 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3937 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3938 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3939 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3940 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3941 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3942 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3943 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3944 // load submodels before leafs because they contain the number of vis leafs
3945 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3946 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3947 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3948 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3950 for (i = 0; i < HEADER_LUMPS; i++)
3951 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3952 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3954 // check if the map supports transparent water rendering
3955 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3957 // we don't need the compressed pvs data anymore
3958 if (mod->brushq1.data_compressedpvs)
3959 Mem_Free(mod->brushq1.data_compressedpvs);
3960 mod->brushq1.data_compressedpvs = NULL;
3961 mod->brushq1.num_compressedpvs = 0;
3963 Mod_Q1BSP_MakeHull0();
3964 if (mod_bsp_portalize.integer)
3965 Mod_Q1BSP_MakePortals();
3967 mod->numframes = 2; // regular and alternate animation
3970 // make a single combined shadow mesh to allow optimized shadow volume creation
3971 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3973 if (loadmodel->brush.numsubmodels)
3974 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3976 // LordHavoc: to clear the fog around the original quake submodel code, I
3978 // first of all, some background info on the submodels:
3979 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3980 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3981 // now the weird for loop itself:
3982 // the loop functions in an odd way, on each iteration it sets up the
3983 // current 'mod' model (which despite the confusing code IS the model of
3984 // the number i), at the end of the loop it duplicates the model to become
3985 // the next submodel, and loops back to set up the new submodel.
3987 // LordHavoc: now the explanation of my sane way (which works identically):
3988 // set up the world model, then on each submodel copy from the world model
3989 // and set up the submodel with the respective model info.
3990 totalstylesurfaces = 0;
3992 for (i = 0;i < mod->brush.numsubmodels;i++)
3994 memset(stylecounts, 0, sizeof(stylecounts));
3995 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3997 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3998 for (j = 0;j < MAXLIGHTMAPS;j++)
3999 stylecounts[surface->lightmapinfo->styles[j]]++;
4001 for (k = 0;k < 255;k++)
4005 totalstylesurfaces += stylecounts[k];
4008 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4009 for (i = 0;i < mod->brush.numsubmodels;i++)
4011 // LordHavoc: this code was originally at the end of this loop, but
4012 // has been transformed to something more readable at the start here.
4017 // duplicate the basic information
4018 dpsnprintf(name, sizeof(name), "*%i", i);
4019 mod = Mod_FindName(name, loadmodel->name);
4020 // copy the base model to this one
4022 // rename the clone back to its proper name
4023 strlcpy(mod->name, name, sizeof(mod->name));
4024 mod->brush.parentmodel = loadmodel;
4025 // textures and memory belong to the main model
4026 mod->texturepool = NULL;
4027 mod->mempool = NULL;
4028 mod->brush.GetPVS = NULL;
4029 mod->brush.FatPVS = NULL;
4030 mod->brush.BoxTouchingPVS = NULL;
4031 mod->brush.BoxTouchingLeafPVS = NULL;
4032 mod->brush.BoxTouchingVisibleLeafs = NULL;
4033 mod->brush.FindBoxClusters = NULL;
4034 mod->brush.LightPoint = NULL;
4035 mod->brush.AmbientSoundLevelsForPoint = NULL;
4038 mod->brush.submodel = i;
4040 if (loadmodel->brush.submodels)
4041 loadmodel->brush.submodels[i] = mod;
4043 bm = &mod->brushq1.submodels[i];
4045 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4046 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4048 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4049 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4052 mod->firstmodelsurface = bm->firstface;
4053 mod->nummodelsurfaces = bm->numfaces;
4055 // set node/leaf parents for this submodel
4056 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4058 // make the model surface list (used by shadowing/lighting)
4059 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4060 Mod_MakeSortedSurfaces(mod);
4062 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4063 // (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)
4064 VectorCopy(bm->mins, mod->normalmins);
4065 VectorCopy(bm->maxs, mod->normalmaxs);
4066 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4067 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4068 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4069 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4070 modelradius = modelyawradius + modelradius * modelradius;
4071 modelyawradius = sqrt(modelyawradius);
4072 modelradius = sqrt(modelradius);
4073 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4074 mod->yawmins[2] = mod->normalmins[2];
4075 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4076 mod->yawmaxs[2] = mod->normalmaxs[2];
4077 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4078 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4079 mod->radius = modelradius;
4080 mod->radius2 = modelradius * modelradius;
4082 // this gets altered below if sky or water is used
4083 mod->DrawSky = NULL;
4084 mod->DrawAddWaterPlanes = NULL;
4086 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4087 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4088 if (mod->nummodelsurfaces)
4090 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4091 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4093 if (j < mod->nummodelsurfaces)
4094 mod->DrawSky = R_Q1BSP_DrawSky;
4096 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4097 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4099 if (j < mod->nummodelsurfaces)
4100 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4102 // build lightstyle update chains
4103 // (used to rapidly mark lightmapupdateflags on many surfaces
4104 // when d_lightstylevalue changes)
4105 memset(stylecounts, 0, sizeof(stylecounts));
4106 for (k = 0;k < mod->nummodelsurfaces;k++)
4108 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4109 for (j = 0;j < MAXLIGHTMAPS;j++)
4110 stylecounts[surface->lightmapinfo->styles[j]]++;
4112 mod->brushq1.num_lightstyles = 0;
4113 for (k = 0;k < 255;k++)
4117 styleinfo[mod->brushq1.num_lightstyles].style = k;
4118 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4119 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4120 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4121 remapstyles[k] = mod->brushq1.num_lightstyles;
4122 mod->brushq1.num_lightstyles++;
4125 for (k = 0;k < mod->nummodelsurfaces;k++)
4127 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4128 for (j = 0;j < MAXLIGHTMAPS;j++)
4130 if (surface->lightmapinfo->styles[j] != 255)
4132 int r = remapstyles[surface->lightmapinfo->styles[j]];
4133 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4137 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4138 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4142 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4143 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4145 //mod->brushq1.num_visleafs = bm->visleafs;
4147 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4148 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4150 if (mod_q1bsp_polygoncollisions.integer)
4152 mod->collision_bih = mod->render_bih;
4153 // point traces and contents checks still use the bsp tree
4154 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4155 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4156 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4157 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4160 // generate VBOs and other shared data before cloning submodels
4164 Mod_Q1BSP_LoadMapBrushes();
4165 //Mod_Q1BSP_ProcessLightList();
4169 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);
4172 int Mod_Q2BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
4174 int supercontents = 0;
4175 if (nativecontents & CONTENTSQ2_SOLID)
4176 supercontents |= SUPERCONTENTS_SOLID;
4177 if (nativecontents & CONTENTSQ2_WATER)
4178 supercontents |= SUPERCONTENTS_WATER;
4179 if (nativecontents & CONTENTSQ2_SLIME)
4180 supercontents |= SUPERCONTENTS_SLIME;
4181 if (nativecontents & CONTENTSQ2_LAVA)
4182 supercontents |= SUPERCONTENTS_LAVA;
4183 if (nativecontents & CONTENTSQ2_MONSTER)
4184 supercontents |= SUPERCONTENTS_BODY;
4185 if (nativecontents & CONTENTSQ2_DEADMONSTER)
4186 supercontents |= SUPERCONTENTS_CORPSE;
4187 if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4188 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4189 if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4190 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4191 if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4192 supercontents |= SUPERCONTENTS_OPAQUE;
4193 return supercontents;
4196 int Mod_Q2BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
4198 int nativecontents = 0;
4199 if (supercontents & SUPERCONTENTS_SOLID)
4200 nativecontents |= CONTENTSQ2_SOLID;
4201 if (supercontents & SUPERCONTENTS_WATER)
4202 nativecontents |= CONTENTSQ2_WATER;
4203 if (supercontents & SUPERCONTENTS_SLIME)
4204 nativecontents |= CONTENTSQ2_SLIME;
4205 if (supercontents & SUPERCONTENTS_LAVA)
4206 nativecontents |= CONTENTSQ2_LAVA;
4207 if (supercontents & SUPERCONTENTS_BODY)
4208 nativecontents |= CONTENTSQ2_MONSTER;
4209 if (supercontents & SUPERCONTENTS_CORPSE)
4210 nativecontents |= CONTENTSQ2_DEADMONSTER;
4211 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4212 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4213 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4214 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4215 if (!(supercontents & SUPERCONTENTS_OPAQUE))
4216 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4217 return nativecontents;
4220 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4223 loadmodel->brushq1.num_compressedpvs = 0;
4224 loadmodel->brushq1.data_compressedpvs = NULL;
4225 loadmodel->brush.num_pvsclusters = 0;
4226 loadmodel->brush.num_pvsclusterbytes = 0;
4227 loadmodel->brush.data_pvsclusters = NULL;
4232 count = MSG_ReadLittleLong(sb);
4233 loadmodel->brush.num_pvsclusters = count;
4234 loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4235 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4236 for (i = 0;i < count;i++)
4238 int pvsofs = MSG_ReadLittleLong(sb);
4239 /*int phsofs = */MSG_ReadLittleLong(sb);
4240 // decompress the vis data for this cluster
4241 // (note this accesses the underlying data store of sb, which is kind of evil)
4242 Mod_Q1BSP_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);
4244 // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4245 sb->readcount = sb->cursize;
4248 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4250 int i, j, count, p, child[2];
4252 int structsize = 28;
4254 if (sb->cursize % structsize)
4255 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4256 count = sb->cursize / structsize;
4258 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4259 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4261 loadmodel->brush.data_nodes = out;
4262 loadmodel->brush.num_nodes = count;
4264 for ( i=0 ; i<count ; i++, out++)
4266 p = MSG_ReadLittleLong(sb);
4267 out->plane = loadmodel->brush.data_planes + p;
4268 child[0] = MSG_ReadLittleLong(sb);
4269 child[1] = MSG_ReadLittleLong(sb);
4270 out->mins[0] = MSG_ReadLittleShort(sb);
4271 out->mins[1] = MSG_ReadLittleShort(sb);
4272 out->mins[2] = MSG_ReadLittleShort(sb);
4273 out->maxs[0] = MSG_ReadLittleShort(sb);
4274 out->maxs[1] = MSG_ReadLittleShort(sb);
4275 out->maxs[2] = MSG_ReadLittleShort(sb);
4276 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4277 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4278 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4280 Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4281 out->firstsurface = 0;
4282 out->numsurfaces = 0;
4284 for (j=0 ; j<2 ; j++)
4289 if (p < loadmodel->brush.num_nodes)
4290 out->children[j] = loadmodel->brush.data_nodes + p;
4293 Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4294 // map it to the solid leaf
4295 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4300 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4302 if (p < loadmodel->brush.num_leafs)
4303 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4306 Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4307 // map it to the solid leaf
4308 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4314 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
4317 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4321 int structsize = 76;
4322 int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4323 char filename[MAX_QPATH];
4325 if (sb->cursize % structsize)
4326 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4327 count = sb->cursize / structsize;
4328 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4329 loadmodel->brushq1.texinfo = out;
4330 loadmodel->brushq1.numtexinfo = count;
4331 loadmodel->num_texturesperskin = 0;
4332 loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4334 for (i = 0;i < count;i++, out++)
4337 for (k = 0;k < 2;k++)
4338 for (j = 0;j < 4;j++)
4339 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4341 out->q2flags = MSG_ReadLittleLong(sb);
4342 out->q2value = MSG_ReadLittleLong(sb);
4343 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4344 out->q2texture[31] = 0; // make absolutely sure it is terminated
4345 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4347 // find an existing match for the texture if possible
4348 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4349 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4350 if (!strcmp(filename, loadmodel->data_textures[j].name)
4351 && out->q2flags == loadmodel->data_textures[j].q2flags
4352 && out->q2value == loadmodel->data_textures[j].q2value)
4354 // if we don't find the texture, store the new texture
4355 if (j == loadmodel->num_texturesperskin)
4357 if (loadmodel->num_texturesperskin < maxtextures)
4359 texture_t *tx = loadmodel->data_textures + j;
4360 int q2flags = out->q2flags;
4361 unsigned char *walfile = NULL;
4362 fs_offset_t walfilesize = 0;
4363 Mod_LoadTextureFromQ3Shader(tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4364 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4365 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4369 LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4379 tx->q2flags = out->q2flags;
4380 tx->q2value = out->q2value;
4381 // also modify the texture to have the correct contents and such based on flags
4382 // note that we create multiple texture_t structures if q2flags differs
4383 if (q2flags & Q2SURF_LIGHT)
4385 // doesn't mean anything to us
4387 if (q2flags & Q2SURF_SLICK)
4389 // would be nice to support...
4391 if (q2flags & Q2SURF_SKY)
4393 // sky is a rather specific thing
4394 q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4395 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
4396 tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4397 tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4399 if (q2flags & Q2SURF_WARP)
4401 // we use a scroll instead of a warp
4402 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4403 // if it's also transparent, we can enable the WATERSHADER
4404 // but we do not set the WATERALPHA flag because we don't
4405 // want to honor r_wateralpha in q2bsp
4406 // (it would go against the artistic intent)
4407 if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4408 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4410 if (q2flags & Q2SURF_TRANS33)
4412 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4413 tx->basealpha = 1.0f / 3.0f;
4414 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4415 if (tx->q2contents & Q2CONTENTS_SOLID)
4416 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4418 if (q2flags & Q2SURF_TRANS66)
4420 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4421 tx->basealpha = 2.0f / 3.0f;
4422 tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4423 if (tx->q2contents & Q2CONTENTS_SOLID)
4424 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4426 if (q2flags & Q2SURF_FLOWING)
4428 tx->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4429 if (q2flags & Q2SURF_WARP)
4430 tx->tcmods[0].parms[0] = -0.5f;
4432 tx->tcmods[0].parms[0] = -1.6f;
4433 tx->tcmods[0].parms[1] = 0.0f;
4435 if (q2flags & Q2SURF_ALPHATEST)
4437 // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4438 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4440 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4442 if (!mod_q2bsp_littransparentsurfaces.integer)
4443 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4445 if (q2flags & Q2SURF_NODRAW)
4447 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4449 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4450 tx->q2contents |= Q2CONTENTS_DETAIL;
4451 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4452 tx->q2contents |= Q2CONTENTS_SOLID;
4453 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4455 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, tx->q2contents);
4456 // set the current values to the base values
4457 tx->currentframe = tx;
4458 tx->currentskinframe = tx->skinframes[0];
4459 tx->currentmaterialflags = tx->basematerialflags;
4460 loadmodel->num_texturesperskin++;
4461 loadmodel->num_textures = loadmodel->num_texturesperskin;
4465 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4466 j = 0; // use first texture and give up
4469 // store the index we found for this texture
4470 out->textureindex = j;
4473 // realloc the textures array now that we know how many we actually need
4474 loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4476 // now assemble the texture chains
4477 // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier
4478 for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4481 texture_t *t = loadmodel->data_textures + out->textureindex;
4482 t->currentframe = t; // fix the reallocated pointer
4484 // if this is not animated, skip it
4485 // if this is already processed, skip it (part of an existing sequence)
4486 if (out->q2nexttexinfo == 0 || t->animated)
4489 // store the array of frames to use
4490 t->animated = 2; // q2bsp animation
4491 t->anim_total[0] = 0;
4492 t->anim_total[1] = 0;
4493 // gather up to 10 frames (we don't support more)
4494 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)
4496 // detect looping and stop there
4497 if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4499 t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4501 // we could look for the +a sequence here if this is the +0 sequence,
4502 // but it seems that quake2 did not implement that (even though the
4503 // files exist in the baseq2 content)
4505 // write the frame sequence to all the textures involved (just like
4506 // in the q1bsp loader)
4508 // note that this can overwrite the rest of the sequence - so if the
4509 // start of a sequence is found later than the other parts of the
4510 // sequence, it will go back and rewrite them correctly.
4511 for (k = 0;k < t->anim_total[0];k++)
4513 texture_t *txk = t->anim_frames[0][k];
4514 txk->animated = t->animated;
4515 txk->anim_total[0] = t->anim_total[0];
4516 for (l = 0;l < t->anim_total[0];l++)
4517 txk->anim_frames[0][l] = t->anim_frames[0][l];
4522 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4524 // LordHavoc: this fits exactly the same format that we use in .lit files
4525 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4526 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4529 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4532 int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4533 int structsize = 28;
4535 if (sb->cursize % structsize)
4536 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4537 count = sb->cursize / structsize;
4538 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4540 loadmodel->brush.data_leafs = out;
4541 loadmodel->brush.num_leafs = count;
4543 // FIXME: this function could really benefit from some error checking
4544 for ( i=0 ; i<count ; i++, out++)
4546 out->contents = MSG_ReadLittleLong(sb);
4547 out->clusterindex = MSG_ReadLittleShort(sb);
4548 out->areaindex = MSG_ReadLittleShort(sb);
4549 out->mins[0] = MSG_ReadLittleShort(sb);
4550 out->mins[1] = MSG_ReadLittleShort(sb);
4551 out->mins[2] = MSG_ReadLittleShort(sb);
4552 out->maxs[0] = MSG_ReadLittleShort(sb);
4553 out->maxs[1] = MSG_ReadLittleShort(sb);
4554 out->maxs[2] = MSG_ReadLittleShort(sb);
4556 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4557 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4558 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4559 nummarkbrushes = (unsigned short)MSG_ReadLittleShort(sb);
4561 for (j = 0;j < 4;j++)
4562 out->ambient_sound_level[j] = 0;
4564 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4566 Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4567 out->clusterindex = -1;
4570 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4572 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4573 out->numleafsurfaces = nummarksurfaces;
4577 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4578 out->firstleafsurface = NULL;
4579 out->numleafsurfaces = 0;
4582 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4584 out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4585 out->numleafbrushes = nummarkbrushes;
4589 Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4590 out->firstleafbrush = NULL;
4591 out->numleafbrushes = 0;
4596 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4601 if (sb->cursize % structsize)
4602 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4603 loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4604 loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4606 for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4608 j = (unsigned short) MSG_ReadLittleShort(sb);
4609 if (j >= loadmodel->brush.num_brushes)
4610 Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4611 loadmodel->brush.data_leafbrushes[i] = j;
4615 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4617 q3mbrushside_t *out;
4621 if (sb->cursize % structsize)
4622 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4623 count = sb->cursize / structsize;
4624 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4626 loadmodel->brush.data_brushsides = out;
4627 loadmodel->brush.num_brushsides = count;
4629 for (i = 0;i < count;i++, out++)
4631 n = (unsigned short)MSG_ReadLittleShort(sb);
4632 if (n < 0 || n >= loadmodel->brush.num_planes)
4633 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4634 out->plane = loadmodel->brush.data_planes + n;
4635 n = MSG_ReadLittleShort(sb);
4638 if (n >= loadmodel->brushq1.numtexinfo)
4639 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4640 out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4644 //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4645 out->texture = &mod_q1bsp_texture_solid;
4650 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4653 int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4654 colplanef_t *planes;
4655 int structsize = 12;
4656 qboolean brushmissingtextures;
4657 int numbrushesmissingtextures = 0;
4658 int numcreatedtextures = 0;
4660 if (sb->cursize % structsize)
4661 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4662 count = sb->cursize / structsize;
4663 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4665 loadmodel->brush.data_brushes = out;
4666 loadmodel->brush.num_brushes = count;
4671 for (i = 0; i < count; i++, out++)
4673 firstside = MSG_ReadLittleLong(sb);
4674 numsides = MSG_ReadLittleLong(sb);
4675 contents = MSG_ReadLittleLong(sb);
4676 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4677 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4679 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4680 out->numbrushsides = numsides;
4681 // convert the contents to our values
4682 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(loadmodel, contents);
4684 // problem: q2bsp brushes have contents but not a texture
4685 // problem: q2bsp brushsides *may* have a texture or may not
4686 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4687 // solution: nasty hacks
4688 brushmissingtextures = false;
4689 out->texture = NULL;
4690 for (j = 0; j < out->numbrushsides; j++)
4692 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4693 brushmissingtextures = true;
4696 // if we can find a matching texture on a brush side we can use it instead of creating one
4697 if (out->firstbrushside[j].texture->supercontents == supercontents)
4698 out->texture = out->firstbrushside[j].texture;
4701 if (brushmissingtextures || out->texture == NULL)
4703 numbrushesmissingtextures++;
4704 // if we didn't find any appropriate texture (matching contents), we'll have to create one
4705 // we could search earlier ones for a matching one but that can be slow
4706 if (out->texture == NULL)
4708 texture_t *validtexture;
4709 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4710 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4711 validtexture->surfaceflags = 0;
4712 validtexture->supercontents = supercontents;
4713 numcreatedtextures++;
4714 out->texture = validtexture;
4716 // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4717 for (j = 0; j < out->numbrushsides; j++)
4718 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4719 out->firstbrushside[j].texture = out->texture;
4722 // make a colbrush from the brush
4724 // make a list of mplane_t structs to construct a colbrush from
4725 if (maxplanes < out->numbrushsides)
4727 maxplanes = out->numbrushsides;
4730 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4732 for (j = 0;j < out->numbrushsides;j++)
4734 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4735 planes[j].dist = out->firstbrushside[j].plane->dist;
4736 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4737 planes[j].texture = out->firstbrushside[j].texture;
4738 q3surfaceflags |= planes[j].q3surfaceflags;
4740 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4742 // this whole loop can take a while (e.g. on redstarrepublic4)
4743 CL_KeepaliveMessage(false);
4747 if (numcreatedtextures)
4748 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);
4751 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4753 // 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)
4754 sb->readcount = sb->cursize;
4757 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4759 // we currently don't use areas, they represent closable doors as vis blockers
4760 sb->readcount = sb->cursize;
4763 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4765 // we currently don't use areas, they represent closable doors as vis blockers
4766 sb->readcount = sb->cursize;
4769 static void Mod_Q2BSP_LoadSubmodels(sizebuf_t *sb)
4773 int structsize = 48;
4775 if (sb->cursize % structsize)
4776 Host_Error ("Mod_Q2BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
4778 count = sb->cursize / structsize;
4779 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
4781 loadmodel->brushq1.submodels = out;
4782 loadmodel->brush.numsubmodels = count;
4784 // this is identical to the q1 submodel structure except for having 1 hull
4785 for (i = 0; i < count; i++, out++)
4787 // spread out the mins / maxs by a pixel
4788 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
4789 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
4790 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
4791 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
4792 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
4793 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
4794 out->origin[0] = MSG_ReadLittleFloat(sb);
4795 out->origin[1] = MSG_ReadLittleFloat(sb);
4796 out->origin[2] = MSG_ReadLittleFloat(sb);
4797 out->headnode[0] = MSG_ReadLittleLong(sb);
4798 out->firstface = MSG_ReadLittleLong(sb);
4799 out->numfaces = MSG_ReadLittleLong(sb);
4803 static void Mod_Q2BSP_FindSubmodelBrushRange_r(dp_model_t *mod, mnode_t *node, int *first, int *last)
4809 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4810 node = node->children[1];
4812 leaf = (mleaf_t*)node;
4813 for (i = 0;i < leaf->numleafbrushes;i++)
4815 int brushnum = leaf->firstleafbrush[i];
4816 if (*first > brushnum)
4818 if (*last < brushnum)
4823 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4826 sizebuf_t lumpsb[Q2HEADER_LUMPS];
4828 float dist, modelyawradius, modelradius;
4829 msurface_t *surface;
4830 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4831 model_brush_lightstyleinfo_t styleinfo[256];
4832 unsigned char *datapointer;
4835 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4837 mod->type = mod_brushq2;
4839 mod->brush.ishlbsp = false;
4840 mod->brush.isbsp2rmqe = false;
4841 mod->brush.isbsp2 = false;
4842 mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4843 mod->brush.isq3bsp = false;
4844 mod->brush.skymasking = true;
4845 mod->modeldatatypestring = "Q2BSP";
4847 i = MSG_ReadLittleLong(&sb);
4848 if (i != Q2BSPMAGIC)
4849 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4851 i = MSG_ReadLittleLong(&sb);
4852 if (i != Q2BSPVERSION)
4853 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4856 for (i = 0; i < Q2HEADER_LUMPS; i++)
4858 int offset = MSG_ReadLittleLong(&sb);
4859 int size = MSG_ReadLittleLong(&sb);
4860 if (offset < 0 || offset + size > sb.cursize)
4861 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);
4862 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4865 mod->soundfromcenter = true;
4866 mod->TracePoint = Mod_CollisionBIH_TracePoint;
4867 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4868 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4869 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4870 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4871 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4872 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4873 mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4874 mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4875 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
4876 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
4877 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
4878 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
4879 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
4880 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
4881 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
4882 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
4883 mod->brush.AmbientSoundLevelsForPoint = NULL;
4884 mod->brush.RoundUpToHullSize = NULL;
4885 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
4886 mod->Draw = R_Q1BSP_Draw;
4887 mod->DrawDepth = R_Q1BSP_DrawDepth;
4888 mod->DrawDebug = R_Q1BSP_DrawDebug;
4889 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
4890 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
4891 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
4892 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
4893 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
4894 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
4895 mod->DrawLight = R_Q1BSP_DrawLight;
4899 mod->brush.qw_md4sum = 0;
4900 mod->brush.qw_md4sum2 = 0;
4901 for (i = 0;i < Q2HEADER_LUMPS;i++)
4904 if (i == Q2LUMP_ENTITIES)
4906 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4907 mod->brush.qw_md4sum ^= LittleLong(temp);
4908 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4910 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4913 // many of these functions are identical to Q1 loaders, so we use those where possible
4914 Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4915 Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4916 Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4917 Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4918 Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4919 Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4920 Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4921 Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4922 Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4923 Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4924 Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4925 Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4926 Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4927 Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4928 Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4929 Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4930 Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4931 Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4932 Mod_Q2BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS]);
4934 for (i = 0; i < Q2HEADER_LUMPS; i++)
4935 if (lumpsb[i].readcount != lumpsb[i].cursize)
4936 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4938 // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4939 // doesn't enable the cvar, just indicates that transparent water is OK
4940 loadmodel->brush.supportwateralpha = true;
4942 // we don't need the compressed pvs data anymore
4943 if (mod->brushq1.data_compressedpvs)
4944 Mem_Free(mod->brushq1.data_compressedpvs);
4945 mod->brushq1.data_compressedpvs = NULL;
4946 mod->brushq1.num_compressedpvs = 0;
4948 // the MakePortals code works fine on the q2bsp data as well
4949 if (mod_bsp_portalize.integer)
4950 Mod_Q1BSP_MakePortals();
4952 mod->numframes = 0; // q2bsp animations are kind of special, frame is unbounded...
4955 // make a single combined shadow mesh to allow optimized shadow volume creation
4956 Mod_Q1BSP_CreateShadowMesh(loadmodel);
4958 if (loadmodel->brush.numsubmodels)
4959 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
4961 totalstylesurfaces = 0;
4963 for (i = 0;i < mod->brush.numsubmodels;i++)
4965 memset(stylecounts, 0, sizeof(stylecounts));
4966 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4968 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4969 for (j = 0;j < MAXLIGHTMAPS;j++)
4970 stylecounts[surface->lightmapinfo->styles[j]]++;
4972 for (k = 0;k < 255;k++)
4976 totalstylesurfaces += stylecounts[k];
4979 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
4980 // set up the world model, then on each submodel copy from the world model
4981 // and set up the submodel with the respective model info.
4983 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4985 mnode_t *rootnode = NULL;
4986 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
4990 // duplicate the basic information
4991 dpsnprintf(name, sizeof(name), "*%i", i);
4992 mod = Mod_FindName(name, loadmodel->name);
4993 // copy the base model to this one
4995 // rename the clone back to its proper name
4996 strlcpy(mod->name, name, sizeof(mod->name));
4997 mod->brush.parentmodel = loadmodel;
4998 // textures and memory belong to the main model
4999 mod->texturepool = NULL;
5000 mod->mempool = NULL;
5001 mod->brush.GetPVS = NULL;
5002 mod->brush.FatPVS = NULL;
5003 mod->brush.BoxTouchingPVS = NULL;
5004 mod->brush.BoxTouchingLeafPVS = NULL;
5005 mod->brush.BoxTouchingVisibleLeafs = NULL;
5006 mod->brush.FindBoxClusters = NULL;
5007 mod->brush.LightPoint = NULL;
5008 mod->brush.AmbientSoundLevelsForPoint = NULL;
5010 mod->brush.submodel = i;
5011 if (loadmodel->brush.submodels)
5012 loadmodel->brush.submodels[i] = mod;
5014 bm = &mod->brushq1.submodels[i];
5016 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5017 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5019 mod->firstmodelsurface = bm->firstface;
5020 mod->nummodelsurfaces = bm->numfaces;
5022 // set node/leaf parents for this submodel
5023 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5024 // (this happens in base3.bsp)
5025 if (bm->headnode[0] >= 0)
5026 rootnode = mod->brush.data_nodes + bm->headnode[0];
5028 rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5029 Mod_Q1BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5031 // make the model surface list (used by shadowing/lighting)
5032 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
5033 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5034 if (firstbrush <= lastbrush)
5036 mod->firstmodelbrush = firstbrush;
5037 mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5041 mod->firstmodelbrush = 0;
5042 mod->nummodelbrushes = 0;
5044 Mod_MakeSortedSurfaces(mod);
5046 VectorCopy(bm->mins, mod->normalmins);
5047 VectorCopy(bm->maxs, mod->normalmaxs);
5048 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5049 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5050 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5051 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5052 modelradius = modelyawradius + modelradius * modelradius;
5053 modelyawradius = sqrt(modelyawradius);
5054 modelradius = sqrt(modelradius);
5055 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5056 mod->yawmins[2] = mod->normalmins[2];
5057 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
5058 mod->yawmaxs[2] = mod->normalmaxs[2];
5059 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5060 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5061 mod->radius = modelradius;
5062 mod->radius2 = modelradius * modelradius;
5064 // this gets altered below if sky or water is used
5065 mod->DrawSky = NULL;
5066 mod->DrawAddWaterPlanes = NULL;
5068 // scan surfaces for sky and water and flag the submodel as possessing these features or not
5069 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5070 if (mod->nummodelsurfaces)
5072 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5073 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
5075 if (j < mod->nummodelsurfaces)
5076 mod->DrawSky = R_Q1BSP_DrawSky;
5078 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
5079 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
5081 if (j < mod->nummodelsurfaces)
5082 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
5084 // build lightstyle update chains
5085 // (used to rapidly mark lightmapupdateflags on many surfaces
5086 // when d_lightstylevalue changes)
5087 memset(stylecounts, 0, sizeof(stylecounts));
5088 for (k = 0;k < mod->nummodelsurfaces;k++)
5090 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5091 for (j = 0;j < MAXLIGHTMAPS;j++)
5092 stylecounts[surface->lightmapinfo->styles[j]]++;
5094 mod->brushq1.num_lightstyles = 0;
5095 for (k = 0;k < 255;k++)
5099 styleinfo[mod->brushq1.num_lightstyles].style = k;
5100 styleinfo[mod->brushq1.num_lightstyles].value = 0;
5101 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5102 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
5103 remapstyles[k] = mod->brushq1.num_lightstyles;
5104 mod->brushq1.num_lightstyles++;
5107 for (k = 0;k < mod->nummodelsurfaces;k++)
5109 surface = mod->data_surfaces + mod->firstmodelsurface + k;
5110 for (j = 0;j < MAXLIGHTMAPS;j++)
5112 if (surface->lightmapinfo->styles[j] != 255)
5114 int r = remapstyles[surface->lightmapinfo->styles[j]];
5115 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
5119 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
5120 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5124 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5126 //mod->brushq1.num_visleafs = bm->visleafs;
5128 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5129 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5131 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5132 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5134 // generate VBOs and other shared data before cloning submodels
5140 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);
5143 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
5144 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
5146 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5149 char key[128], value[MAX_INPUTLINE];
5151 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5152 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5153 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5156 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5157 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5158 loadmodel->brush.entities[l->filelen] = 0;
5159 data = loadmodel->brush.entities;
5160 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5161 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5162 loadmodel->brushq3.deluxemapping = false;
5163 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5167 if (!COM_ParseToken_Simple(&data, false, false, true))
5169 if (com_token[0] == '}')
5170 break; // end of worldspawn
5171 if (com_token[0] == '_')
5172 strlcpy(key, com_token + 1, sizeof(key));
5174 strlcpy(key, com_token, sizeof(key));
5175 while (key[strlen(key)-1] == ' ') // remove trailing spaces
5176 key[strlen(key)-1] = 0;
5177 if (!COM_ParseToken_Simple(&data, false, false, true))
5179 strlcpy(value, com_token, sizeof(value));
5180 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5182 #if _MSC_VER >= 1400
5183 #define sscanf sscanf_s
5186 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5187 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5189 VectorSet(v, 64, 64, 128);
5190 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5191 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]);
5192 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5193 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5196 else if (!strcmp("deluxeMaps", key))
5198 if (!strcmp(com_token, "1"))
5200 loadmodel->brushq3.deluxemapping = true;
5201 loadmodel->brushq3.deluxemapping_modelspace = true;
5203 else if (!strcmp(com_token, "2"))
5205 loadmodel->brushq3.deluxemapping = true;
5206 loadmodel->brushq3.deluxemapping_modelspace = false;
5213 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5219 in = (q3dtexture_t *)(mod_base + l->fileofs);
5220 if (l->filelen % sizeof(*in))
5221 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5222 count = l->filelen / sizeof(*in);
5223 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5225 loadmodel->data_textures = out;
5226 loadmodel->num_textures = count;
5227 loadmodel->num_texturesperskin = loadmodel->num_textures;
5229 for (i = 0;i < count;i++)
5231 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5232 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5233 Mod_LoadTextureFromQ3Shader(out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
5234 // restore the surfaceflags and supercontents
5235 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5236 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
5240 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5246 in = (q3dplane_t *)(mod_base + l->fileofs);
5247 if (l->filelen % sizeof(*in))
5248 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5249 count = l->filelen / sizeof(*in);
5250 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5252 loadmodel->brush.data_planes = out;
5253 loadmodel->brush.num_planes = count;
5255 for (i = 0;i < count;i++, in++, out++)
5257 out->normal[0] = LittleFloat(in->normal[0]);
5258 out->normal[1] = LittleFloat(in->normal[1]);
5259 out->normal[2] = LittleFloat(in->normal[2]);
5260 out->dist = LittleFloat(in->dist);
5265 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5268 q3mbrushside_t *out;
5271 in = (q3dbrushside_t *)(mod_base + l->fileofs);
5272 if (l->filelen % sizeof(*in))
5273 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5274 count = l->filelen / sizeof(*in);
5275 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5277 loadmodel->brush.data_brushsides = out;
5278 loadmodel->brush.num_brushsides = count;
5280 for (i = 0;i < count;i++, in++, out++)
5282 n = LittleLong(in->planeindex);
5283 if (n < 0 || n >= loadmodel->brush.num_planes)
5284 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5285 out->plane = loadmodel->brush.data_planes + n;
5286 n = LittleLong(in->textureindex);
5287 if (n < 0 || n >= loadmodel->num_textures)
5288 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5289 out->texture = loadmodel->data_textures + n;
5293 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5295 q3dbrushside_ig_t *in;
5296 q3mbrushside_t *out;
5299 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5300 if (l->filelen % sizeof(*in))
5301 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5302 count = l->filelen / sizeof(*in);
5303 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5305 loadmodel->brush.data_brushsides = out;
5306 loadmodel->brush.num_brushsides = count;
5308 for (i = 0;i < count;i++, in++, out++)
5310 n = LittleLong(in->planeindex);
5311 if (n < 0 || n >= loadmodel->brush.num_planes)
5312 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5313 out->plane = loadmodel->brush.data_planes + n;
5314 n = LittleLong(in->textureindex);
5315 if (n < 0 || n >= loadmodel->num_textures)
5316 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5317 out->texture = loadmodel->data_textures + n;
5321 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5325 int i, j, n, c, count, maxplanes, q3surfaceflags;
5326 colplanef_t *planes;
5328 in = (q3dbrush_t *)(mod_base + l->fileofs);
5329 if (l->filelen % sizeof(*in))
5330 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5331 count = l->filelen / sizeof(*in);
5332 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5334 loadmodel->brush.data_brushes = out;
5335 loadmodel->brush.num_brushes = count;
5340 for (i = 0;i < count;i++, in++, out++)
5342 n = LittleLong(in->firstbrushside);
5343 c = LittleLong(in->numbrushsides);
5344 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5345 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5346 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5347 out->numbrushsides = c;
5348 n = LittleLong(in->textureindex);
5349 if (n < 0 || n >= loadmodel->num_textures)
5350 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5351 out->texture = loadmodel->data_textures + n;
5353 // make a list of mplane_t structs to construct a colbrush from
5354 if (maxplanes < out->numbrushsides)
5356 maxplanes = out->numbrushsides;
5359 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5362 for (j = 0;j < out->numbrushsides;j++)
5364 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5365 planes[j].dist = out->firstbrushside[j].plane->dist;
5366 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5367 planes[j].texture = out->firstbrushside[j].texture;
5368 q3surfaceflags |= planes[j].q3surfaceflags;
5370 // make the colbrush from the planes
5371 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5373 // this whole loop can take a while (e.g. on redstarrepublic4)
5374 CL_KeepaliveMessage(false);
5380 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5386 in = (q3deffect_t *)(mod_base + l->fileofs);
5387 if (l->filelen % sizeof(*in))
5388 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5389 count = l->filelen / sizeof(*in);
5390 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5392 loadmodel->brushq3.data_effects = out;
5393 loadmodel->brushq3.num_effects = count;
5395 for (i = 0;i < count;i++, in++, out++)
5397 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5398 n = LittleLong(in->brushindex);
5399 if (n >= loadmodel->brush.num_brushes)
5401 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5404 out->brushindex = n;
5405 out->unknown = LittleLong(in->unknown);
5409 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5414 in = (q3dvertex_t *)(mod_base + l->fileofs);
5415 if (l->filelen % sizeof(*in))
5416 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5417 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5418 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5419 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5420 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5421 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5422 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5424 for (i = 0;i < count;i++, in++)
5426 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5427 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5428 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5429 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5430 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5431 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5432 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5433 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5434 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5435 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5436 // svector/tvector are calculated later in face loading
5437 if(mod_q3bsp_sRGBlightmaps.integer)
5439 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5440 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5441 // working like this may be odd, but matches q3map2 -gamma 2.2
5442 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5444 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5445 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5446 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5447 // we fix the brightness consistently via lightmapscale
5451 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5452 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5453 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5458 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5460 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5461 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5462 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5466 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5467 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5468 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5471 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5472 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5473 loadmodel->lit = true;
5477 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5483 in = (int *)(mod_base + l->fileofs);
5484 if (l->filelen % sizeof(int[3]))
5485 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5486 count = l->filelen / sizeof(*in);
5488 if(!loadmodel->brushq3.num_vertices)
5491 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5492 loadmodel->brushq3.num_triangles = 0;
5496 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5497 loadmodel->brushq3.num_triangles = count / 3;
5498 loadmodel->brushq3.data_element3i = out;
5500 for (i = 0;i < count;i++, in++, out++)
5502 *out = LittleLong(*in);
5503 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5505 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5511 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5513 q3dlightmap_t *input_pointer;
5531 int mergedrowsxcolumns;
5536 unsigned char *mergedpixels;
5537 unsigned char *mergeddeluxepixels;
5538 unsigned char *mergebuf;
5539 char mapname[MAX_QPATH];
5541 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5544 // defaults for q3bsp
5551 loadmodel->brushq3.lightmapsize = 128;
5553 if (cls.state == ca_dedicated)
5556 if(mod_q3bsp_nolightmaps.integer)
5562 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5563 if (developer_loading.integer)
5564 Con_Printf("Using internal lightmaps\n");
5565 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5566 if (l->filelen % sizeof(*input_pointer))
5567 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5568 count = l->filelen / sizeof(*input_pointer);
5569 for(i = 0; i < count; ++i)
5570 inpixels[i] = input_pointer[i].rgb;
5574 // no internal lightmaps
5575 // try external lightmaps
5576 if (developer_loading.integer)
5577 Con_Printf("Using external lightmaps\n");
5578 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5579 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5583 // using EXTERNAL lightmaps instead
5584 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5586 Mem_Free(inpixels[0]);
5587 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5597 for(count = 1; ; ++count)
5599 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5600 if(!inpixels[count])
5601 break; // we got all of them
5602 if(image_width != size || image_height != size)
5604 Mem_Free(inpixels[count]);
5605 inpixels[count] = NULL;
5606 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);
5612 loadmodel->brushq3.lightmapsize = size;
5613 loadmodel->brushq3.num_originallightmaps = count;
5615 // now check the surfaces to see if any of them index an odd numbered
5616 // lightmap, if so this is not a deluxemapped bsp file
5618 // also check what lightmaps are actually used, because q3map2 sometimes
5619 // (always?) makes an unused one at the end, which
5620 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5621 // reason when only one lightmap is used, which can throw off the
5622 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5623 // to see if the second lightmap is blank, if so it is not deluxemapped.
5624 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5625 // in Mod_Q3BSP_LoadEntities was failed
5626 if (!loadmodel->brushq3.deluxemapping)
5628 loadmodel->brushq3.deluxemapping = !(count & 1);
5629 loadmodel->brushq3.deluxemapping_modelspace = true;
5631 if (loadmodel->brushq3.deluxemapping)
5633 int facecount = faceslump->filelen / sizeof(q3dface_t);
5634 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5635 for (i = 0;i < facecount;i++)
5637 j = LittleLong(faces[i].lightmapindex);
5640 endlightmap = max(endlightmap, j + 1);
5641 if ((j & 1) || j + 1 >= count)
5643 loadmodel->brushq3.deluxemapping = false;
5650 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5651 // reason when only one lightmap is used, which can throw off the
5652 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5653 // to see if the second lightmap is blank, if so it is not deluxemapped.
5655 // further research has shown q3map2 sometimes creates a deluxemap and two
5656 // blank lightmaps, which must be handled properly as well
5657 if (endlightmap == 1 && count > 1)
5660 for (i = 0;i < size*size;i++)
5662 if (c[bytesperpixel*i + rgbmap[0]])
5664 if (c[bytesperpixel*i + rgbmap[1]])
5666 if (c[bytesperpixel*i + rgbmap[2]])
5671 // all pixels in the unused lightmap were black...
5672 loadmodel->brushq3.deluxemapping = false;
5677 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5679 // figure out what the most reasonable merge power is within limits
5681 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5682 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5684 // figure out how big the merged texture has to be
5685 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5686 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5687 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5689 mergedwidth = mergegoal;
5690 mergedheight = mergegoal;
5691 // choose non-square size (2x1 aspect) if only half the space is used;
5692 // this really only happens when the entire set fits in one texture, if
5693 // there are multiple textures, we don't worry about shrinking the last
5694 // one to fit, because the driver prefers the same texture size on
5695 // consecutive draw calls...
5696 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5699 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5700 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5701 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5702 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5703 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5704 loadmodel->brushq3.num_lightmapmergedheightpower++;
5705 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5707 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5708 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5709 powerxy = powerx+powery;
5710 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5712 mergedcolumns = 1 << powerx;
5713 mergedrows = 1 << powery;
5714 mergedrowsxcolumns = 1 << powerxy;
5716 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5717 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5718 if (loadmodel->brushq3.deluxemapping)
5719 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5721 // allocate a texture pool if we need it
5722 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5723 loadmodel->texturepool = R_AllocTexturePool();
5725 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5726 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5727 for (i = 0;i < count;i++)
5729 // figure out which merged lightmap texture this fits into
5730 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5731 lightmapindex = i >> powerdxy;
5733 // choose the destination address
5734 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5735 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5736 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5737 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);
5739 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5740 for (j = 0;j < size;j++)
5741 for (k = 0;k < size;k++)
5743 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5744 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5745 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5746 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5749 // upload texture if this was the last tile being written to the texture
5750 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5752 if (loadmodel->brushq3.deluxemapping && (i & 1))
5753 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);
5756 if(mod_q3bsp_sRGBlightmaps.integer)
5759 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5761 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5762 // we fix the brightness consistently via lightmapscale
5765 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5766 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);
5770 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5771 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5772 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);
5778 if (mergeddeluxepixels)
5779 Mem_Free(mergeddeluxepixels);
5780 Mem_Free(mergedpixels);
5783 for(i = 0; i < count; ++i)
5784 Mem_Free(inpixels[i]);
5788 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5793 *collisionstride = stride;
5796 cnt = (num_triangles + stride - 1) / stride;
5797 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5798 for(j = 0; j < cnt; ++j)
5800 mins = &((*collisionbbox6f)[6 * j + 0]);
5801 maxs = &((*collisionbbox6f)[6 * j + 3]);
5802 for(k = 0; k < stride; ++k)
5804 tri = j * stride + k;
5805 if(tri >= num_triangles)
5807 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5808 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5809 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5810 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5811 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5812 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5813 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5814 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5815 if(vert[0] < mins[0]) mins[0] = vert[0];
5816 if(vert[1] < mins[1]) mins[1] = vert[1];
5817 if(vert[2] < mins[2]) mins[2] = vert[2];
5818 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5819 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5820 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5821 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5822 if(vert[0] < mins[0]) mins[0] = vert[0];
5823 if(vert[1] < mins[1]) mins[1] = vert[1];
5824 if(vert[2] < mins[2]) mins[2] = vert[2];
5825 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5826 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5827 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5832 *collisionbbox6f = NULL;
5835 typedef struct patchtess_s
5839 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5842 float *originalvertex3f;
5845 #define PATCHTESS_SAME_LODGROUP(a,b) \
5847 (a).lodgroup[0] == (b).lodgroup[0] && \
5848 (a).lodgroup[1] == (b).lodgroup[1] && \
5849 (a).lodgroup[2] == (b).lodgroup[2] && \
5850 (a).lodgroup[3] == (b).lodgroup[3] && \
5851 (a).lodgroup[4] == (b).lodgroup[4] && \
5852 (a).lodgroup[5] == (b).lodgroup[5] \
5855 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5857 q3dface_t *in, *oldin;
5858 msurface_t *out, *oldout;
5859 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;
5860 float lightmaptcbase[2], lightmaptcscale[2];
5861 //int *originalelement3i;
5862 //int *originalneighbor3i;
5863 float *originalvertex3f;
5864 //float *originalsvector3f;
5865 //float *originaltvector3f;
5866 float *originalnormal3f;
5867 float *originalcolor4f;
5868 float *originaltexcoordtexture2f;
5869 float *originaltexcoordlightmap2f;
5870 float *surfacecollisionvertex3f;
5871 int *surfacecollisionelement3i;
5873 patchtess_t *patchtess = NULL;
5874 int patchtesscount = 0;
5877 in = (q3dface_t *)(mod_base + l->fileofs);
5878 if (l->filelen % sizeof(*in))
5879 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5880 count = l->filelen / sizeof(*in);
5881 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5883 loadmodel->data_surfaces = out;
5884 loadmodel->num_surfaces = count;
5887 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5895 for (;i < count;i++, in++, out++)
5897 // check face type first
5898 type = LittleLong(in->type);
5899 if (type != Q3FACETYPE_FLAT
5900 && type != Q3FACETYPE_PATCH
5901 && type != Q3FACETYPE_MESH
5902 && type != Q3FACETYPE_FLARE)
5904 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5908 n = LittleLong(in->textureindex);
5909 if (n < 0 || n >= loadmodel->num_textures)
5911 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5914 out->texture = loadmodel->data_textures + n;
5915 n = LittleLong(in->effectindex);
5916 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5918 if (developer_extra.integer)
5919 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5925 out->effect = loadmodel->brushq3.data_effects + n;
5927 if (cls.state != ca_dedicated)
5929 out->lightmaptexture = NULL;
5930 out->deluxemaptexture = r_texture_blanknormalmap;
5931 n = LittleLong(in->lightmapindex);
5934 else if (n >= loadmodel->brushq3.num_originallightmaps)
5936 if(loadmodel->brushq3.num_originallightmaps != 0)
5937 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5942 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5943 if (loadmodel->brushq3.deluxemapping)
5944 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5945 loadmodel->lit = true;
5949 firstvertex = LittleLong(in->firstvertex);
5950 numvertices = LittleLong(in->numvertices);
5951 firstelement = LittleLong(in->firstelement);
5952 numtriangles = LittleLong(in->numelements) / 3;
5953 if (numtriangles * 3 != LittleLong(in->numelements))
5955 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));
5958 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5960 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);
5963 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5965 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);
5970 case Q3FACETYPE_FLAT:
5971 case Q3FACETYPE_MESH:
5972 // no processing necessary
5974 case Q3FACETYPE_PATCH:
5975 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5976 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5977 if (numvertices != (patchsize[0] * patchsize[1]) || patchsize[0] < 3 || patchsize[1] < 3 || !(patchsize[0] & 1) || !(patchsize[1] & 1) || patchsize[0] * patchsize[1] >= min(r_subdivisions_maxvertices.integer, r_subdivisions_collision_maxvertices.integer))
5979 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5982 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5984 // convert patch to Q3FACETYPE_MESH
5985 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5986 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5987 // bound to user settings
5988 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5989 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5990 // bound to sanity settings
5991 xtess = bound(0, xtess, 1024);
5992 ytess = bound(0, ytess, 1024);
5994 // lower quality collision patches! Same procedure as before, but different cvars
5995 // convert patch to Q3FACETYPE_MESH
5996 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5997 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5998 // bound to user settings
5999 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
6000 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
6001 // bound to sanity settings
6002 cxtess = bound(0, cxtess, 1024);
6003 cytess = bound(0, cytess, 1024);
6005 // store it for the LOD grouping step
6006 patchtess[patchtesscount].info.xsize = patchsize[0];
6007 patchtess[patchtesscount].info.ysize = patchsize[1];
6008 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
6009 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
6010 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
6011 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
6013 patchtess[patchtesscount].surface_id = i;
6014 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
6015 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
6016 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
6017 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
6018 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
6019 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
6020 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
6023 case Q3FACETYPE_FLARE:
6024 if (developer_extra.integer)
6025 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
6029 out->num_vertices = numvertices;
6030 out->num_triangles = numtriangles;
6031 meshvertices += out->num_vertices;
6032 meshtriangles += out->num_triangles;
6035 // Fix patches tesselations so that they make no seams
6039 for(i = 0; i < patchtesscount; ++i)
6041 for(j = i+1; j < patchtesscount; ++j)
6043 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
6046 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
6053 // Calculate resulting number of triangles
6054 collisionvertices = 0;
6055 collisiontriangles = 0;
6056 for(i = 0; i < patchtesscount; ++i)
6058 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
6059 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
6060 numvertices = finalwidth * finalheight;
6061 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6063 oldout[patchtess[i].surface_id].num_vertices = numvertices;
6064 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
6065 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
6066 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
6068 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
6069 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
6070 numvertices = finalwidth * finalheight;
6071 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6073 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6074 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6075 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6076 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6082 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
6083 if (collisiontriangles)
6085 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6086 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6090 collisionvertices = 0;
6091 collisiontriangles = 0;
6092 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6094 if (out->num_vertices < 3 || out->num_triangles < 1)
6097 type = LittleLong(in->type);
6098 firstvertex = LittleLong(in->firstvertex);
6099 firstelement = LittleLong(in->firstelement);
6100 out->num_firstvertex = meshvertices;
6101 out->num_firsttriangle = meshtriangles;
6102 out->num_firstcollisiontriangle = collisiontriangles;
6105 case Q3FACETYPE_FLAT:
6106 case Q3FACETYPE_MESH:
6107 // no processing necessary, except for lightmap merging
6108 for (j = 0;j < out->num_vertices;j++)
6110 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6111 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6112 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6113 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6114 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6115 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6116 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6117 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6118 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6119 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6120 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6121 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6122 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6123 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6125 for (j = 0;j < out->num_triangles*3;j++)
6126 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6128 case Q3FACETYPE_PATCH:
6129 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6130 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6131 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6132 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6133 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6134 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6135 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6137 xtess = ytess = cxtess = cytess = -1;
6138 for(j = 0; j < patchtesscount; ++j)
6139 if(patchtess[j].surface_id == i)
6141 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6142 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6143 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6144 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6149 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
6150 xtess = ytess = cxtess = cytess = 0;
6153 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6154 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6155 finalvertices = finalwidth * finalheight;
6156 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6157 type = Q3FACETYPE_MESH;
6158 // generate geometry
6159 // (note: normals are skipped because they get recalculated)
6160 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6161 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6162 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6163 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6164 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6165 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6167 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);
6169 if (developer_extra.integer)
6171 if (out->num_triangles < finaltriangles)
6172 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);
6174 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);
6176 // q3map does not put in collision brushes for curves... ugh
6177 // build the lower quality collision geometry
6178 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6179 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6180 finalvertices = finalwidth * finalheight;
6181 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6183 // legacy collision geometry implementation
6184 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
6185 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
6186 out->num_collisionvertices = finalvertices;
6187 out->num_collisiontriangles = finaltriangles;
6188 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6189 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
6191 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
6192 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
6194 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
6196 // now optimize the collision mesh by finding triangle bboxes...
6197 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
6198 Mod_Q3BSP_BuildBBoxes(loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle, out->num_triangles, loadmodel->surfmesh.data_vertex3f, &out->deprecatedq3data_bbox6f, &out->deprecatedq3num_bboxstride, mod_q3bsp_curves_stride.integer);
6200 // store collision geometry for BIH collision tree
6201 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6202 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6203 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6204 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6205 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6207 // remove this once the legacy code is removed
6209 int nc = out->num_collisiontriangles;
6211 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6213 if(nc != out->num_collisiontriangles)
6215 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
6220 if (developer_extra.integer)
6221 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);
6223 collisionvertices += finalvertices;
6224 collisiontriangles += out->num_collisiontriangles;
6229 meshvertices += out->num_vertices;
6230 meshtriangles += out->num_triangles;
6231 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6232 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)
6234 if (invalidelements)
6236 Con_Printf("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);
6237 for (j = 0;j < out->num_triangles * 3;j++)
6239 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6240 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)
6241 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6245 // calculate a bounding box
6246 VectorClear(out->mins);
6247 VectorClear(out->maxs);
6248 if (out->num_vertices)
6250 if (cls.state != ca_dedicated && out->lightmaptexture)
6252 // figure out which part of the merged lightmap this fits into
6253 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6254 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6255 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6256 lightmapindex &= mergewidth * mergeheight - 1;
6257 lightmaptcscale[0] = 1.0f / mergewidth;
6258 lightmaptcscale[1] = 1.0f / mergeheight;
6259 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6260 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6261 // modify the lightmap texcoords to match this region of the merged lightmap
6262 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6264 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6265 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6268 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6269 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6270 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6272 out->mins[0] = min(out->mins[0], v[0]);
6273 out->maxs[0] = max(out->maxs[0], v[0]);
6274 out->mins[1] = min(out->mins[1], v[1]);
6275 out->maxs[1] = max(out->maxs[1], v[1]);
6276 out->mins[2] = min(out->mins[2], v[2]);
6277 out->maxs[2] = max(out->maxs[2], v[2]);
6279 out->mins[0] -= 1.0f;
6280 out->mins[1] -= 1.0f;
6281 out->mins[2] -= 1.0f;
6282 out->maxs[0] += 1.0f;
6283 out->maxs[1] += 1.0f;
6284 out->maxs[2] += 1.0f;
6286 // set lightmap styles for consistency with q1bsp
6287 //out->lightmapinfo->styles[0] = 0;
6288 //out->lightmapinfo->styles[1] = 255;
6289 //out->lightmapinfo->styles[2] = 255;
6290 //out->lightmapinfo->styles[3] = 255;
6295 for (;i < count;i++, out++)
6297 if(out->num_vertices && out->num_triangles)
6299 if(out->num_vertices == 0)
6301 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6302 if(out->num_triangles == 0)
6303 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6305 else if(out->num_triangles == 0)
6306 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)",
6307 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6308 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6309 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6312 // for per pixel lighting
6313 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);
6315 // generate ushort elements array if possible
6316 if (loadmodel->surfmesh.data_element3s)
6317 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6318 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6320 // free the no longer needed vertex data
6321 loadmodel->brushq3.num_vertices = 0;
6322 if (loadmodel->brushq3.data_vertex3f)
6323 Mem_Free(loadmodel->brushq3.data_vertex3f);
6324 loadmodel->brushq3.data_vertex3f = NULL;
6325 loadmodel->brushq3.data_normal3f = NULL;
6326 loadmodel->brushq3.data_texcoordtexture2f = NULL;
6327 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6328 loadmodel->brushq3.data_color4f = NULL;
6329 // free the no longer needed triangle data
6330 loadmodel->brushq3.num_triangles = 0;
6331 if (loadmodel->brushq3.data_element3i)
6332 Mem_Free(loadmodel->brushq3.data_element3i);
6333 loadmodel->brushq3.data_element3i = NULL;
6336 Mem_Free(patchtess);
6339 static void Mod_Q3BSP_LoadModels(lump_t *l)
6343 int i, j, n, c, count;
6345 in = (q3dmodel_t *)(mod_base + l->fileofs);
6346 if (l->filelen % sizeof(*in))
6347 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6348 count = l->filelen / sizeof(*in);
6349 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6351 loadmodel->brushq3.data_models = out;
6352 loadmodel->brushq3.num_models = count;
6354 for (i = 0;i < count;i++, in++, out++)
6356 for (j = 0;j < 3;j++)
6358 out->mins[j] = LittleFloat(in->mins[j]);
6359 out->maxs[j] = LittleFloat(in->maxs[j]);
6361 n = LittleLong(in->firstface);
6362 c = LittleLong(in->numfaces);
6363 if (n < 0 || n + c > loadmodel->num_surfaces)
6364 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6367 n = LittleLong(in->firstbrush);
6368 c = LittleLong(in->numbrushes);
6369 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6370 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6371 out->firstbrush = n;
6372 out->numbrushes = c;
6376 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6382 in = (int *)(mod_base + l->fileofs);
6383 if (l->filelen % sizeof(*in))
6384 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6385 count = l->filelen / sizeof(*in);
6386 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6388 loadmodel->brush.data_leafbrushes = out;
6389 loadmodel->brush.num_leafbrushes = count;
6391 for (i = 0;i < count;i++, in++, out++)
6393 n = LittleLong(*in);
6394 if (n < 0 || n >= loadmodel->brush.num_brushes)
6395 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6400 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6406 in = (int *)(mod_base + l->fileofs);
6407 if (l->filelen % sizeof(*in))
6408 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6409 count = l->filelen / sizeof(*in);
6410 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6412 loadmodel->brush.data_leafsurfaces = out;
6413 loadmodel->brush.num_leafsurfaces = count;
6415 for (i = 0;i < count;i++, in++, out++)
6417 n = LittleLong(*in);
6418 if (n < 0 || n >= loadmodel->num_surfaces)
6419 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6424 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6428 int i, j, n, c, count;
6430 in = (q3dleaf_t *)(mod_base + l->fileofs);
6431 if (l->filelen % sizeof(*in))
6432 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6433 count = l->filelen / sizeof(*in);
6434 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6436 loadmodel->brush.data_leafs = out;
6437 loadmodel->brush.num_leafs = count;
6439 for (i = 0;i < count;i++, in++, out++)
6443 out->clusterindex = LittleLong(in->clusterindex);
6444 out->areaindex = LittleLong(in->areaindex);
6445 for (j = 0;j < 3;j++)
6447 // yes the mins/maxs are ints
6448 out->mins[j] = LittleLong(in->mins[j]) - 1;
6449 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6451 n = LittleLong(in->firstleafface);
6452 c = LittleLong(in->numleaffaces);
6453 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6454 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6455 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6456 out->numleafsurfaces = c;
6457 n = LittleLong(in->firstleafbrush);
6458 c = LittleLong(in->numleafbrushes);
6459 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6460 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6461 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6462 out->numleafbrushes = c;
6466 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6472 in = (q3dnode_t *)(mod_base + l->fileofs);
6473 if (l->filelen % sizeof(*in))
6474 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6475 count = l->filelen / sizeof(*in);
6477 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6478 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6480 loadmodel->brush.data_nodes = out;
6481 loadmodel->brush.num_nodes = count;
6483 for (i = 0;i < count;i++, in++, out++)
6486 n = LittleLong(in->planeindex);
6487 if (n < 0 || n >= loadmodel->brush.num_planes)
6488 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6489 out->plane = loadmodel->brush.data_planes + n;
6490 for (j = 0;j < 2;j++)
6492 n = LittleLong(in->childrenindex[j]);
6495 if (n >= loadmodel->brush.num_nodes)
6496 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6497 out->children[j] = loadmodel->brush.data_nodes + n;
6502 if (n >= loadmodel->brush.num_leafs)
6503 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6504 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6507 for (j = 0;j < 3;j++)
6509 // yes the mins/maxs are ints
6510 out->mins[j] = LittleLong(in->mins[j]) - 1;
6511 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6515 // set the parent pointers
6516 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6519 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6522 q3dlightgrid_t *out;
6526 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6527 if (l->filelen % sizeof(*in))
6528 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6529 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6530 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6531 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6532 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6533 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6534 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6535 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6536 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6537 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6538 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6539 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6540 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6541 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6542 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]);
6543 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]);
6545 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6548 if (l->filelen < count * (int)sizeof(*in))
6550 Con_Printf("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]);
6551 return; // ignore the grid if we cannot understand it
6553 if (l->filelen != count * (int)sizeof(*in))
6554 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6555 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6556 loadmodel->brushq3.data_lightgrid = out;
6557 loadmodel->brushq3.num_lightgrid = count;
6558 // no swapping or validation necessary
6559 memcpy(out, in, count * (int)sizeof(*out));
6561 if(mod_q3bsp_sRGBlightmaps.integer)
6563 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6565 // we fix the brightness consistently via lightmapscale
6569 for(i = 0; i < count; ++i)
6571 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6572 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6573 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6574 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6575 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6576 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6582 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6584 for(i = 0; i < count; ++i)
6586 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6587 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6588 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6589 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6590 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6591 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6602 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6607 if (l->filelen == 0)
6610 // unvised maps often have cluster indices even without pvs, so check
6611 // leafs to find real number of clusters
6612 loadmodel->brush.num_pvsclusters = 1;
6613 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6614 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6617 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6618 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6619 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6620 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6624 in = (q3dpvs_t *)(mod_base + l->fileofs);
6626 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6628 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6629 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6630 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6631 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6632 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6633 if (l->filelen < totalchains + (int)sizeof(*in))
6634 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);
6636 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6637 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6640 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6642 int i, j, k, index[3];
6643 float transformed[3], blend1, blend2, blend, stylescale = 1;
6644 q3dlightgrid_t *a, *s;
6646 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6647 switch(vid.renderpath)
6649 case RENDERPATH_GL20:
6650 case RENDERPATH_D3D9:
6651 case RENDERPATH_D3D10:
6652 case RENDERPATH_D3D11:
6653 case RENDERPATH_SOFT:
6654 case RENDERPATH_GLES2:
6655 // LordHavoc: FIXME: is this true?
6656 stylescale = 1; // added while render
6658 case RENDERPATH_GL11:
6659 case RENDERPATH_GL13:
6660 case RENDERPATH_GLES1:
6661 stylescale = r_refdef.scene.rtlightstylevalue[0];
6665 if (!model->brushq3.num_lightgrid)
6667 ambientcolor[0] = stylescale;
6668 ambientcolor[1] = stylescale;
6669 ambientcolor[2] = stylescale;
6673 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6674 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6675 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6676 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6677 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6678 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6679 index[0] = (int)floor(transformed[0]);
6680 index[1] = (int)floor(transformed[1]);
6681 index[2] = (int)floor(transformed[2]);
6682 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6684 // now lerp the values
6685 VectorClear(diffusenormal);
6686 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6687 for (k = 0;k < 2;k++)
6689 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6690 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6692 for (j = 0;j < 2;j++)
6694 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6695 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6697 for (i = 0;i < 2;i++)
6699 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6700 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6702 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6703 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6704 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6705 // this uses the mod_md3_sin table because the values are
6706 // already in the 0-255 range, the 64+ bias fetches a cosine
6707 // instead of a sine value
6708 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6709 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6710 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6711 //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)));
6716 // normalize the light direction before turning
6717 VectorNormalize(diffusenormal);
6718 //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]);
6721 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6724 double midf, mid[3];
6730 // find the point distances
6731 mplane_t *plane = node->plane;
6732 if (plane->type < 3)
6734 t1 = p1[plane->type] - plane->dist;
6735 t2 = p2[plane->type] - plane->dist;
6739 t1 = DotProduct (plane->normal, p1) - plane->dist;
6740 t2 = DotProduct (plane->normal, p2) - plane->dist;
6747 node = node->children[1];
6756 node = node->children[0];
6762 midf = t1 / (t1 - t2);
6763 VectorLerp(p1, midf, p2, mid);
6765 // recurse both sides, front side first
6766 // return 2 if empty is followed by solid (hit something)
6767 // do not return 2 if both are solid or both empty,
6768 // or if start is solid and end is empty
6769 // as these degenerate cases usually indicate the eye is in solid and
6770 // should see the target point anyway
6771 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6774 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6779 return ((mleaf_t *)node)->clusterindex < 0;
6782 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6784 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6787 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
6788 return trace.fraction == 1;
6792 double tracestart[3], traceend[3];
6793 VectorCopy(start, tracestart);
6794 VectorCopy(end, traceend);
6795 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6799 void Mod_CollisionBIH_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask)
6802 const bih_leaf_t *leaf;
6803 const bih_node_t *node;
6804 const colbrushf_t *brush;
6807 int nodestackpos = 0;
6808 int nodestack[1024];
6810 memset(trace, 0, sizeof(*trace));
6811 trace->fraction = 1;
6812 trace->hitsupercontentsmask = hitsupercontentsmask;
6813 trace->skipsupercontentsmask = skipsupercontentsmask;
6815 bih = &model->collision_bih;
6819 nodenum = bih->rootnode;
6820 nodestack[nodestackpos++] = nodenum;
6821 while (nodestackpos)
6823 nodenum = nodestack[--nodestackpos];
6824 node = bih->nodes + nodenum;
6826 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6829 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6831 axis = node->type - BIH_SPLITX;
6832 if (start[axis] >= node->frontmin)
6833 nodestack[nodestackpos++] = node->front;
6834 if (start[axis] <= node->backmax)
6835 nodestack[nodestackpos++] = node->back;
6837 else if (node->type == BIH_UNORDERED)
6839 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6841 leaf = bih->leafs + node->children[axis];
6843 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6849 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6850 Collision_TracePointBrushFloat(trace, start, brush);
6852 case BIH_COLLISIONTRIANGLE:
6853 // collision triangle - skipped because they have no volume
6855 case BIH_RENDERTRIANGLE:
6856 // render triangle - skipped because they have no volume
6864 static void Mod_CollisionBIH_TraceLineShared(dp_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, const bih_t *bih)
6866 const bih_leaf_t *leaf;
6867 const bih_node_t *node;
6868 const colbrushf_t *brush;
6870 const texture_t *texture;
6871 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6872 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6873 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6878 if (VectorCompare(start, end))
6880 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
6884 nodenum = bih->rootnode;
6886 memset(trace, 0, sizeof(*trace));
6887 trace->fraction = 1;
6888 trace->hitsupercontentsmask = hitsupercontentsmask;
6889 trace->skipsupercontentsmask = skipsupercontentsmask;
6892 nodestackline[nodestackpos][0] = start[0];
6893 nodestackline[nodestackpos][1] = start[1];
6894 nodestackline[nodestackpos][2] = start[2];
6895 nodestackline[nodestackpos][3] = end[0];
6896 nodestackline[nodestackpos][4] = end[1];
6897 nodestackline[nodestackpos][5] = end[2];
6898 nodestack[nodestackpos++] = nodenum;
6899 while (nodestackpos)
6901 nodenum = nodestack[--nodestackpos];
6902 node = bih->nodes + nodenum;
6903 VectorCopy(nodestackline[nodestackpos], nodestart);
6904 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6905 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6906 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6907 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6908 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6909 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6910 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6911 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6913 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6915 // recurse children of the split
6916 axis = node->type - BIH_SPLITX;
6917 d1 = node->backmax - nodestart[axis];
6918 d2 = node->backmax - nodeend[axis];
6919 d3 = nodestart[axis] - node->frontmin;
6920 d4 = nodeend[axis] - node->frontmin;
6921 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6923 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;
6924 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;
6925 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;
6926 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6927 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;
6928 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;
6929 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;
6930 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6931 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;
6932 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;
6933 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;
6934 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6935 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6936 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6937 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6938 case 15: /* <<<< */ break;
6941 else if (node->type == BIH_UNORDERED)
6943 // calculate sweep bounds for this node
6944 // copy node bounds into local variables
6945 VectorCopy(node->mins, nodebigmins);
6946 VectorCopy(node->maxs, nodebigmaxs);
6947 // clip line to this node bounds
6948 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); }
6949 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); }
6950 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); }
6951 // some of the line intersected the enlarged node box
6952 // calculate sweep bounds for this node
6953 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6954 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6955 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6956 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6957 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6958 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6959 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6961 leaf = bih->leafs + node->children[axis];
6962 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6967 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6968 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6970 case BIH_COLLISIONTRIANGLE:
6971 if (!mod_q3bsp_curves_collisions.integer)
6973 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6974 texture = model->data_textures + leaf->textureindex;
6975 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);
6977 case BIH_RENDERTRIANGLE:
6978 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6979 texture = model->data_textures + leaf->textureindex;
6980 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);
6988 void Mod_CollisionBIH_TraceLine(dp_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)
6990 if (VectorCompare(start, end))
6992 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
6995 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, &model->collision_bih);
6998 void Mod_CollisionBIH_TraceBrush(dp_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)
7001 const bih_leaf_t *leaf;
7002 const bih_node_t *node;
7003 const colbrushf_t *brush;
7005 const texture_t *texture;
7006 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
7007 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
7008 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
7009 int axis, nodenum, nodestackpos = 0, nodestack[1024];
7011 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
7013 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
7014 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask);
7016 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask);
7020 bih = &model->collision_bih;
7023 nodenum = bih->rootnode;
7025 // box trace, performed as brush trace
7026 memset(trace, 0, sizeof(*trace));
7027 trace->fraction = 1;
7028 trace->hitsupercontentsmask = hitsupercontentsmask;
7029 trace->skipsupercontentsmask = skipsupercontentsmask;
7031 // calculate tracebox-like parameters for efficient culling
7032 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7033 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7034 VectorSubtract(thisbrush_start->mins, start, startmins);
7035 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7036 VectorSubtract(thisbrush_end->mins, end, endmins);
7037 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7038 mins[0] = min(startmins[0], endmins[0]);
7039 mins[1] = min(startmins[1], endmins[1]);
7040 mins[2] = min(startmins[2], endmins[2]);
7041 maxs[0] = max(startmaxs[0], endmaxs[0]);
7042 maxs[1] = max(startmaxs[1], endmaxs[1]);
7043 maxs[2] = max(startmaxs[2], endmaxs[2]);
7046 nodestackline[nodestackpos][0] = start[0];
7047 nodestackline[nodestackpos][1] = start[1];
7048 nodestackline[nodestackpos][2] = start[2];
7049 nodestackline[nodestackpos][3] = end[0];
7050 nodestackline[nodestackpos][4] = end[1];
7051 nodestackline[nodestackpos][5] = end[2];
7052 nodestack[nodestackpos++] = nodenum;
7053 while (nodestackpos)
7055 nodenum = nodestack[--nodestackpos];
7056 node = bih->nodes + nodenum;
7057 VectorCopy(nodestackline[nodestackpos], nodestart);
7058 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7059 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7060 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7061 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7062 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7063 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7064 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7065 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7067 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7069 // recurse children of the split
7070 axis = node->type - BIH_SPLITX;
7071 d1 = node->backmax - nodestart[axis] - mins[axis];
7072 d2 = node->backmax - nodeend[axis] - mins[axis];
7073 d3 = nodestart[axis] - node->frontmin + maxs[axis];
7074 d4 = nodeend[axis] - node->frontmin + maxs[axis];
7075 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7077 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;
7078 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;
7079 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;
7080 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7081 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;
7082 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;
7083 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;
7084 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7085 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;
7086 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;
7087 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;
7088 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7089 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7090 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7091 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
7092 case 15: /* <<<< */ break;
7095 else if (node->type == BIH_UNORDERED)
7097 // calculate sweep bounds for this node
7098 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7099 VectorSubtract(node->mins, maxs, nodebigmins);
7100 VectorSubtract(node->maxs, mins, nodebigmaxs);
7101 // clip line to this node bounds
7102 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); }
7103 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); }
7104 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); }
7105 // some of the line intersected the enlarged node box
7106 // calculate sweep bounds for this node
7107 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7108 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7109 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7110 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7111 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7112 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7113 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7115 leaf = bih->leafs + node->children[axis];
7116 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7121 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7122 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7124 case BIH_COLLISIONTRIANGLE:
7125 if (!mod_q3bsp_curves_collisions.integer)
7127 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7128 texture = model->data_textures + leaf->textureindex;
7129 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);
7131 case BIH_RENDERTRIANGLE:
7132 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7133 texture = model->data_textures + leaf->textureindex;
7134 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);
7142 void Mod_CollisionBIH_TraceBox(dp_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)
7144 colboxbrushf_t thisbrush_start, thisbrush_end;
7145 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7147 // box trace, performed as brush trace
7148 VectorAdd(start, boxmins, boxstartmins);
7149 VectorAdd(start, boxmaxs, boxstartmaxs);
7150 VectorAdd(end, boxmins, boxendmins);
7151 VectorAdd(end, boxmaxs, boxendmaxs);
7152 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7153 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7154 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask);
7158 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7161 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0);
7162 return trace.startsupercontents;
7165 qboolean Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
7168 Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
7169 return trace.fraction == 1;
7172 void Mod_CollisionBIH_TracePoint_Mesh(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask)
7175 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7177 int hitsupercontents;
7178 VectorSet(end, start[0], start[1], model->normalmins[2]);
7180 memset(trace, 0, sizeof(*trace));
7181 trace->fraction = 1;
7182 trace->hitsupercontentsmask = hitsupercontentsmask;
7183 trace->skipsupercontentsmask = skipsupercontentsmask;
7185 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7186 hitsupercontents = trace->hitsupercontents;
7187 memset(trace, 0, sizeof(*trace));
7188 trace->fraction = 1;
7189 trace->hitsupercontentsmask = hitsupercontentsmask;
7190 trace->skipsupercontentsmask = skipsupercontentsmask;
7191 trace->startsupercontents = hitsupercontents;
7195 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7198 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7201 VectorSet(end, start[0], start[1], model->normalmins[2]);
7202 memset(&trace, 0, sizeof(trace));
7204 trace.hitsupercontentsmask = hitsupercontentsmask;
7205 trace.skipsupercontentsmask = skipsupercontentsmask;
7206 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7207 return trace.hitsupercontents;
7213 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
7218 // find which leaf the point is in
7220 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7221 // point trace the brushes
7222 leaf = (mleaf_t *)node;
7223 for (i = 0;i < leaf->numleafbrushes;i++)
7225 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7226 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
7228 brush->markframe = markframe;
7229 Collision_TracePointBrushFloat(trace, point, brush);
7232 // can't do point traces on curves (they have no thickness)
7235 static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t start, const vec3_t end, vec_t startfrac, vec_t endfrac, const vec3_t linestart, const vec3_t lineend, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
7237 int i, startside, endside;
7238 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
7240 msurface_t *surface;
7243 // walk the tree until we hit a leaf, recursing for any split cases
7247 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7249 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7250 node = node->children[1];
7252 // abort if this part of the bsp tree can not be hit by this trace
7253 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7255 plane = node->plane;
7256 // axial planes are much more common than non-axial, so an optimized
7257 // axial case pays off here
7258 if (plane->type < 3)
7260 dist1 = start[plane->type] - plane->dist;
7261 dist2 = end[plane->type] - plane->dist;
7265 dist1 = DotProduct(start, plane->normal) - plane->dist;
7266 dist2 = DotProduct(end, plane->normal) - plane->dist;
7268 startside = dist1 < 0;
7269 endside = dist2 < 0;
7270 if (startside == endside)
7272 // most of the time the line fragment is on one side of the plane
7273 node = node->children[startside];
7277 // line crosses node plane, split the line
7278 dist1 = PlaneDiff(linestart, plane);
7279 dist2 = PlaneDiff(lineend, plane);
7280 midfrac = dist1 / (dist1 - dist2);
7281 VectorLerp(linestart, midfrac, lineend, mid);
7282 // take the near side first
7283 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7284 // if we found an impact on the front side, don't waste time
7285 // exploring the far side
7286 if (midfrac <= trace->fraction)
7287 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
7292 // abort if this part of the bsp tree can not be hit by this trace
7293 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7296 nodesegmentmins[0] = min(start[0], end[0]) - 1;
7297 nodesegmentmins[1] = min(start[1], end[1]) - 1;
7298 nodesegmentmins[2] = min(start[2], end[2]) - 1;
7299 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
7300 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
7301 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
7302 // line trace the brushes
7303 leaf = (mleaf_t *)node;
7305 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7308 for (i = 0;i < leaf->numleafbrushes;i++)
7310 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7311 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7313 brush->markframe = markframe;
7314 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
7317 // can't do point traces on curves (they have no thickness)
7318 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
7320 // line trace the curves
7321 for (i = 0;i < leaf->numleafsurfaces;i++)
7323 surface = model->data_surfaces + leaf->firstleafsurface[i];
7324 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7326 surface->deprecatedq3collisionmarkframe = markframe;
7327 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
7333 static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
7339 msurface_t *surface;
7341 float nodesegmentmins[3], nodesegmentmaxs[3];
7342 // walk the tree until we hit a leaf, recursing for any split cases
7346 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
7348 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7349 node = node->children[1];
7351 // abort if this part of the bsp tree can not be hit by this trace
7352 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7354 plane = node->plane;
7355 // axial planes are much more common than non-axial, so an optimized
7356 // axial case pays off here
7357 if (plane->type < 3)
7359 // this is an axial plane, compare bounding box directly to it and
7360 // recurse sides accordingly
7361 // recurse down node sides
7362 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
7363 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
7364 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
7365 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
7369 // this is a non-axial plane, so check if the start and end boxes
7370 // are both on one side of the plane to handle 'diagonal' cases
7371 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
7375 // segment crosses plane
7376 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
7379 // if sides == 0 then the trace itself is bogus (Not A Number values),
7380 // in this case we simply pretend the trace hit nothing
7382 return; // ERROR: NAN bounding box!
7383 // take whichever side the segment box is on
7384 node = node->children[sides - 1];
7387 // abort if this part of the bsp tree can not be hit by this trace
7388 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
7390 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
7391 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
7392 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
7393 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
7394 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
7395 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
7397 leaf = (mleaf_t *)node;
7399 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
7402 for (i = 0;i < leaf->numleafbrushes;i++)
7404 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
7405 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
7407 brush->markframe = markframe;
7408 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7411 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
7413 for (i = 0;i < leaf->numleafsurfaces;i++)
7415 surface = model->data_surfaces + leaf->firstleafsurface[i];
7416 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
7418 surface->deprecatedq3collisionmarkframe = markframe;
7419 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
7426 static int markframe = 0;
7428 static void Mod_Q3BSP_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask)
7432 memset(trace, 0, sizeof(*trace));
7433 trace->fraction = 1;
7434 trace->hitsupercontentsmask = hitsupercontentsmask;
7435 trace->skipsupercontentsmask = skipsupercontentsmask;
7436 if (mod_collision_bih.integer)
7437 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
7438 else if (model->brush.submodel)
7440 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7441 if (brush->colbrushf)
7442 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
7445 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
7448 static void Mod_Q3BSP_TraceLine(dp_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)
7451 float segmentmins[3], segmentmaxs[3];
7452 msurface_t *surface;
7455 if (VectorCompare(start, end))
7457 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
7461 memset(trace, 0, sizeof(*trace));
7462 trace->fraction = 1;
7463 trace->hitsupercontentsmask = hitsupercontentsmask;
7464 trace->skipsupercontentsmask = skipsupercontentsmask;
7465 segmentmins[0] = min(start[0], end[0]) - 1;
7466 segmentmins[1] = min(start[1], end[1]) - 1;
7467 segmentmins[2] = min(start[2], end[2]) - 1;
7468 segmentmaxs[0] = max(start[0], end[0]) + 1;
7469 segmentmaxs[1] = max(start[1], end[1]) + 1;
7470 segmentmaxs[2] = max(start[2], end[2]) + 1;
7471 if (mod_collision_bih.integer)
7472 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7473 else if (model->brush.submodel)
7475 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7476 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7477 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7478 if (mod_q3bsp_curves_collisions.integer)
7479 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7480 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7481 Collision_TraceLineTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
7484 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
7487 static void Mod_Q3BSP_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *start, colbrushf_t *end, int hitsupercontentsmask, int skipsupercontentsmask)
7489 float segmentmins[3], segmentmaxs[3];
7491 msurface_t *surface;
7494 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
7496 if (VectorCompare(start->mins, end->mins))
7497 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask, skipsupercontentsmask);
7499 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask, skipsupercontentsmask);
7503 // box trace, performed as brush trace
7504 memset(trace, 0, sizeof(*trace));
7505 trace->fraction = 1;
7506 trace->hitsupercontentsmask = hitsupercontentsmask;
7507 trace->skipsupercontentsmask = skipsupercontentsmask;
7508 segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
7509 segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
7510 segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
7511 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
7512 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
7513 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
7514 if (mod_collision_bih.integer)
7515 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
7516 else if (model->brush.submodel)
7518 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7519 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
7520 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
7521 if (mod_q3bsp_curves_collisions.integer)
7522 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
7523 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
7524 Collision_TraceBrushTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
7527 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
7530 static void Mod_Q3BSP_TraceBox(dp_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)
7532 colboxbrushf_t thisbrush_start, thisbrush_end;
7533 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7535 // box trace, performed as brush trace
7536 VectorAdd(start, boxmins, boxstartmins);
7537 VectorAdd(start, boxmaxs, boxstartmaxs);
7538 VectorAdd(end, boxmins, boxendmins);
7539 VectorAdd(end, boxmaxs, boxendmaxs);
7540 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7541 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7542 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask);
7545 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7548 int supercontents = 0;
7550 if (mod_collision_bih.integer)
7552 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
7554 // test if the point is inside each brush
7555 else if (model->brush.submodel)
7557 // submodels are effectively one leaf
7558 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
7559 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7560 supercontents |= brush->colbrushf->supercontents;
7564 mnode_t *node = model->brush.data_nodes;
7566 // find which leaf the point is in
7568 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
7569 leaf = (mleaf_t *)node;
7570 // now check the brushes in the leaf
7571 for (i = 0;i < leaf->numleafbrushes;i++)
7573 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
7574 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7575 supercontents |= brush->colbrushf->supercontents;
7578 return supercontents;
7581 void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_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)
7583 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, &model->render_bih);
7587 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7595 int nummodelbrushes = model->nummodelbrushes;
7596 int nummodelsurfaces = model->nummodelsurfaces;
7598 const int *collisionelement3i;
7599 const float *collisionvertex3f;
7600 const int *renderelement3i;
7601 const float *rendervertex3f;
7602 bih_leaf_t *bihleafs;
7603 bih_node_t *bihnodes;
7605 int *temp_leafsortscratch;
7606 const msurface_t *surface;
7607 const q3mbrush_t *brush;
7609 // find out how many BIH leaf nodes we need
7611 if (userendersurfaces)
7613 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7614 bihnumleafs += surface->num_triangles;
7618 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7619 if (brush->colbrushf)
7621 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7623 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7624 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7626 bihnumleafs += surface->num_collisiontriangles;
7633 // allocate the memory for the BIH leaf nodes
7634 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7636 // now populate the BIH leaf nodes
7639 // add render surfaces
7640 renderelement3i = model->surfmesh.data_element3i;
7641 rendervertex3f = model->surfmesh.data_vertex3f;
7642 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7644 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7646 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7648 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7649 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7650 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7651 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7652 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7653 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7654 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7655 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7656 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7657 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7662 if (!userendersurfaces)
7664 // add collision brushes
7665 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7667 if (!brush->colbrushf)
7669 bihleafs[bihleafindex].type = BIH_BRUSH;
7670 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7671 bihleafs[bihleafindex].surfaceindex = -1;
7672 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7673 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7674 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7678 // add collision surfaces
7679 collisionelement3i = model->brush.data_collisionelement3i;
7680 collisionvertex3f = model->brush.data_collisionvertex3f;
7681 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7683 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7685 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7686 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7687 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7688 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7689 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7690 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7691 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7692 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7693 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7694 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7700 // allocate buffers for the produced and temporary data
7701 bihmaxnodes = bihnumleafs + 1;
7702 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7703 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7704 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7707 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7709 // we're done with the temporary data
7710 Mem_Free(temp_leafsort);
7712 // resize the BIH nodes array if it over-allocated
7713 if (out->maxnodes > out->numnodes)
7715 out->maxnodes = out->numnodes;
7716 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7722 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7724 int supercontents = 0;
7725 if (nativecontents & CONTENTSQ3_SOLID)
7726 supercontents |= SUPERCONTENTS_SOLID;
7727 if (nativecontents & CONTENTSQ3_WATER)
7728 supercontents |= SUPERCONTENTS_WATER;
7729 if (nativecontents & CONTENTSQ3_SLIME)
7730 supercontents |= SUPERCONTENTS_SLIME;
7731 if (nativecontents & CONTENTSQ3_LAVA)
7732 supercontents |= SUPERCONTENTS_LAVA;
7733 if (nativecontents & CONTENTSQ3_BODY)
7734 supercontents |= SUPERCONTENTS_BODY;
7735 if (nativecontents & CONTENTSQ3_CORPSE)
7736 supercontents |= SUPERCONTENTS_CORPSE;
7737 if (nativecontents & CONTENTSQ3_NODROP)
7738 supercontents |= SUPERCONTENTS_NODROP;
7739 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7740 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7741 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7742 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7743 if (nativecontents & CONTENTSQ3_DONOTENTER)
7744 supercontents |= SUPERCONTENTS_DONOTENTER;
7745 if (nativecontents & CONTENTSQ3_BOTCLIP)
7746 supercontents |= SUPERCONTENTS_BOTCLIP;
7747 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7748 supercontents |= SUPERCONTENTS_OPAQUE;
7749 return supercontents;
7752 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7754 int nativecontents = 0;
7755 if (supercontents & SUPERCONTENTS_SOLID)
7756 nativecontents |= CONTENTSQ3_SOLID;
7757 if (supercontents & SUPERCONTENTS_WATER)
7758 nativecontents |= CONTENTSQ3_WATER;
7759 if (supercontents & SUPERCONTENTS_SLIME)
7760 nativecontents |= CONTENTSQ3_SLIME;
7761 if (supercontents & SUPERCONTENTS_LAVA)
7762 nativecontents |= CONTENTSQ3_LAVA;
7763 if (supercontents & SUPERCONTENTS_BODY)
7764 nativecontents |= CONTENTSQ3_BODY;
7765 if (supercontents & SUPERCONTENTS_CORPSE)
7766 nativecontents |= CONTENTSQ3_CORPSE;
7767 if (supercontents & SUPERCONTENTS_NODROP)
7768 nativecontents |= CONTENTSQ3_NODROP;
7769 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7770 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7771 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7772 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7773 if (supercontents & SUPERCONTENTS_DONOTENTER)
7774 nativecontents |= CONTENTSQ3_DONOTENTER;
7775 if (supercontents & SUPERCONTENTS_BOTCLIP)
7776 nativecontents |= CONTENTSQ3_BOTCLIP;
7777 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7778 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7779 return nativecontents;
7782 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7787 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7788 node = node->children[1];
7790 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7791 if (loadmodel->brush.num_leafs < numleafs)
7792 loadmodel->brush.num_leafs = numleafs;
7795 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7798 q3dheader_t *header;
7799 float corner[3], yawradius, modelradius;
7801 mod->modeldatatypestring = "Q3BSP";
7803 mod->type = mod_brushq3;
7804 mod->brush.ishlbsp = false;
7805 mod->brush.isbsp2rmqe = false;
7806 mod->brush.isbsp2 = false;
7807 mod->brush.isq2bsp = false;
7808 mod->brush.isq3bsp = true;
7809 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7812 header = (q3dheader_t *)buffer;
7813 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7814 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7816 i = LittleLong(header->version);
7817 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7818 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7820 mod->soundfromcenter = true;
7821 mod->TraceBox = Mod_Q3BSP_TraceBox;
7822 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7823 mod->TraceLine = Mod_Q3BSP_TraceLine;
7824 mod->TracePoint = Mod_Q3BSP_TracePoint;
7825 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7826 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7827 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7828 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7829 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7830 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7831 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7832 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7833 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7834 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7835 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7836 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7837 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7838 mod->brush.AmbientSoundLevelsForPoint = NULL;
7839 mod->brush.RoundUpToHullSize = NULL;
7840 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7841 mod->Draw = R_Q1BSP_Draw;
7842 mod->DrawDepth = R_Q1BSP_DrawDepth;
7843 mod->DrawDebug = R_Q1BSP_DrawDebug;
7844 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7845 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7846 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7847 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7848 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7849 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7850 mod->DrawLight = R_Q1BSP_DrawLight;
7852 mod_base = (unsigned char *)header;
7854 // swap all the lumps
7855 header->ident = LittleLong(header->ident);
7856 header->version = LittleLong(header->version);
7857 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7858 for (i = 0;i < lumps;i++)
7860 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7861 if((char *) bufferend < (char *) buffer + j)
7862 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7863 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7864 if((char *) bufferend < (char *) buffer + j)
7865 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7868 * NO, do NOT clear them!
7869 * they contain actual data referenced by other stuff.
7870 * Instead, before using the advertisements lump, check header->versio
7872 * Sorry, but otherwise it breaks memory of the first lump.
7873 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7875 header->lumps[i].fileofs = 0;
7876 header->lumps[i].filelen = 0;
7880 mod->brush.qw_md4sum = 0;
7881 mod->brush.qw_md4sum2 = 0;
7882 for (i = 0;i < lumps;i++)
7884 if (i == Q3LUMP_ENTITIES)
7886 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7887 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7889 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7891 // all this checksumming can take a while, so let's send keepalives here too
7892 CL_KeepaliveMessage(false);
7895 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7896 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7897 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7898 if (header->version == Q3BSPVERSION_IG)
7899 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7901 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7902 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7903 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7904 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7905 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7906 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7907 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7908 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7909 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7910 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7911 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7912 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7913 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7914 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7915 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7917 // the MakePortals code works fine on the q3bsp data as well
7918 if (mod_bsp_portalize.integer)
7919 Mod_Q1BSP_MakePortals();
7921 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7922 loadmodel->brush.supportwateralpha = true;
7924 // make a single combined shadow mesh to allow optimized shadow volume creation
7925 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7927 loadmodel->brush.num_leafs = 0;
7928 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7930 if (loadmodel->brush.numsubmodels)
7931 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7934 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7939 // duplicate the basic information
7940 dpsnprintf(name, sizeof(name), "*%i", i);
7941 mod = Mod_FindName(name, loadmodel->name);
7942 // copy the base model to this one
7944 // rename the clone back to its proper name
7945 strlcpy(mod->name, name, sizeof(mod->name));
7946 mod->brush.parentmodel = loadmodel;
7947 // textures and memory belong to the main model
7948 mod->texturepool = NULL;
7949 mod->mempool = NULL;
7950 mod->brush.GetPVS = NULL;
7951 mod->brush.FatPVS = NULL;
7952 mod->brush.BoxTouchingPVS = NULL;
7953 mod->brush.BoxTouchingLeafPVS = NULL;
7954 mod->brush.BoxTouchingVisibleLeafs = NULL;
7955 mod->brush.FindBoxClusters = NULL;
7956 mod->brush.LightPoint = NULL;
7957 mod->brush.AmbientSoundLevelsForPoint = NULL;
7959 mod->brush.submodel = i;
7960 if (loadmodel->brush.submodels)
7961 loadmodel->brush.submodels[i] = mod;
7963 // make the model surface list (used by shadowing/lighting)
7964 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7965 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7966 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7967 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7968 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7969 Mod_MakeSortedSurfaces(mod);
7971 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7972 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7973 // enlarge the bounding box to enclose all geometry of this model,
7974 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7975 // which can in turn mess up the farclip (as well as culling when
7976 // outside the level - an unimportant concern)
7978 //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]);
7979 for (j = 0;j < mod->nummodelsurfaces;j++)
7981 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7982 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7984 if (!surface->num_vertices)
7986 for (k = 0;k < surface->num_vertices;k++, v += 3)
7988 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7989 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7990 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7991 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7992 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7993 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7996 //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]);
7997 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7998 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7999 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8000 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8001 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8002 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8003 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8004 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8005 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8006 mod->yawmins[2] = mod->normalmins[2];
8007 mod->yawmaxs[2] = mod->normalmaxs[2];
8008 mod->radius = modelradius;
8009 mod->radius2 = modelradius * modelradius;
8011 // this gets altered below if sky or water is used
8012 mod->DrawSky = NULL;
8013 mod->DrawAddWaterPlanes = NULL;
8015 for (j = 0;j < mod->nummodelsurfaces;j++)
8016 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8018 if (j < mod->nummodelsurfaces)
8019 mod->DrawSky = R_Q1BSP_DrawSky;
8021 for (j = 0;j < mod->nummodelsurfaces;j++)
8022 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8024 if (j < mod->nummodelsurfaces)
8025 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8027 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
8028 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
8030 // generate VBOs and other shared data before cloning submodels
8035 if (mod_q3bsp_sRGBlightmaps.integer)
8037 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
8039 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
8040 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
8041 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
8042 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
8043 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
8045 else // if this is NOT set, regular rendering looks right by this requirement anyway
8048 // we want color 1 to do the same as without sRGB
8049 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
8050 loadmodel->lightmapscale *= 2.476923f; // fixes max level
8053 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
8054 // we need to undo that
8055 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
8059 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);
8062 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8064 int i = LittleLong(((int *)buffer)[1]);
8065 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
8066 Mod_Q3BSP_Load(mod,buffer, bufferend);
8067 else if (i == Q2BSPVERSION)
8068 Mod_Q2BSP_Load(mod,buffer, bufferend);
8070 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
8073 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
8075 Host_Error("Mod_MAP_Load: not yet implemented");
8078 typedef struct objvertex_s
8089 static unsigned char nobsp_pvs[1] = {1};
8091 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8093 const char *textbase = (char *)buffer, *text = textbase;
8097 char materialname[MAX_QPATH];
8098 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8099 int index1, index2, index3;
8100 objvertex_t vfirst, vprev, vcurrent;
8103 int numtriangles = 0;
8104 int maxtriangles = 0;
8105 objvertex_t *vertices = NULL;
8107 int maxtextures = 0, numtextures = 0, textureindex = 0;
8108 int maxv = 0, numv = 1;
8109 int maxvt = 0, numvt = 1;
8110 int maxvn = 0, numvn = 1;
8111 char *texturenames = NULL;
8112 float dist, modelradius, modelyawradius, yawradius;
8113 float *obj_v = NULL;
8114 float *obj_vt = NULL;
8115 float *obj_vn = NULL;
8119 objvertex_t *thisvertex = NULL;
8120 int vertexhashindex;
8121 int *vertexhashtable = NULL;
8122 objvertex_t *vertexhashdata = NULL;
8123 objvertex_t *vdata = NULL;
8124 int vertexhashsize = 0;
8125 int vertexhashcount = 0;
8126 skinfile_t *skinfiles = NULL;
8127 unsigned char *data = NULL;
8128 int *submodelfirstsurface;
8129 msurface_t *tempsurface;
8130 msurface_t *tempsurfaces;
8132 memset(&vfirst, 0, sizeof(vfirst));
8133 memset(&vprev, 0, sizeof(vprev));
8134 memset(&vcurrent, 0, sizeof(vcurrent));
8136 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8138 loadmodel->modeldatatypestring = "OBJ";
8140 loadmodel->type = mod_obj;
8141 loadmodel->soundfromcenter = true;
8142 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8143 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8144 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8145 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8146 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8147 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8148 loadmodel->brush.TraceLineOfSight = NULL;
8149 loadmodel->brush.SuperContentsFromNativeContents = NULL;
8150 loadmodel->brush.NativeContentsFromSuperContents = NULL;
8151 loadmodel->brush.GetPVS = NULL;
8152 loadmodel->brush.FatPVS = NULL;
8153 loadmodel->brush.BoxTouchingPVS = NULL;
8154 loadmodel->brush.BoxTouchingLeafPVS = NULL;
8155 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8156 loadmodel->brush.FindBoxClusters = NULL;
8157 loadmodel->brush.LightPoint = NULL;
8158 loadmodel->brush.FindNonSolidLocation = NULL;
8159 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8160 loadmodel->brush.RoundUpToHullSize = NULL;
8161 loadmodel->brush.PointInLeaf = NULL;
8162 loadmodel->Draw = R_Q1BSP_Draw;
8163 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8164 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8165 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8166 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8167 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8168 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8169 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
8170 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
8171 loadmodel->DrawLight = R_Q1BSP_DrawLight;
8173 skinfiles = Mod_LoadSkinFiles();
8174 if (loadmodel->numskins < 1)
8175 loadmodel->numskins = 1;
8177 // make skinscenes for the skins (no groups)
8178 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8179 for (i = 0;i < loadmodel->numskins;i++)
8181 loadmodel->skinscenes[i].firstframe = i;
8182 loadmodel->skinscenes[i].framecount = 1;
8183 loadmodel->skinscenes[i].loop = true;
8184 loadmodel->skinscenes[i].framerate = 10;
8190 // we always have model 0, i.e. the first "submodel"
8191 loadmodel->brush.numsubmodels = 1;
8193 // parse the OBJ text now
8196 static char emptyarg[1] = "";
8201 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8202 line[linelen] = text[linelen];
8204 for (argc = 0;argc < 4;argc++)
8205 argv[argc] = emptyarg;
8208 while (*s == ' ' || *s == '\t')
8218 while (*s == ' ' || *s == '\t')
8228 if (argv[0][0] == '#')
8230 if (!strcmp(argv[0], "v"))
8234 maxv = max(maxv * 2, 1024);
8235 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8237 if(mod_obj_orientation.integer)
8239 obj_v[numv*3+0] = atof(argv[1]);
8240 obj_v[numv*3+2] = atof(argv[2]);
8241 obj_v[numv*3+1] = atof(argv[3]);
8245 obj_v[numv*3+0] = atof(argv[1]);
8246 obj_v[numv*3+1] = atof(argv[2]);
8247 obj_v[numv*3+2] = atof(argv[3]);
8251 else if (!strcmp(argv[0], "vt"))
8255 maxvt = max(maxvt * 2, 1024);
8256 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8258 obj_vt[numvt*2+0] = atof(argv[1]);
8259 obj_vt[numvt*2+1] = 1-atof(argv[2]);
8262 else if (!strcmp(argv[0], "vn"))
8266 maxvn = max(maxvn * 2, 1024);
8267 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8269 if(mod_obj_orientation.integer)
8271 obj_vn[numvn*3+0] = atof(argv[1]);
8272 obj_vn[numvn*3+2] = atof(argv[2]);
8273 obj_vn[numvn*3+1] = atof(argv[3]);
8277 obj_vn[numvn*3+0] = atof(argv[1]);
8278 obj_vn[numvn*3+1] = atof(argv[2]);
8279 obj_vn[numvn*3+2] = atof(argv[3]);
8283 else if (!strcmp(argv[0], "f"))
8287 if (maxtextures <= numtextures)
8289 maxtextures = max(maxtextures * 2, 256);
8290 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8292 textureindex = numtextures++;
8293 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8295 for (j = 1;j < argc;j++)
8297 index1 = atoi(argv[j]);
8298 while(argv[j][0] && argv[j][0] != '/')
8302 index2 = atoi(argv[j]);
8303 while(argv[j][0] && argv[j][0] != '/')
8307 index3 = atoi(argv[j]);
8308 // negative refers to a recent vertex
8309 // zero means not specified
8310 // positive means an absolute vertex index
8312 index1 = numv - index1;
8314 index2 = numvt - index2;
8316 index3 = numvn - index3;
8317 vcurrent.nextindex = -1;
8318 vcurrent.textureindex = textureindex;
8319 vcurrent.submodelindex = submodelindex;
8320 if (obj_v && index1 >= 0 && index1 < numv)
8321 VectorCopy(obj_v + 3*index1, vcurrent.v);
8322 if (obj_vt && index2 >= 0 && index2 < numvt)
8323 Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8324 if (obj_vn && index3 >= 0 && index3 < numvn)
8325 VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8326 if (numtriangles == 0)
8328 VectorCopy(vcurrent.v, mins);
8329 VectorCopy(vcurrent.v, maxs);
8333 mins[0] = min(mins[0], vcurrent.v[0]);
8334 mins[1] = min(mins[1], vcurrent.v[1]);
8335 mins[2] = min(mins[2], vcurrent.v[2]);
8336 maxs[0] = max(maxs[0], vcurrent.v[0]);
8337 maxs[1] = max(maxs[1], vcurrent.v[1]);
8338 maxs[2] = max(maxs[2], vcurrent.v[2]);
8344 if (maxtriangles <= numtriangles)
8346 maxtriangles = max(maxtriangles * 2, 32768);
8347 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8349 if(mod_obj_orientation.integer)
8351 vertices[numtriangles*3+0] = vfirst;
8352 vertices[numtriangles*3+1] = vprev;
8353 vertices[numtriangles*3+2] = vcurrent;
8357 vertices[numtriangles*3+0] = vfirst;
8358 vertices[numtriangles*3+2] = vprev;
8359 vertices[numtriangles*3+1] = vcurrent;
8366 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8368 submodelindex = atof(argv[1]);
8369 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8371 else if (!strcmp(argv[0], "usemtl"))
8373 for (i = 0;i < numtextures;i++)
8374 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8376 if (i < numtextures)
8380 if (maxtextures <= numtextures)
8382 maxtextures = max(maxtextures * 2, 256);
8383 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8385 textureindex = numtextures++;
8386 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8391 // now that we have the OBJ data loaded as-is, we can convert it
8393 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8394 VectorCopy(mins, loadmodel->normalmins);
8395 VectorCopy(maxs, loadmodel->normalmaxs);
8396 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8397 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8398 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8399 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8400 modelradius = modelyawradius + modelradius * modelradius;
8401 modelyawradius = sqrt(modelyawradius);
8402 modelradius = sqrt(modelradius);
8403 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8404 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8405 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8406 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8407 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8408 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8409 loadmodel->radius = modelradius;
8410 loadmodel->radius2 = modelradius * modelradius;
8412 // allocate storage for triangles
8413 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8414 // allocate vertex hash structures to build an optimal vertex subset
8415 vertexhashsize = numtriangles*2;
8416 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8417 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8418 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8419 vertexhashcount = 0;
8421 // gather surface stats for assigning vertex/triangle ranges
8425 loadmodel->num_surfaces = 0;
8426 // allocate storage for the worst case number of surfaces, later we resize
8427 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8428 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8429 tempsurface = tempsurfaces;
8430 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8432 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8433 for (textureindex = 0;textureindex < numtextures;textureindex++)
8435 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8437 thisvertex = vertices + vertexindex;
8438 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8441 // skip the surface creation if there are no triangles for it
8442 if (vertexindex == numtriangles*3)
8444 // create a surface for these vertices
8445 surfacevertices = 0;
8446 surfaceelements = 0;
8447 // we hack in a texture index in the surface to be fixed up later...
8448 tempsurface->texture = (texture_t *)((size_t)textureindex);
8449 // calculate bounds as we go
8450 VectorCopy(thisvertex->v, tempsurface->mins);
8451 VectorCopy(thisvertex->v, tempsurface->maxs);
8452 for (;vertexindex < numtriangles*3;vertexindex++)
8454 thisvertex = vertices + vertexindex;
8455 if (thisvertex->submodelindex != submodelindex)
8457 if (thisvertex->textureindex != textureindex)
8459 // add vertex to surface bounds
8460 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8461 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8462 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8463 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8464 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8465 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8466 // add the vertex if it is not found in the merged set, and
8467 // get its index (triangle element) for the surface
8468 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8469 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8471 vdata = vertexhashdata + i;
8472 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8477 i = vertexhashcount++;
8478 vdata = vertexhashdata + i;
8479 *vdata = *thisvertex;
8480 vdata->nextindex = vertexhashtable[vertexhashindex];
8481 vertexhashtable[vertexhashindex] = i;
8484 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8487 surfacetriangles = surfaceelements / 3;
8488 tempsurface->num_vertices = surfacevertices;
8489 tempsurface->num_triangles = surfacetriangles;
8490 tempsurface->num_firstvertex = firstvertex;
8491 tempsurface->num_firsttriangle = firsttriangle;
8492 firstvertex += tempsurface->num_vertices;
8493 firsttriangle += tempsurface->num_triangles;
8495 loadmodel->num_surfaces++;
8498 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8499 numvertices = firstvertex;
8500 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8501 tempsurfaces = NULL;
8503 // allocate storage for final mesh data
8504 loadmodel->num_textures = numtextures * loadmodel->numskins;
8505 loadmodel->num_texturesperskin = numtextures;
8506 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) + (r_enableshadowvolumes.integer ? numtriangles * sizeof(int[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8507 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
8508 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8509 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8510 loadmodel->surfmesh.num_vertices = numvertices;
8511 loadmodel->surfmesh.num_triangles = numtriangles;
8512 if (r_enableshadowvolumes.integer)
8513 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
8514 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8515 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8516 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8517 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8518 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8519 if (loadmodel->surfmesh.num_vertices <= 65536)
8520 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8522 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8524 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8525 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8526 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8529 // load the textures
8530 for (textureindex = 0;textureindex < numtextures;textureindex++)
8531 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8532 Mod_FreeSkinFiles(skinfiles);
8534 // set the surface textures to their real values now that we loaded them...
8535 for (i = 0;i < loadmodel->num_surfaces;i++)
8536 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8540 Mem_Free(texturenames);
8544 Mem_Free(vertexhashtable);
8545 Mem_Free(vertexhashdata);
8547 // make a single combined shadow mesh to allow optimized shadow volume creation
8548 Mod_Q1BSP_CreateShadowMesh(loadmodel);
8550 // compute all the mesh information that was not loaded from the file
8551 if (loadmodel->surfmesh.data_element3s)
8552 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8553 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8554 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8555 // generate normals if the file did not have them
8556 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8557 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);
8558 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);
8559 if (loadmodel->surfmesh.data_neighbor3i)
8560 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8562 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8563 loadmodel->brush.num_visleafs = 1;
8564 loadmodel->brush.num_leafs = 1;
8565 loadmodel->brush.num_nodes = 0;
8566 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8567 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8568 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8569 loadmodel->brush.num_pvsclusters = 1;
8570 loadmodel->brush.num_pvsclusterbytes = 1;
8571 loadmodel->brush.data_pvsclusters = nobsp_pvs;
8572 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8573 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8574 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
8575 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8576 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8577 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8578 loadmodel->brush.data_leafs->clusterindex = 0;
8579 loadmodel->brush.data_leafs->areaindex = 0;
8580 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8581 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8582 loadmodel->brush.data_leafs->numleafbrushes = 0;
8583 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8584 loadmodel->brush.supportwateralpha = true;
8586 if (loadmodel->brush.numsubmodels)
8587 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8590 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8595 // duplicate the basic information
8596 dpsnprintf(name, sizeof(name), "*%i", i);
8597 mod = Mod_FindName(name, loadmodel->name);
8598 // copy the base model to this one
8600 // rename the clone back to its proper name
8601 strlcpy(mod->name, name, sizeof(mod->name));
8602 mod->brush.parentmodel = loadmodel;
8603 // textures and memory belong to the main model
8604 mod->texturepool = NULL;
8605 mod->mempool = NULL;
8606 mod->brush.GetPVS = NULL;
8607 mod->brush.FatPVS = NULL;
8608 mod->brush.BoxTouchingPVS = NULL;
8609 mod->brush.BoxTouchingLeafPVS = NULL;
8610 mod->brush.BoxTouchingVisibleLeafs = NULL;
8611 mod->brush.FindBoxClusters = NULL;
8612 mod->brush.LightPoint = NULL;
8613 mod->brush.AmbientSoundLevelsForPoint = NULL;
8615 mod->brush.submodel = i;
8616 if (loadmodel->brush.submodels)
8617 loadmodel->brush.submodels[i] = mod;
8619 // make the model surface list (used by shadowing/lighting)
8620 mod->firstmodelsurface = submodelfirstsurface[i];
8621 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8622 mod->firstmodelbrush = 0;
8623 mod->nummodelbrushes = 0;
8624 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8625 Mod_MakeSortedSurfaces(mod);
8627 VectorClear(mod->normalmins);
8628 VectorClear(mod->normalmaxs);
8630 for (j = 0;j < mod->nummodelsurfaces;j++)
8632 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8633 const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8635 if (!surface->num_vertices)
8640 VectorCopy(v3f, mod->normalmins);
8641 VectorCopy(v3f, mod->normalmaxs);
8643 for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8645 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8646 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8647 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8648 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8649 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8650 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8653 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8654 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8655 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8656 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8657 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8658 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8659 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8660 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8661 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8662 mod->yawmins[2] = mod->normalmins[2];
8663 mod->yawmaxs[2] = mod->normalmaxs[2];
8664 mod->radius = modelradius;
8665 mod->radius2 = modelradius * modelradius;
8667 // this gets altered below if sky or water is used
8668 mod->DrawSky = NULL;
8669 mod->DrawAddWaterPlanes = NULL;
8671 for (j = 0;j < mod->nummodelsurfaces;j++)
8672 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8674 if (j < mod->nummodelsurfaces)
8675 mod->DrawSky = R_Q1BSP_DrawSky;
8677 for (j = 0;j < mod->nummodelsurfaces;j++)
8678 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8680 if (j < mod->nummodelsurfaces)
8681 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8683 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8684 mod->render_bih = mod->collision_bih;
8686 // generate VBOs and other shared data before cloning submodels
8691 Mem_Free(submodelfirstsurface);
8693 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);