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_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
46 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
47 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
48 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
49 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
50 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
51 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
52 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
53 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
54 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
55 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
56 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
57 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
58 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
59 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
60 cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
62 cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
63 cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
64 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
66 static texture_t mod_q1bsp_texture_solid;
67 static texture_t mod_q1bsp_texture_sky;
68 static texture_t mod_q1bsp_texture_lava;
69 static texture_t mod_q1bsp_texture_slime;
70 static texture_t mod_q1bsp_texture_water;
72 void Mod_BrushInit(void)
74 // Cvar_RegisterVariable(&r_subdivide_size);
75 Cvar_RegisterVariable(&mod_bsp_portalize);
76 Cvar_RegisterVariable(&r_novis);
77 Cvar_RegisterVariable(&r_nosurftextures);
78 Cvar_RegisterVariable(&r_subdivisions_tolerance);
79 Cvar_RegisterVariable(&r_subdivisions_mintess);
80 Cvar_RegisterVariable(&r_subdivisions_maxtess);
81 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
82 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
83 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
84 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
85 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
86 Cvar_RegisterVariable(&r_trippy);
87 Cvar_RegisterVariable(&r_fxaa);
88 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
89 Cvar_RegisterVariable(&mod_obj_orientation);
90 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
91 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
92 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
93 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
94 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
95 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
96 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
97 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
98 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
99 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
100 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
101 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
102 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
103 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
104 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
105 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
106 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
107 Cvar_RegisterVariable(&mod_collision_bih);
108 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
110 // these games were made for older DP engines and are no longer
111 // maintained; use this hack to show their textures properly
112 if(gamemode == GAME_NEXUIZ)
113 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
115 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
116 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
117 mod_q1bsp_texture_solid.surfaceflags = 0;
118 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
120 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
121 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
122 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
123 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
125 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
126 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
127 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
128 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
130 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
131 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
132 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
133 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
135 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
136 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
137 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
138 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
141 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
148 // LordHavoc: modified to start at first clip node,
149 // in other words: first node of the (sub)model
150 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
152 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
154 return (mleaf_t *)node;
157 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
161 leaf = Mod_Q1BSP_PointInLeaf(model, p);
164 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
167 memcpy(out, leaf->ambient_sound_level, i);
173 memset(out, 0, outsize);
176 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
179 int nodestackindex = 0;
180 mnode_t *node, *nodestack[1024];
181 if (!model->brush.num_pvsclusters)
183 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
189 // node - recurse down the BSP tree
190 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
194 return -1; // ERROR: NAN bounding box!
195 // box is on one side of plane, take that path
196 node = node->children[sides-1];
200 // box crosses plane, take one path and remember the other
201 if (nodestackindex < 1024)
202 nodestack[nodestackindex++] = node->children[0];
203 node = node->children[1];
209 // leaf - add clusterindex to list
210 if (numclusters < maxclusters)
211 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
215 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
219 if (nodestackindex < 1024)
220 nodestack[nodestackindex++] = node->children[0];
221 node = node->children[1];
226 // leaf - add clusterindex to list
227 if (numclusters < maxclusters)
228 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
233 // try another path we didn't take earlier
234 if (nodestackindex == 0)
236 node = nodestack[--nodestackindex];
238 // return number of clusters found (even if more than the maxclusters)
242 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
244 int nodestackindex = 0;
245 mnode_t *node, *nodestack[1024];
246 if (!model->brush.num_pvsclusters)
248 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
254 // node - recurse down the BSP tree
255 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
259 return -1; // ERROR: NAN bounding box!
260 // box is on one side of plane, take that path
261 node = node->children[sides-1];
265 // box crosses plane, take one path and remember the other
266 if (nodestackindex < 1024)
267 nodestack[nodestackindex++] = node->children[0];
268 node = node->children[1];
274 // leaf - check cluster bit
275 int clusterindex = ((mleaf_t *)node)->clusterindex;
276 if (CHECKPVSBIT(pvs, clusterindex))
278 // it is visible, return immediately with the news
283 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
287 if (nodestackindex < 1024)
288 nodestack[nodestackindex++] = node->children[0];
289 node = node->children[1];
294 // leaf - check cluster bit
295 int clusterindex = ((mleaf_t *)node)->clusterindex;
296 if (CHECKPVSBIT(pvs, clusterindex))
298 // it is visible, return immediately with the news
304 // nothing to see here, try another path we didn't take earlier
305 if (nodestackindex == 0)
307 node = nodestack[--nodestackindex];
313 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
315 int nodestackindex = 0;
316 mnode_t *node, *nodestack[1024];
317 if (!model->brush.num_leafs)
319 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
325 // node - recurse down the BSP tree
326 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
330 return -1; // ERROR: NAN bounding box!
331 // box is on one side of plane, take that path
332 node = node->children[sides-1];
336 // box crosses plane, take one path and remember the other
337 if (nodestackindex < 1024)
338 nodestack[nodestackindex++] = node->children[0];
339 node = node->children[1];
345 // leaf - check cluster bit
346 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
347 if (CHECKPVSBIT(pvs, clusterindex))
349 // it is visible, return immediately with the news
354 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
358 if (nodestackindex < 1024)
359 nodestack[nodestackindex++] = node->children[0];
360 node = node->children[1];
365 // leaf - check cluster bit
366 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
367 if (CHECKPVSBIT(pvs, clusterindex))
369 // it is visible, return immediately with the news
375 // nothing to see here, try another path we didn't take earlier
376 if (nodestackindex == 0)
378 node = nodestack[--nodestackindex];
384 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
386 int nodestackindex = 0;
387 mnode_t *node, *nodestack[1024];
388 if (!model->brush.num_leafs)
390 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
396 // node - recurse down the BSP tree
397 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
401 return -1; // ERROR: NAN bounding box!
402 // box is on one side of plane, take that path
403 node = node->children[sides-1];
407 // box crosses plane, take one path and remember the other
408 if (nodestackindex < 1024)
409 nodestack[nodestackindex++] = node->children[0];
410 node = node->children[1];
416 // leaf - check if it is visible
417 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
419 // it is visible, return immediately with the news
424 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
428 if (nodestackindex < 1024)
429 nodestack[nodestackindex++] = node->children[0];
430 node = node->children[1];
435 // leaf - check if it is visible
436 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
438 // it is visible, return immediately with the news
444 // nothing to see here, try another path we didn't take earlier
445 if (nodestackindex == 0)
447 node = nodestack[--nodestackindex];
453 typedef struct findnonsolidlocationinfo_s
456 vec3_t absmin, absmax;
462 findnonsolidlocationinfo_t;
464 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
467 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
469 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
470 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
471 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
472 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
473 VectorSubtract(vert[1], vert[0], edge[0]);
474 VectorSubtract(vert[2], vert[1], edge[1]);
475 CrossProduct(edge[1], edge[0], facenormal);
476 if (facenormal[0] || facenormal[1] || facenormal[2])
478 VectorNormalize(facenormal);
479 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
480 if (f <= info->bestdist && f >= -info->bestdist)
482 VectorSubtract(vert[0], vert[2], edge[2]);
483 VectorNormalize(edge[0]);
484 VectorNormalize(edge[1]);
485 VectorNormalize(edge[2]);
486 CrossProduct(facenormal, edge[0], edgenormal[0]);
487 CrossProduct(facenormal, edge[1], edgenormal[1]);
488 CrossProduct(facenormal, edge[2], edgenormal[2]);
490 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
491 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
492 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
494 // we got lucky, the center is within the face
495 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
499 if (info->bestdist > dist)
501 info->bestdist = dist;
502 VectorScale(facenormal, (info->radius - -dist), info->nudge);
507 if (info->bestdist > dist)
509 info->bestdist = dist;
510 VectorScale(facenormal, (info->radius - dist), info->nudge);
516 // check which edge or vertex the center is nearest
517 for (i = 0;i < 3;i++)
519 f = DotProduct(info->center, edge[i]);
520 if (f >= DotProduct(vert[0], edge[i])
521 && f <= DotProduct(vert[1], edge[i]))
524 VectorMA(info->center, -f, edge[i], point);
525 dist = sqrt(DotProduct(point, point));
526 if (info->bestdist > dist)
528 info->bestdist = dist;
529 VectorScale(point, (info->radius / dist), info->nudge);
531 // skip both vertex checks
532 // (both are further away than this edge)
537 // not on edge, check first vertex of edge
538 VectorSubtract(info->center, vert[i], point);
539 dist = sqrt(DotProduct(point, point));
540 if (info->bestdist > dist)
542 info->bestdist = dist;
543 VectorScale(point, (info->radius / dist), info->nudge);
552 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
554 int surfacenum, k, *mark;
556 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
558 surface = info->model->data_surfaces + *mark;
559 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
561 if(surface->deprecatedq3num_bboxstride > 0)
564 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
565 for(i = 0; i < cnt; ++i)
567 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
569 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
571 tri = i * surface->deprecatedq3num_bboxstride + k;
572 if(tri >= surface->num_triangles)
574 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
581 for (k = 0;k < surface->num_triangles;k++)
583 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
590 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
594 float f = PlaneDiff(info->center, node->plane);
595 if (f >= -info->bestdist)
596 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
597 if (f <= info->bestdist)
598 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
602 if (((mleaf_t *)node)->numleafsurfaces)
603 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
607 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
610 findnonsolidlocationinfo_t info;
616 VectorCopy(in, info.center);
617 info.radius = radius;
622 VectorClear(info.nudge);
623 info.bestdist = radius;
624 VectorCopy(info.center, info.absmin);
625 VectorCopy(info.center, info.absmax);
626 info.absmin[0] -= info.radius + 1;
627 info.absmin[1] -= info.radius + 1;
628 info.absmin[2] -= info.radius + 1;
629 info.absmax[0] += info.radius + 1;
630 info.absmax[1] += info.radius + 1;
631 info.absmax[2] += info.radius + 1;
632 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
633 VectorAdd(info.center, info.nudge, info.center);
635 while (info.bestdist < radius && ++i < 10);
636 VectorCopy(info.center, out);
639 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
641 switch(nativecontents)
646 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
648 return SUPERCONTENTS_WATER;
650 return SUPERCONTENTS_SLIME;
652 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
654 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
659 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
661 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
662 return CONTENTS_SOLID;
663 if (supercontents & SUPERCONTENTS_SKY)
665 if (supercontents & SUPERCONTENTS_LAVA)
666 return CONTENTS_LAVA;
667 if (supercontents & SUPERCONTENTS_SLIME)
668 return CONTENTS_SLIME;
669 if (supercontents & SUPERCONTENTS_WATER)
670 return CONTENTS_WATER;
671 return CONTENTS_EMPTY;
674 typedef struct RecursiveHullCheckTraceInfo_s
676 // the hull we're tracing through
679 // the trace structure to fill in
682 // start, end, and end - start (in model space)
687 RecursiveHullCheckTraceInfo_t;
689 // 1/32 epsilon to keep floating point happy
690 #define DIST_EPSILON (0.03125)
692 #define HULLCHECKSTATE_EMPTY 0
693 #define HULLCHECKSTATE_SOLID 1
694 #define HULLCHECKSTATE_DONE 2
696 extern cvar_t collision_prefernudgedfraction;
697 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
699 // status variables, these don't need to be saved on the stack when
700 // recursing... but are because this should be thread-safe
701 // (note: tracing against a bbox is not thread-safe, yet)
706 // variables that need to be stored on the stack when recursing
711 // LordHavoc: a goto! everyone flee in terror... :)
716 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
717 if (!t->trace->startfound)
719 t->trace->startfound = true;
720 t->trace->startsupercontents |= num;
722 if (num & SUPERCONTENTS_LIQUIDSMASK)
723 t->trace->inwater = true;
725 t->trace->inopen = true;
726 if (num & SUPERCONTENTS_SOLID)
727 t->trace->hittexture = &mod_q1bsp_texture_solid;
728 else if (num & SUPERCONTENTS_SKY)
729 t->trace->hittexture = &mod_q1bsp_texture_sky;
730 else if (num & SUPERCONTENTS_LAVA)
731 t->trace->hittexture = &mod_q1bsp_texture_lava;
732 else if (num & SUPERCONTENTS_SLIME)
733 t->trace->hittexture = &mod_q1bsp_texture_slime;
735 t->trace->hittexture = &mod_q1bsp_texture_water;
736 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
737 t->trace->hitsupercontents = num;
738 if (num & t->trace->hitsupercontentsmask)
740 // if the first leaf is solid, set startsolid
741 if (t->trace->allsolid)
742 t->trace->startsolid = true;
743 #if COLLISIONPARANOID >= 3
746 return HULLCHECKSTATE_SOLID;
750 t->trace->allsolid = false;
751 #if COLLISIONPARANOID >= 3
754 return HULLCHECKSTATE_EMPTY;
758 // find the point distances
759 node = t->hull->clipnodes + num;
761 plane = t->hull->planes + node->planenum;
764 t1 = p1[plane->type] - plane->dist;
765 t2 = p2[plane->type] - plane->dist;
769 t1 = DotProduct (plane->normal, p1) - plane->dist;
770 t2 = DotProduct (plane->normal, p2) - plane->dist;
777 #if COLLISIONPARANOID >= 3
780 num = node->children[1];
789 #if COLLISIONPARANOID >= 3
792 num = node->children[0];
798 // the line intersects, find intersection point
799 // LordHavoc: this uses the original trace for maximum accuracy
800 #if COLLISIONPARANOID >= 3
805 t1 = t->start[plane->type] - plane->dist;
806 t2 = t->end[plane->type] - plane->dist;
810 t1 = DotProduct (plane->normal, t->start) - plane->dist;
811 t2 = DotProduct (plane->normal, t->end) - plane->dist;
814 midf = t1 / (t1 - t2);
815 midf = bound(p1f, midf, p2f);
816 VectorMA(t->start, midf, t->dist, mid);
818 // recurse both sides, front side first
819 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
820 // if this side is not empty, return what it is (solid or done)
821 if (ret != HULLCHECKSTATE_EMPTY)
824 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
825 // if other side is not solid, return what it is (empty or done)
826 if (ret != HULLCHECKSTATE_SOLID)
829 // front is air and back is solid, this is the impact point...
832 t->trace->plane.dist = -plane->dist;
833 VectorNegate (plane->normal, t->trace->plane.normal);
837 t->trace->plane.dist = plane->dist;
838 VectorCopy (plane->normal, t->trace->plane.normal);
841 // calculate the true fraction
842 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
843 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
844 midf = t1 / (t1 - t2);
845 t->trace->realfraction = bound(0, midf, 1);
847 // calculate the return fraction which is nudged off the surface a bit
848 midf = (t1 - DIST_EPSILON) / (t1 - t2);
849 t->trace->fraction = bound(0, midf, 1);
851 if (collision_prefernudgedfraction.integer)
852 t->trace->realfraction = t->trace->fraction;
854 #if COLLISIONPARANOID >= 3
857 return HULLCHECKSTATE_DONE;
860 //#if COLLISIONPARANOID < 2
861 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
864 mclipnode_t *nodes = t->hull->clipnodes;
865 mplane_t *planes = t->hull->planes;
867 VectorCopy(t->start, point);
870 plane = planes + nodes[num].planenum;
871 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
873 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
874 t->trace->startsupercontents |= num;
875 if (num & SUPERCONTENTS_LIQUIDSMASK)
876 t->trace->inwater = true;
878 t->trace->inopen = true;
879 if (num & t->trace->hitsupercontentsmask)
881 t->trace->allsolid = t->trace->startsolid = true;
882 return HULLCHECKSTATE_SOLID;
886 t->trace->allsolid = t->trace->startsolid = false;
887 return HULLCHECKSTATE_EMPTY;
892 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)
894 RecursiveHullCheckTraceInfo_t rhc;
896 memset(&rhc, 0, sizeof(rhc));
897 memset(trace, 0, sizeof(trace_t));
899 rhc.trace->fraction = 1;
900 rhc.trace->realfraction = 1;
901 rhc.trace->allsolid = true;
902 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
903 VectorCopy(start, rhc.start);
904 VectorCopy(start, rhc.end);
905 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
908 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);
910 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)
912 RecursiveHullCheckTraceInfo_t rhc;
914 if (VectorCompare(start, end))
916 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
920 // 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...
921 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
923 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
927 memset(&rhc, 0, sizeof(rhc));
928 memset(trace, 0, sizeof(trace_t));
930 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
931 rhc.trace->fraction = 1;
932 rhc.trace->realfraction = 1;
933 rhc.trace->allsolid = true;
934 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
935 VectorCopy(start, rhc.start);
936 VectorCopy(end, rhc.end);
937 VectorSubtract(rhc.end, rhc.start, rhc.dist);
938 #if COLLISIONPARANOID >= 2
939 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]);
940 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
945 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
946 memset(&testtrace, 0, sizeof(trace_t));
947 rhc.trace = &testtrace;
948 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
949 rhc.trace->fraction = 1;
950 rhc.trace->realfraction = 1;
951 rhc.trace->allsolid = true;
952 VectorCopy(test, rhc.start);
953 VectorCopy(test, rhc.end);
954 VectorClear(rhc.dist);
955 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
956 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
957 if (!trace->startsolid && testtrace.startsolid)
958 Con_Printf(" - ended in solid!\n");
962 if (VectorLength2(rhc.dist))
963 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
965 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
969 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)
971 // this function currently only supports same size start and end
973 RecursiveHullCheckTraceInfo_t rhc;
975 if (VectorCompare(boxmins, boxmaxs))
977 if (VectorCompare(start, end))
978 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
980 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
984 memset(&rhc, 0, sizeof(rhc));
985 memset(trace, 0, sizeof(trace_t));
987 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
988 rhc.trace->fraction = 1;
989 rhc.trace->realfraction = 1;
990 rhc.trace->allsolid = true;
991 VectorSubtract(boxmaxs, boxmins, boxsize);
993 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
994 else if (model->brush.ishlbsp)
996 // LordHavoc: this has to have a minor tolerance (the .1) because of
997 // minor float precision errors from the box being transformed around
998 if (boxsize[0] < 32.1)
1000 if (boxsize[2] < 54) // pick the nearest of 36 or 72
1001 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
1003 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1006 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1010 // LordHavoc: this has to have a minor tolerance (the .1) because of
1011 // minor float precision errors from the box being transformed around
1012 if (boxsize[0] < 32.1)
1013 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1015 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1017 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1018 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1019 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1020 #if COLLISIONPARANOID >= 2
1021 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]);
1022 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1027 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1028 memset(&testtrace, 0, sizeof(trace_t));
1029 rhc.trace = &testtrace;
1030 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1031 rhc.trace->fraction = 1;
1032 rhc.trace->realfraction = 1;
1033 rhc.trace->allsolid = true;
1034 VectorCopy(test, rhc.start);
1035 VectorCopy(test, rhc.end);
1036 VectorClear(rhc.dist);
1037 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1038 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1039 if (!trace->startsolid && testtrace.startsolid)
1040 Con_Printf(" - ended in solid!\n");
1044 if (VectorLength2(rhc.dist))
1045 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1047 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1051 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1053 int num = model->brushq1.hulls[0].firstclipnode;
1055 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1056 mplane_t *planes = model->brushq1.hulls[0].planes;
1059 plane = planes + nodes[num].planenum;
1060 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1062 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1065 void Collision_ClipTrace_Box(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1069 colplanef_t cbox_planes[6];
1071 cbox.hasaabbplanes = true;
1072 cbox.supercontents = boxsupercontents;
1075 cbox.numtriangles = 0;
1076 cbox.planes = cbox_planes;
1078 cbox.elements = NULL;
1086 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];
1087 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];
1088 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];
1089 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];
1090 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];
1091 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];
1092 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1093 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1094 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1095 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1096 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1097 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1098 memset(trace, 0, sizeof(trace_t));
1099 trace->hitsupercontentsmask = hitsupercontentsmask;
1100 trace->fraction = 1;
1101 trace->realfraction = 1;
1102 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1104 RecursiveHullCheckTraceInfo_t rhc;
1105 static hull_t box_hull;
1106 static mclipnode_t box_clipnodes[6];
1107 static mplane_t box_planes[6];
1108 // fill in a default trace
1109 memset(&rhc, 0, sizeof(rhc));
1110 memset(trace, 0, sizeof(trace_t));
1111 //To keep everything totally uniform, bounding boxes are turned into small
1112 //BSP trees instead of being compared directly.
1113 // create a temp hull from bounding box sizes
1114 box_planes[0].dist = cmaxs[0] - mins[0];
1115 box_planes[1].dist = cmins[0] - maxs[0];
1116 box_planes[2].dist = cmaxs[1] - mins[1];
1117 box_planes[3].dist = cmins[1] - maxs[1];
1118 box_planes[4].dist = cmaxs[2] - mins[2];
1119 box_planes[5].dist = cmins[2] - maxs[2];
1120 #if COLLISIONPARANOID >= 3
1121 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]);
1124 if (box_hull.clipnodes == NULL)
1128 //Set up the planes and clipnodes so that the six floats of a bounding box
1129 //can just be stored out and get a proper hull_t structure.
1131 box_hull.clipnodes = box_clipnodes;
1132 box_hull.planes = box_planes;
1133 box_hull.firstclipnode = 0;
1134 box_hull.lastclipnode = 5;
1136 for (i = 0;i < 6;i++)
1138 box_clipnodes[i].planenum = i;
1142 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1144 box_clipnodes[i].children[side^1] = i + 1;
1146 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1148 box_planes[i].type = i>>1;
1149 box_planes[i].normal[i>>1] = 1;
1153 // trace a line through the generated clipping hull
1154 //rhc.boxsupercontents = boxsupercontents;
1155 rhc.hull = &box_hull;
1157 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1158 rhc.trace->fraction = 1;
1159 rhc.trace->realfraction = 1;
1160 rhc.trace->allsolid = true;
1161 VectorCopy(start, rhc.start);
1162 VectorCopy(end, rhc.end);
1163 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1164 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1165 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1166 if (rhc.trace->startsupercontents)
1167 rhc.trace->startsupercontents = boxsupercontents;
1171 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1173 memset(trace, 0, sizeof(trace_t));
1174 trace->fraction = 1;
1175 trace->realfraction = 1;
1176 if (BoxesOverlap(start, start, cmins, cmaxs))
1178 trace->startsupercontents |= boxsupercontents;
1179 if (hitsupercontentsmask & boxsupercontents)
1181 trace->startsolid = true;
1182 trace->allsolid = true;
1187 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1190 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1191 return trace.fraction == 1;
1194 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)
1198 float mid, distz = endz - startz;
1202 return false; // didn't hit anything
1204 switch (node->plane->type)
1207 node = node->children[x < node->plane->dist];
1210 node = node->children[y < node->plane->dist];
1213 side = startz < node->plane->dist;
1214 if ((endz < node->plane->dist) == side)
1216 node = node->children[side];
1219 // found an intersection
1220 mid = node->plane->dist;
1223 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1224 front += startz * node->plane->normal[2];
1225 back += endz * node->plane->normal[2];
1226 side = front < node->plane->dist;
1227 if ((back < node->plane->dist) == side)
1229 node = node->children[side];
1232 // found an intersection
1233 mid = startz + distz * (front - node->plane->dist) / (front - back);
1237 // go down front side
1238 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1239 return true; // hit something
1242 // check for impact on this node
1243 if (node->numsurfaces)
1246 int dsi, dti, lmwidth, lmheight;
1248 msurface_t *surface;
1249 unsigned char *lightmap;
1250 int maps, line3, size3;
1253 float scale, w, w00, w01, w10, w11;
1255 surface = model->data_surfaces + node->firstsurface;
1256 for (i = 0;i < node->numsurfaces;i++, surface++)
1258 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1259 continue; // no lightmaps
1261 // location we want to sample in the lightmap
1262 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;
1263 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;
1266 // thanks to jitspoe for pointing out that this int cast was
1267 // rounding toward zero, so we floor it
1268 dsi = (int)floor(ds);
1269 dti = (int)floor(dt);
1270 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1271 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1274 // we have to tolerate a position of lmwidth-1 for some rare
1275 // cases - in which case the sampling position still gets
1276 // clamped but the color gets interpolated to that edge.
1277 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1279 // in the rare cases where we're sampling slightly off
1280 // the polygon, clamp the sampling position (we can still
1281 // interpolate outside it, where it becomes extrapolation)
1286 if (dsi > lmwidth-2)
1288 if (dti > lmheight-2)
1291 // calculate bilinear interpolation factors
1292 // and also multiply by fixedpoint conversion factors to
1293 // compensate for lightmaps being 0-255 (as 0-2), we use
1294 // r_refdef.scene.rtlightstylevalue here which is already
1295 // 0.000-2.148 range
1296 // (if we used r_refdef.scene.lightstylevalue this
1297 // divisor would be 32768 rather than 128)
1300 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1301 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1302 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1303 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1305 // values for pointer math
1306 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1307 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1309 // look up the pixel
1310 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1312 // bilinear filter each lightmap style, and sum them
1313 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1315 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1316 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1317 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1318 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1319 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1323 return true; // success
1328 // go down back side
1329 node = node->children[side ^ 1];
1331 distz = endz - startz;
1336 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1338 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1339 VectorSet(diffusenormal, 0, 0, 1);
1341 if (!model->brushq1.lightdata)
1343 VectorSet(ambientcolor, 1, 1, 1);
1344 VectorSet(diffusecolor, 0, 0, 0);
1348 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);
1351 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1356 const msurface_t *surface;
1361 float edgenormal[3];
1368 surface = model->data_surfaces + node->firstsurface;
1369 for (i = 0;i < node->numsurfaces;i++, surface++)
1371 // skip surfaces whose bounding box does not include the point
1372 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1374 // skip faces with contents we don't care about
1375 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1377 // get the surface normal - since it is flat we know any vertex normal will suffice
1378 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1380 if (DotProduct(t->dist, normal) > 0)
1382 // iterate edges and see if the point is outside one of them
1383 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1385 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1386 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1387 VectorSubtract(v0, v1, edgedir);
1388 CrossProduct(edgedir, normal, edgenormal);
1389 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1392 // if the point is outside one of the edges, it is not within the surface
1393 if (j < surface->num_vertices)
1396 // we hit a surface, this is the impact point...
1397 VectorCopy(normal, t->trace->plane.normal);
1398 t->trace->plane.dist = DotProduct(normal, p);
1400 // calculate the true fraction
1401 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1402 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1403 midf = t1 / (t1 - t2);
1404 t->trace->realfraction = midf;
1406 // calculate the return fraction which is nudged off the surface a bit
1407 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1408 t->trace->fraction = bound(0, midf, 1);
1410 if (collision_prefernudgedfraction.integer)
1411 t->trace->realfraction = t->trace->fraction;
1413 t->trace->hittexture = surface->texture->currentframe;
1414 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1415 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1416 return surface->texture->currentframe;
1421 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])
1423 const mplane_t *plane;
1426 double midf, mid[3];
1427 const mleaf_t *leaf;
1431 plane = node->plane;
1432 if (plane->type < 3)
1434 t1 = p1[plane->type] - plane->dist;
1435 t2 = p2[plane->type] - plane->dist;
1439 t1 = DotProduct (plane->normal, p1) - plane->dist;
1440 t2 = DotProduct (plane->normal, p2) - plane->dist;
1446 node = node->children[1];
1455 node = node->children[0];
1461 // the line intersects, find intersection point
1462 // LordHavoc: this uses the original trace for maximum accuracy
1463 if (plane->type < 3)
1465 t1 = t->start[plane->type] - plane->dist;
1466 t2 = t->end[plane->type] - plane->dist;
1470 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1471 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1474 midf = t1 / (t1 - t2);
1475 VectorMA(t->start, midf, t->dist, mid);
1477 // recurse both sides, front side first, return if we hit a surface
1478 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1479 return HULLCHECKSTATE_DONE;
1481 // test each surface on the node
1482 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1483 if (t->trace->hittexture)
1484 return HULLCHECKSTATE_DONE;
1486 // recurse back side
1487 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1489 leaf = (const mleaf_t *)node;
1490 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1491 if (!t->trace->startfound)
1493 t->trace->startfound = true;
1494 t->trace->startsupercontents |= side;
1496 if (side & SUPERCONTENTS_LIQUIDSMASK)
1497 t->trace->inwater = true;
1499 t->trace->inopen = true;
1500 if (side & t->trace->hitsupercontentsmask)
1502 // if the first leaf is solid, set startsolid
1503 if (t->trace->allsolid)
1504 t->trace->startsolid = true;
1505 return HULLCHECKSTATE_SOLID;
1509 t->trace->allsolid = false;
1510 return HULLCHECKSTATE_EMPTY;
1514 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)
1516 RecursiveHullCheckTraceInfo_t rhc;
1518 memset(&rhc, 0, sizeof(rhc));
1519 memset(trace, 0, sizeof(trace_t));
1521 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1522 rhc.trace->fraction = 1;
1523 rhc.trace->realfraction = 1;
1524 rhc.trace->allsolid = true;
1525 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1526 VectorCopy(start, rhc.start);
1527 VectorCopy(end, rhc.end);
1528 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1529 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1530 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1533 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1536 unsigned char *outstart = out;
1537 while (out < outend)
1541 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));
1551 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));
1554 for (c = *in++;c > 0;c--)
1558 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));
1569 R_Q1BSP_LoadSplitSky
1571 A sky texture is 256*128, with the right side being a masked overlay
1574 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1579 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1580 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1582 // allocate a texture pool if we need it
1583 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1584 loadmodel->texturepool = R_AllocTexturePool();
1586 if (bytesperpixel == 4)
1588 for (y = 0;y < h;y++)
1590 for (x = 0;x < w;x++)
1592 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1593 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1599 // make an average value for the back to avoid
1600 // a fringe on the top level
1609 for (y = 0;y < h;y++)
1611 for (x = 0;x < w;x++)
1613 p = src[x*width+y+w];
1614 r += palette_rgb[p][0];
1615 g += palette_rgb[p][1];
1616 b += palette_rgb[p][2];
1619 bgra.b[2] = r/(w*h);
1620 bgra.b[1] = g/(w*h);
1621 bgra.b[0] = b/(w*h);
1623 for (y = 0;y < h;y++)
1625 for (x = 0;x < w;x++)
1627 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1629 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1634 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1635 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1636 Mem_Free(solidpixels);
1637 Mem_Free(alphapixels);
1640 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1642 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1643 skinframe_t *skinframe;
1644 texture_t *tx, *tx2, *anims[10], *altanims[10];
1645 texture_t backuptex;
1646 unsigned char *data, *mtdata;
1648 char mapname[MAX_QPATH], name[MAX_QPATH];
1649 unsigned char zeroopaque[4], zerotrans[4];
1652 Vector4Set(zeroopaque, 0, 0, 0, 255);
1653 Vector4Set(zerotrans, 0, 0, 0, 128);
1655 loadmodel->data_textures = NULL;
1657 // add two slots for notexture walls and notexture liquids
1660 nummiptex = MSG_ReadLittleLong(sb);
1661 loadmodel->num_textures = nummiptex + 2;
1662 loadmodel->num_texturesperskin = loadmodel->num_textures;
1666 loadmodel->num_textures = 2;
1667 loadmodel->num_texturesperskin = loadmodel->num_textures;
1670 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1672 // fill out all slots with notexture
1673 if (cls.state != ca_dedicated)
1674 skinframe = R_SkinFrame_LoadMissing();
1677 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1679 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1682 if (cls.state != ca_dedicated)
1684 tx->numskinframes = 1;
1685 tx->skinframerate = 1;
1686 tx->skinframes[0] = skinframe;
1687 tx->currentskinframe = tx->skinframes[0];
1689 tx->basematerialflags = MATERIALFLAG_WALL;
1690 if (i == loadmodel->num_textures - 1)
1692 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1693 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1694 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1698 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1699 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1701 tx->currentframe = tx;
1703 // clear water settings
1706 tx->refractfactor = 1;
1707 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1708 tx->reflectfactor = 1;
1709 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1710 tx->r_water_wateralpha = 1;
1711 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1712 tx->offsetscale = 1;
1714 tx->specularscalemod = 1;
1715 tx->specularpowermod = 1;
1716 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1717 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1718 // JUST GREP FOR "specularscalemod = 1".
1723 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1727 s = loadmodel->name;
1728 if (!strncasecmp(s, "maps/", 5))
1730 FS_StripExtension(s, mapname, sizeof(mapname));
1732 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1733 // LordHavoc: mostly rewritten map texture loader
1734 for (i = 0;i < nummiptex;i++)
1736 doffset = MSG_ReadLittleLong(sb);
1737 if (r_nosurftextures.integer)
1741 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1745 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1747 // copy name, but only up to 16 characters
1748 // (the output buffer can hold more than this, but the input buffer is
1750 for (j = 0;j < 16;j++)
1751 name[j] = MSG_ReadByte(&miptexsb);
1753 // pretty up the buffer (replacing any trailing garbage with 0)
1754 for (j = strlen(name);j < 16;j++)
1759 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1760 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1763 mtwidth = MSG_ReadLittleLong(&miptexsb);
1764 mtheight = MSG_ReadLittleLong(&miptexsb);
1766 j = MSG_ReadLittleLong(&miptexsb);
1770 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1772 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1775 mtdata = miptexsb.data + j;
1778 if ((mtwidth & 15) || (mtheight & 15))
1779 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1781 // LordHavoc: force all names to lowercase
1782 for (j = 0;name[j];j++)
1783 if (name[j] >= 'A' && name[j] <= 'Z')
1784 name[j] += 'a' - 'A';
1786 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1787 backuptex = loadmodel->data_textures[i];
1788 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1790 loadmodel->data_textures[i] = backuptex;
1792 tx = loadmodel->data_textures + i;
1793 strlcpy(tx->name, name, sizeof(tx->name));
1794 tx->width = mtwidth;
1795 tx->height = mtheight;
1797 if (tx->name[0] == '*')
1799 if (!strncmp(tx->name, "*lava", 5))
1801 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1802 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1804 else if (!strncmp(tx->name, "*slime", 6))
1806 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1807 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1811 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1812 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1815 else if (!strncmp(tx->name, "sky", 3))
1817 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1818 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1819 // for the surface traceline we need to hit this surface as a solid...
1820 tx->supercontents |= SUPERCONTENTS_SOLID;
1824 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1825 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1828 if (cls.state != ca_dedicated)
1830 // LordHavoc: HL sky textures are entirely different than quake
1831 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1833 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1835 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1836 if (data && image_width == image_height * 2)
1838 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1841 else if (mtdata != NULL)
1842 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1846 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);
1848 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);
1850 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1853 // did not find external texture, load it from the bsp or wad3
1854 if (loadmodel->brush.ishlbsp)
1856 // internal texture overrides wad
1857 unsigned char *pixels, *freepixels;
1858 pixels = freepixels = NULL;
1860 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1862 pixels = freepixels = W_GetTextureBGRA(tx->name);
1865 tx->width = image_width;
1866 tx->height = image_height;
1867 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1870 Mem_Free(freepixels);
1872 else if (mtdata) // texture included
1873 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1875 // if skinframe is still NULL the "missing" texture will be used
1877 tx->skinframes[0] = skinframe;
1879 // LordHavoc: some Tenebrae textures get replaced by black
1880 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1881 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1882 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1883 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1886 tx->basematerialflags = MATERIALFLAG_WALL;
1887 if (tx->name[0] == '*')
1889 // LordHavoc: some turbulent textures should not be affected by wateralpha
1890 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1891 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1892 else if (!strncmp(tx->name,"*lava",5)
1893 || !strncmp(tx->name,"*teleport",9)
1894 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1895 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1897 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1898 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1899 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | 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)
1925 if (tx->anim_total[0] || tx->anim_total[1])
1926 continue; // already sequenced
1928 // find the number of frames in the animation
1929 memset(anims, 0, sizeof(anims));
1930 memset(altanims, 0, sizeof(altanims));
1932 for (j = i;j < nummiptex;j++)
1934 tx2 = loadmodel->data_textures + j;
1935 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1939 if (num >= '0' && num <= '9')
1940 anims[num - '0'] = tx2;
1941 else if (num >= 'a' && num <= 'j')
1942 altanims[num - 'a'] = tx2;
1944 Con_Printf("Bad animating texture %s\n", tx->name);
1948 for (j = 0;j < 10;j++)
1955 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1958 for (j = 0;j < max;j++)
1962 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1966 for (j = 0;j < altmax;j++)
1970 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1979 // if there is no alternate animation, duplicate the primary
1980 // animation into the alternate
1982 for (k = 0;k < 10;k++)
1983 altanims[k] = anims[k];
1986 // link together the primary animation
1987 for (j = 0;j < max;j++)
1990 tx2->animated = true;
1991 tx2->anim_total[0] = max;
1992 tx2->anim_total[1] = altmax;
1993 for (k = 0;k < 10;k++)
1995 tx2->anim_frames[0][k] = anims[k];
1996 tx2->anim_frames[1][k] = altanims[k];
2000 // if there really is an alternate anim...
2001 if (anims[0] != altanims[0])
2003 // link together the alternate animation
2004 for (j = 0;j < altmax;j++)
2007 tx2->animated = true;
2008 // the primary/alternate are reversed here
2009 tx2->anim_total[0] = altmax;
2010 tx2->anim_total[1] = max;
2011 for (k = 0;k < 10;k++)
2013 tx2->anim_frames[0][k] = altanims[k];
2014 tx2->anim_frames[1][k] = anims[k];
2021 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2024 unsigned char *in, *out, *data, d;
2025 char litfilename[MAX_QPATH];
2026 char dlitfilename[MAX_QPATH];
2027 fs_offset_t filesize;
2028 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2030 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2031 for (i = 0;i < sb->cursize;i++)
2032 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2034 else // LordHavoc: bsp version 29 (normal white lighting)
2036 // LordHavoc: hope is not lost yet, check for a .lit file to load
2037 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2038 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2039 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2040 strlcat (litfilename, ".lit", sizeof (litfilename));
2041 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2042 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2045 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2047 i = LittleLong(((int *)data)[1]);
2050 if (developer_loading.integer)
2051 Con_Printf("loaded %s\n", litfilename);
2052 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2053 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2055 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2058 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2060 i = LittleLong(((int *)data)[1]);
2063 if (developer_loading.integer)
2064 Con_Printf("loaded %s\n", dlitfilename);
2065 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2066 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2067 loadmodel->brushq3.deluxemapping_modelspace = false;
2068 loadmodel->brushq3.deluxemapping = true;
2077 Con_Printf("Unknown .lit file version (%d)\n", i);
2079 else if (filesize == 8)
2080 Con_Print("Empty .lit file, ignoring\n");
2082 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2089 // LordHavoc: oh well, expand the white lighting data
2092 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2094 out = loadmodel->brushq1.lightdata;
2095 for (i = 0;i < sb->cursize;i++)
2105 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2107 loadmodel->brushq1.num_compressedpvs = 0;
2108 loadmodel->brushq1.data_compressedpvs = NULL;
2111 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2112 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2113 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2116 // used only for HalfLife maps
2117 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2119 char key[128], value[4096];
2123 if (!COM_ParseToken_Simple(&data, false, false, true))
2125 if (com_token[0] != '{')
2129 if (!COM_ParseToken_Simple(&data, false, false, true))
2131 if (com_token[0] == '}')
2132 break; // end of worldspawn
2133 if (com_token[0] == '_')
2134 strlcpy(key, com_token + 1, sizeof(key));
2136 strlcpy(key, com_token, sizeof(key));
2137 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2138 key[strlen(key)-1] = 0;
2139 if (!COM_ParseToken_Simple(&data, false, false, true))
2141 dpsnprintf(value, sizeof(value), "%s", com_token);
2142 if (!strcmp("wad", key)) // for HalfLife maps
2144 if (loadmodel->brush.ishlbsp)
2147 for (i = 0;i < (int)sizeof(value);i++)
2148 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2152 for (;i < (int)sizeof(value);i++)
2154 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2155 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2157 else if (value[i] == ';' || value[i] == 0)
2161 W_LoadTextureWadFile(&value[j], false);
2173 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2175 loadmodel->brush.entities = NULL;
2178 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2179 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2180 loadmodel->brush.entities[sb->cursize] = 0;
2181 if (loadmodel->brush.ishlbsp)
2182 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2186 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2190 size_t structsize = 12;
2192 if (sb->cursize % structsize)
2193 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2194 count = sb->cursize / structsize;
2195 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2197 loadmodel->brushq1.vertexes = out;
2198 loadmodel->brushq1.numvertexes = count;
2200 for ( i=0 ; i<count ; i++, out++)
2202 out->position[0] = MSG_ReadLittleFloat(sb);
2203 out->position[1] = MSG_ReadLittleFloat(sb);
2204 out->position[2] = MSG_ReadLittleFloat(sb);
2208 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2212 size_t structsize = (48+4*hullinfo->filehulls);
2214 if (sb->cursize % structsize)
2215 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2217 count = sb->cursize / structsize;
2218 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2220 loadmodel->brushq1.submodels = out;
2221 loadmodel->brush.numsubmodels = count;
2223 for (i = 0; i < count; i++, out++)
2225 // spread out the mins / maxs by a pixel
2226 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2227 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2228 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2229 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2230 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2231 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2232 out->origin[0] = MSG_ReadLittleFloat(sb);
2233 out->origin[1] = MSG_ReadLittleFloat(sb);
2234 out->origin[2] = MSG_ReadLittleFloat(sb);
2235 for (j = 0; j < hullinfo->filehulls; j++)
2236 out->headnode[j] = MSG_ReadLittleLong(sb);
2237 out->visleafs = MSG_ReadLittleLong(sb);
2238 out->firstface = MSG_ReadLittleLong(sb);
2239 out->numfaces = MSG_ReadLittleLong(sb);
2243 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2247 size_t structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2249 if (sb->cursize % structsize)
2250 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2251 count = sb->cursize / structsize;
2252 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2254 loadmodel->brushq1.edges = out;
2255 loadmodel->brushq1.numedges = count;
2257 for ( i=0 ; i<count ; i++, out++)
2259 if (loadmodel->brush.isbsp2)
2261 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2262 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2266 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2267 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2269 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2271 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);
2272 if(!loadmodel->brushq1.numvertexes)
2273 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2281 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2284 int i, j, k, count, miptex;
2285 size_t structsize = 40;
2287 if (sb->cursize % structsize)
2288 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2289 count = sb->cursize / structsize;
2290 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2292 loadmodel->brushq1.texinfo = out;
2293 loadmodel->brushq1.numtexinfo = count;
2295 for (i = 0;i < count;i++, out++)
2297 for (k = 0;k < 2;k++)
2298 for (j = 0;j < 4;j++)
2299 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2301 miptex = MSG_ReadLittleLong(sb);
2302 out->flags = MSG_ReadLittleLong(sb);
2304 out->texture = NULL;
2305 if (loadmodel->data_textures)
2307 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2308 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2310 out->texture = loadmodel->data_textures + miptex;
2312 if (out->flags & TEX_SPECIAL)
2314 // if texture chosen is NULL or the shader needs a lightmap,
2315 // force to notexture water shader
2316 if (out->texture == NULL)
2317 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2321 // if texture chosen is NULL, force to notexture
2322 if (out->texture == NULL)
2323 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2329 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2334 mins[0] = mins[1] = mins[2] = 9999;
2335 maxs[0] = maxs[1] = maxs[2] = -9999;
2337 for (i = 0;i < numverts;i++)
2339 for (j = 0;j < 3;j++, v++)
2349 #define MAX_SUBDIVPOLYTRIANGLES 4096
2350 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2352 static int subdivpolyverts, subdivpolytriangles;
2353 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2354 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2356 static int subdivpolylookupvert(vec3_t v)
2359 for (i = 0;i < subdivpolyverts;i++)
2360 if (subdivpolyvert[i][0] == v[0]
2361 && subdivpolyvert[i][1] == v[1]
2362 && subdivpolyvert[i][2] == v[2])
2364 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2365 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2366 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2367 return subdivpolyverts++;
2370 static void SubdividePolygon(int numverts, float *verts)
2372 int i, i1, i2, i3, f, b, c, p;
2373 vec3_t mins, maxs, front[256], back[256];
2374 float m, *pv, *cv, dist[256], frac;
2377 Host_Error("SubdividePolygon: ran out of verts in buffer");
2379 BoundPoly(numverts, verts, mins, maxs);
2381 for (i = 0;i < 3;i++)
2383 m = (mins[i] + maxs[i]) * 0.5;
2384 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2385 if (maxs[i] - m < 8)
2387 if (m - mins[i] < 8)
2391 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2392 dist[c] = cv[i] - m;
2395 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2399 VectorCopy(pv, front[f]);
2404 VectorCopy(pv, back[b]);
2407 if (dist[p] == 0 || dist[c] == 0)
2409 if ((dist[p] > 0) != (dist[c] > 0) )
2412 frac = dist[p] / (dist[p] - dist[c]);
2413 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2414 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2415 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2421 SubdividePolygon(f, front[0]);
2422 SubdividePolygon(b, back[0]);
2426 i1 = subdivpolylookupvert(verts);
2427 i2 = subdivpolylookupvert(verts + 3);
2428 for (i = 2;i < numverts;i++)
2430 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2432 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2436 i3 = subdivpolylookupvert(verts + i * 3);
2437 subdivpolyindex[subdivpolytriangles][0] = i1;
2438 subdivpolyindex[subdivpolytriangles][1] = i2;
2439 subdivpolyindex[subdivpolytriangles][2] = i3;
2441 subdivpolytriangles++;
2445 //Breaks a polygon up along axial 64 unit
2446 //boundaries so that turbulent and sky warps
2447 //can be done reasonably.
2448 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2454 subdivpolytriangles = 0;
2455 subdivpolyverts = 0;
2456 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2457 if (subdivpolytriangles < 1)
2458 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2460 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2461 mesh->num_vertices = subdivpolyverts;
2462 mesh->num_triangles = subdivpolytriangles;
2463 mesh->vertex = (surfvertex_t *)(mesh + 1);
2464 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2465 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2467 for (i = 0;i < mesh->num_triangles;i++)
2468 for (j = 0;j < 3;j++)
2469 mesh->index[i*3+j] = subdivpolyindex[i][j];
2471 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2473 VectorCopy(subdivpolyvert[i], v->v);
2474 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2475 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2480 extern cvar_t gl_max_lightmapsize;
2481 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2483 msurface_t *surface;
2484 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2485 float texmins[2], texmaxs[2], val;
2486 rtexture_t *lightmaptexture, *deluxemaptexture;
2488 size_t structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2490 if (sb->cursize % structsize)
2491 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2492 count = sb->cursize / structsize;
2493 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2494 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2496 loadmodel->num_surfaces = count;
2498 loadmodel->brushq1.firstrender = true;
2499 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2503 for (surfacenum = 0;surfacenum < count;surfacenum++)
2505 if (loadmodel->brush.isbsp2)
2506 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2508 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2509 totalverts += numedges;
2510 totaltris += numedges - 2;
2513 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2515 lightmaptexture = NULL;
2516 deluxemaptexture = r_texture_blanknormalmap;
2518 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2519 totallightmapsamples = 0;
2523 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2525 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2526 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2527 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2528 firstedge = MSG_ReadLittleLong(sb);
2529 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2530 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2531 for (i = 0;i < MAXLIGHTMAPS;i++)
2532 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2533 lightmapoffset = MSG_ReadLittleLong(sb);
2535 // FIXME: validate edges, texinfo, etc?
2536 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)
2537 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2538 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2539 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2540 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2541 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2543 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2544 surface->texture = surface->lightmapinfo->texinfo->texture;
2546 //surface->flags = surface->texture->flags;
2547 //if (LittleShort(in->side))
2548 // surface->flags |= SURF_PLANEBACK;
2549 //surface->plane = loadmodel->brush.data_planes + planenum;
2551 surface->num_firstvertex = totalverts;
2552 surface->num_vertices = numedges;
2553 surface->num_firsttriangle = totaltris;
2554 surface->num_triangles = numedges - 2;
2555 totalverts += numedges;
2556 totaltris += numedges - 2;
2558 // convert edges back to a normal polygon
2559 for (i = 0;i < surface->num_vertices;i++)
2561 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2563 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2565 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2567 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2568 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2569 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2570 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2571 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2572 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2573 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2574 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2577 for (i = 0;i < surface->num_triangles;i++)
2579 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2580 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2581 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2584 // compile additional data about the surface geometry
2585 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);
2586 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);
2587 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2589 // generate surface extents information
2590 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2591 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2592 for (i = 1;i < surface->num_vertices;i++)
2594 for (j = 0;j < 2;j++)
2596 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2597 texmins[j] = min(texmins[j], val);
2598 texmaxs[j] = max(texmaxs[j], val);
2601 for (i = 0;i < 2;i++)
2603 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2604 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2607 smax = surface->lightmapinfo->extents[0] >> 4;
2608 tmax = surface->lightmapinfo->extents[1] >> 4;
2609 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2610 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2613 surface->lightmaptexture = NULL;
2614 surface->deluxemaptexture = r_texture_blanknormalmap;
2615 if (lightmapoffset == -1)
2617 surface->lightmapinfo->samples = NULL;
2619 // give non-lightmapped water a 1x white lightmap
2620 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2622 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2623 surface->lightmapinfo->styles[0] = 0;
2624 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2628 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2629 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2630 else // LordHavoc: white lighting (bsp version 29)
2632 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2633 if (loadmodel->brushq1.nmaplightdata)
2634 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2637 // check if we should apply a lightmap to this
2638 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2640 if (ssize > 256 || tsize > 256)
2641 Host_Error("Bad surface extents");
2643 if (lightmapsize < ssize)
2644 lightmapsize = ssize;
2645 if (lightmapsize < tsize)
2646 lightmapsize = tsize;
2648 totallightmapsamples += ssize*tsize;
2650 // force lightmap upload on first time seeing the surface
2652 // additionally this is used by the later code to see if a
2653 // lightmap is needed on this surface (rather than duplicating the
2655 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2656 loadmodel->lit = true;
2660 // small maps (such as ammo boxes especially) don't need big lightmap
2661 // textures, so this code tries to guess a good size based on
2662 // totallightmapsamples (size of the lightmaps lump basically), as well as
2663 // trying to max out the size if there is a lot of lightmap data to store
2664 // additionally, never choose a lightmapsize that is smaller than the
2665 // largest surface encountered (as it would fail)
2667 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2670 // now that we've decided the lightmap texture size, we can do the rest
2671 if (cls.state != ca_dedicated)
2673 int stainmapsize = 0;
2674 mod_alloclightmap_state_t allocState;
2676 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2677 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2679 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2680 float u, v, ubase, vbase, uscale, vscale;
2682 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2685 smax = surface->lightmapinfo->extents[0] >> 4;
2686 tmax = surface->lightmapinfo->extents[1] >> 4;
2687 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2688 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2689 stainmapsize += ssize * tsize * 3;
2691 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2693 // allocate a texture pool if we need it
2694 if (loadmodel->texturepool == NULL)
2695 loadmodel->texturepool = R_AllocTexturePool();
2696 // could not find room, make a new lightmap
2697 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2698 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2699 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2700 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);
2701 if (loadmodel->brushq1.nmaplightdata)
2702 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);
2704 Mod_AllocLightmap_Reset(&allocState);
2705 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2707 surface->lightmaptexture = lightmaptexture;
2708 surface->deluxemaptexture = deluxemaptexture;
2709 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2710 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2712 uscale = 1.0f / (float)lightmapsize;
2713 vscale = 1.0f / (float)lightmapsize;
2714 ubase = lightmapx * uscale;
2715 vbase = lightmapy * vscale;
2717 for (i = 0;i < surface->num_vertices;i++)
2719 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);
2720 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);
2721 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2722 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2723 // LordHavoc: calc lightmap data offset for vertex lighting to use
2726 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2730 if (cl_stainmaps.integer)
2732 // allocate stainmaps for permanent marks on walls and clear white
2733 unsigned char *stainsamples = NULL;
2734 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2735 memset(stainsamples, 255, stainmapsize);
2737 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2739 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2741 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2742 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2743 surface->lightmapinfo->stainsamples = stainsamples;
2744 stainsamples += ssize * tsize * 3;
2749 // generate ushort elements array if possible
2750 if (loadmodel->surfmesh.data_element3s)
2751 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2752 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2755 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2758 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2759 node->parent = parent;
2762 // this is a node, recurse to children
2763 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2764 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2765 // combine supercontents of children
2766 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2771 mleaf_t *leaf = (mleaf_t *)node;
2772 // if this is a leaf, calculate supercontents mask from all collidable
2773 // primitives in the leaf (brushes and collision surfaces)
2774 // also flag if the leaf contains any collision surfaces
2775 leaf->combinedsupercontents = 0;
2776 // combine the supercontents values of all brushes in this leaf
2777 for (j = 0;j < leaf->numleafbrushes;j++)
2778 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2779 // check if this leaf contains any collision surfaces (q3 patches)
2780 for (j = 0;j < leaf->numleafsurfaces;j++)
2782 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2783 if (surface->num_collisiontriangles)
2785 leaf->containscollisionsurfaces = true;
2786 leaf->combinedsupercontents |= surface->texture->supercontents;
2792 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2794 int i, j, count, p, child[2];
2796 size_t structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2798 if (sb->cursize % structsize)
2799 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2800 count = sb->cursize / structsize;
2802 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2803 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2805 loadmodel->brush.data_nodes = out;
2806 loadmodel->brush.num_nodes = count;
2808 for ( i=0 ; i<count ; i++, out++)
2810 p = MSG_ReadLittleLong(sb);
2811 out->plane = loadmodel->brush.data_planes + p;
2813 if (loadmodel->brush.isbsp2rmqe)
2815 child[0] = MSG_ReadLittleLong(sb);
2816 child[1] = MSG_ReadLittleLong(sb);
2817 out->mins[0] = MSG_ReadLittleShort(sb);
2818 out->mins[1] = MSG_ReadLittleShort(sb);
2819 out->mins[2] = MSG_ReadLittleShort(sb);
2820 out->maxs[0] = MSG_ReadLittleShort(sb);
2821 out->maxs[1] = MSG_ReadLittleShort(sb);
2822 out->maxs[2] = MSG_ReadLittleShort(sb);
2823 out->firstsurface = MSG_ReadLittleLong(sb);
2824 out->numsurfaces = MSG_ReadLittleLong(sb);
2826 else if (loadmodel->brush.isbsp2)
2828 child[0] = MSG_ReadLittleLong(sb);
2829 child[1] = MSG_ReadLittleLong(sb);
2830 out->mins[0] = MSG_ReadLittleFloat(sb);
2831 out->mins[1] = MSG_ReadLittleFloat(sb);
2832 out->mins[2] = MSG_ReadLittleFloat(sb);
2833 out->maxs[0] = MSG_ReadLittleFloat(sb);
2834 out->maxs[1] = MSG_ReadLittleFloat(sb);
2835 out->maxs[2] = MSG_ReadLittleFloat(sb);
2836 out->firstsurface = MSG_ReadLittleLong(sb);
2837 out->numsurfaces = MSG_ReadLittleLong(sb);
2841 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2842 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2843 if (child[0] >= count)
2845 if (child[1] >= count)
2848 out->mins[0] = MSG_ReadLittleShort(sb);
2849 out->mins[1] = MSG_ReadLittleShort(sb);
2850 out->mins[2] = MSG_ReadLittleShort(sb);
2851 out->maxs[0] = MSG_ReadLittleShort(sb);
2852 out->maxs[1] = MSG_ReadLittleShort(sb);
2853 out->maxs[2] = MSG_ReadLittleShort(sb);
2855 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2856 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2859 for (j=0 ; j<2 ; j++)
2861 // LordHavoc: this code supports broken bsp files produced by
2862 // arguire qbsp which can produce more than 32768 nodes, any value
2863 // below count is assumed to be a node number, any other value is
2864 // assumed to be a leaf number
2868 if (p < loadmodel->brush.num_nodes)
2869 out->children[j] = loadmodel->brush.data_nodes + p;
2872 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2873 // map it to the solid leaf
2874 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2879 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2881 if (p < loadmodel->brush.num_leafs)
2882 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2885 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2886 // map it to the solid leaf
2887 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2893 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2896 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2899 int i, j, count, p, firstmarksurface, nummarksurfaces;
2900 size_t structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2902 if (sb->cursize % structsize)
2903 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2904 count = sb->cursize / structsize;
2905 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2907 loadmodel->brush.data_leafs = out;
2908 loadmodel->brush.num_leafs = count;
2909 // get visleafs from the submodel data
2910 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2911 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2912 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2913 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2915 // FIXME: this function could really benefit from some error checking
2916 for ( i=0 ; i<count ; i++, out++)
2918 out->contents = MSG_ReadLittleLong(sb);
2920 out->clusterindex = i - 1;
2921 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2922 out->clusterindex = -1;
2924 p = MSG_ReadLittleLong(sb);
2925 // ignore visofs errors on leaf 0 (solid)
2926 if (p >= 0 && out->clusterindex >= 0)
2928 if (p >= loadmodel->brushq1.num_compressedpvs)
2929 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2931 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);
2934 if (loadmodel->brush.isbsp2rmqe)
2936 out->mins[0] = MSG_ReadLittleShort(sb);
2937 out->mins[1] = MSG_ReadLittleShort(sb);
2938 out->mins[2] = MSG_ReadLittleShort(sb);
2939 out->maxs[0] = MSG_ReadLittleShort(sb);
2940 out->maxs[1] = MSG_ReadLittleShort(sb);
2941 out->maxs[2] = MSG_ReadLittleShort(sb);
2943 firstmarksurface = MSG_ReadLittleLong(sb);
2944 nummarksurfaces = MSG_ReadLittleLong(sb);
2946 else if (loadmodel->brush.isbsp2)
2948 out->mins[0] = MSG_ReadLittleFloat(sb);
2949 out->mins[1] = MSG_ReadLittleFloat(sb);
2950 out->mins[2] = MSG_ReadLittleFloat(sb);
2951 out->maxs[0] = MSG_ReadLittleFloat(sb);
2952 out->maxs[1] = MSG_ReadLittleFloat(sb);
2953 out->maxs[2] = MSG_ReadLittleFloat(sb);
2955 firstmarksurface = MSG_ReadLittleLong(sb);
2956 nummarksurfaces = MSG_ReadLittleLong(sb);
2960 out->mins[0] = MSG_ReadLittleShort(sb);
2961 out->mins[1] = MSG_ReadLittleShort(sb);
2962 out->mins[2] = MSG_ReadLittleShort(sb);
2963 out->maxs[0] = MSG_ReadLittleShort(sb);
2964 out->maxs[1] = MSG_ReadLittleShort(sb);
2965 out->maxs[2] = MSG_ReadLittleShort(sb);
2967 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2968 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2971 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2973 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2974 out->numleafsurfaces = nummarksurfaces;
2978 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2979 out->firstleafsurface = NULL;
2980 out->numleafsurfaces = 0;
2983 for (j = 0;j < 4;j++)
2984 out->ambient_sound_level[j] = MSG_ReadByte(sb);
2988 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2992 const unsigned char *pvs;
2993 // if there's no vis data, assume supported (because everything is visible all the time)
2994 if (!loadmodel->brush.data_pvsclusters)
2996 // check all liquid leafs to see if they can see into empty leafs, if any
2997 // can we can assume this map supports r_wateralpha
2998 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3000 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3002 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3003 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3004 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3011 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3016 size_t structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3018 if (sb->cursize % structsize)
3019 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3020 count = sb->cursize / structsize;
3021 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3023 loadmodel->brushq1.clipnodes = out;
3024 loadmodel->brushq1.numclipnodes = count;
3026 for (i = 1; i < MAX_MAP_HULLS; i++)
3028 hull = &loadmodel->brushq1.hulls[i];
3029 hull->clipnodes = out;
3030 hull->firstclipnode = 0;
3031 hull->lastclipnode = count-1;
3032 hull->planes = loadmodel->brush.data_planes;
3033 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3034 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3035 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3036 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3037 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3038 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3039 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3042 for (i=0 ; i<count ; i++, out++)
3044 out->planenum = MSG_ReadLittleLong(sb);
3045 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3046 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3047 if (loadmodel->brush.isbsp2)
3049 out->children[0] = MSG_ReadLittleLong(sb);
3050 out->children[1] = MSG_ReadLittleLong(sb);
3051 if (out->children[0] >= count)
3052 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3053 if (out->children[1] >= count)
3054 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3058 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3059 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3060 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3061 if (out->children[0] >= count)
3062 out->children[0] -= 65536;
3063 if (out->children[1] >= count)
3064 out->children[1] -= 65536;
3069 //Duplicate the drawing hull structure as a clipping hull
3070 static void Mod_Q1BSP_MakeHull0(void)
3077 hull = &loadmodel->brushq1.hulls[0];
3079 in = loadmodel->brush.data_nodes;
3080 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3082 hull->clipnodes = out;
3083 hull->firstclipnode = 0;
3084 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3085 hull->planes = loadmodel->brush.data_planes;
3087 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3089 out->planenum = in->plane - loadmodel->brush.data_planes;
3090 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3091 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3095 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3098 size_t structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3100 if (sb->cursize % structsize)
3101 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3102 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3103 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3105 if (loadmodel->brush.isbsp2)
3107 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3109 j = MSG_ReadLittleLong(sb);
3110 if (j < 0 || j >= loadmodel->num_surfaces)
3111 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3112 loadmodel->brush.data_leafsurfaces[i] = j;
3117 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3119 j = (unsigned short) MSG_ReadLittleShort(sb);
3120 if (j >= loadmodel->num_surfaces)
3121 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3122 loadmodel->brush.data_leafsurfaces[i] = j;
3127 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3130 size_t structsize = 4;
3132 if (sb->cursize % structsize)
3133 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3134 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3135 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3137 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3138 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3142 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3146 size_t structsize = 20;
3148 if (sb->cursize % structsize)
3149 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3150 loadmodel->brush.num_planes = sb->cursize / structsize;
3151 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3153 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3155 out->normal[0] = MSG_ReadLittleFloat(sb);
3156 out->normal[1] = MSG_ReadLittleFloat(sb);
3157 out->normal[2] = MSG_ReadLittleFloat(sb);
3158 out->dist = MSG_ReadLittleFloat(sb);
3159 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3164 static void Mod_Q1BSP_LoadMapBrushes(void)
3168 int submodel, numbrushes;
3169 qboolean firstbrush;
3170 char *text, *maptext;
3171 char mapfilename[MAX_QPATH];
3172 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3173 strlcat (mapfilename, ".map", sizeof (mapfilename));
3174 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3178 if (!COM_ParseToken_Simple(&data, false, false, true))
3183 if (!COM_ParseToken_Simple(&data, false, false, true))
3185 if (com_token[0] != '{')
3191 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3194 if (!COM_ParseToken_Simple(&data, false, false, true))
3196 if (com_token[0] == '}')
3197 break; // end of entity
3198 if (com_token[0] == '{')
3205 if (submodel > loadmodel->brush.numsubmodels)
3207 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3211 model = loadmodel->brush.submodels[submodel];
3218 if (!COM_ParseToken_Simple(&data, false, false, true))
3220 if (com_token[0] == '}')
3221 break; // end of brush
3222 // each brush face should be this format:
3223 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3224 // FIXME: support hl .map format
3225 for (pointnum = 0;pointnum < 3;pointnum++)
3227 COM_ParseToken_Simple(&data, false, false, true);
3228 for (componentnum = 0;componentnum < 3;componentnum++)
3230 COM_ParseToken_Simple(&data, false, false, true);
3231 point[pointnum][componentnum] = atof(com_token);
3233 COM_ParseToken_Simple(&data, false, false, true);
3235 COM_ParseToken_Simple(&data, false, false, true);
3236 strlcpy(facetexture, com_token, sizeof(facetexture));
3237 COM_ParseToken_Simple(&data, false, false, true);
3238 //scroll_s = atof(com_token);
3239 COM_ParseToken_Simple(&data, false, false, true);
3240 //scroll_t = atof(com_token);
3241 COM_ParseToken_Simple(&data, false, false, true);
3242 //rotate = atof(com_token);
3243 COM_ParseToken_Simple(&data, false, false, true);
3244 //scale_s = atof(com_token);
3245 COM_ParseToken_Simple(&data, false, false, true);
3246 //scale_t = atof(com_token);
3247 TriangleNormal(point[0], point[1], point[2], planenormal);
3248 VectorNormalizeDouble(planenormal);
3249 planedist = DotProduct(point[0], planenormal);
3250 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3260 #define MAX_PORTALPOINTS 64
3262 typedef struct portal_s
3265 mnode_t *nodes[2]; // [0] = front side of plane
3266 struct portal_s *next[2];
3268 double points[3*MAX_PORTALPOINTS];
3269 struct portal_s *chain; // all portals are linked into a list
3273 static memexpandablearray_t portalarray;
3275 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3277 // process only nodes (leafs already had their box calculated)
3281 // calculate children first
3282 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3283 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3285 // make combined bounding box from children
3286 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3287 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3288 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3289 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3290 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3291 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3294 static void Mod_Q1BSP_FinalizePortals(void)
3296 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3300 mleaf_t *leaf, *endleaf;
3302 // tally up portal and point counts and recalculate bounding boxes for all
3303 // leafs (because qbsp is very sloppy)
3304 leaf = loadmodel->brush.data_leafs;
3305 endleaf = leaf + loadmodel->brush.num_leafs;
3306 if (mod_recalculatenodeboxes.integer)
3308 for (;leaf < endleaf;leaf++)
3310 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3311 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3316 for (portalindex = 0;portalindex < portalrange;portalindex++)
3318 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3321 // note: this check must match the one below or it will usually corrupt memory
3322 // 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
3323 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3326 numpoints += p->numpoints * 2;
3329 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3330 loadmodel->brush.num_portals = numportals;
3331 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3332 loadmodel->brush.num_portalpoints = numpoints;
3333 // clear all leaf portal chains
3334 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3335 loadmodel->brush.data_leafs[i].portals = NULL;
3336 // process all portals in the global portal chain, while freeing them
3337 portal = loadmodel->brush.data_portals;
3338 point = loadmodel->brush.data_portalpoints;
3339 for (portalindex = 0;portalindex < portalrange;portalindex++)
3341 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3344 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3346 // note: this check must match the one above or it will usually corrupt memory
3347 // 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
3348 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3350 // first make the back to front portal(forward portal)
3351 portal->points = point;
3352 portal->numpoints = p->numpoints;
3353 portal->plane.dist = p->plane.dist;
3354 VectorCopy(p->plane.normal, portal->plane.normal);
3355 portal->here = (mleaf_t *)p->nodes[1];
3356 portal->past = (mleaf_t *)p->nodes[0];
3358 for (j = 0;j < portal->numpoints;j++)
3360 VectorCopy(p->points + j*3, point->position);
3363 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3364 PlaneClassify(&portal->plane);
3366 // link into leaf's portal chain
3367 portal->next = portal->here->portals;
3368 portal->here->portals = portal;
3370 // advance to next portal
3373 // then make the front to back portal(backward portal)
3374 portal->points = point;
3375 portal->numpoints = p->numpoints;
3376 portal->plane.dist = -p->plane.dist;
3377 VectorNegate(p->plane.normal, portal->plane.normal);
3378 portal->here = (mleaf_t *)p->nodes[0];
3379 portal->past = (mleaf_t *)p->nodes[1];
3381 for (j = portal->numpoints - 1;j >= 0;j--)
3383 VectorCopy(p->points + j*3, point->position);
3386 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3387 PlaneClassify(&portal->plane);
3389 // link into leaf's portal chain
3390 portal->next = portal->here->portals;
3391 portal->here->portals = portal;
3393 // advance to next portal
3396 // add the portal's polygon points to the leaf bounding boxes
3397 if (mod_recalculatenodeboxes.integer)
3399 for (i = 0;i < 2;i++)
3401 leaf = (mleaf_t *)p->nodes[i];
3402 for (j = 0;j < p->numpoints;j++)
3404 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3405 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3406 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3407 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3408 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3409 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3415 // now recalculate the node bounding boxes from the leafs
3416 if (mod_recalculatenodeboxes.integer)
3417 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3425 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3428 Host_Error("AddPortalToNodes: NULL front node");
3430 Host_Error("AddPortalToNodes: NULL back node");
3431 if (p->nodes[0] || p->nodes[1])
3432 Host_Error("AddPortalToNodes: already included");
3433 // 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
3435 p->nodes[0] = front;
3436 p->next[0] = (portal_t *)front->portals;
3437 front->portals = (mportal_t *)p;
3440 p->next[1] = (portal_t *)back->portals;
3441 back->portals = (mportal_t *)p;
3446 RemovePortalFromNode
3449 static void RemovePortalFromNodes(portal_t *portal)
3453 void **portalpointer;
3455 for (i = 0;i < 2;i++)
3457 node = portal->nodes[i];
3459 portalpointer = (void **) &node->portals;
3462 t = (portal_t *)*portalpointer;
3464 Host_Error("RemovePortalFromNodes: portal not in leaf");
3468 if (portal->nodes[0] == node)
3470 *portalpointer = portal->next[0];
3471 portal->nodes[0] = NULL;
3473 else if (portal->nodes[1] == node)
3475 *portalpointer = portal->next[1];
3476 portal->nodes[1] = NULL;
3479 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3483 if (t->nodes[0] == node)
3484 portalpointer = (void **) &t->next[0];
3485 else if (t->nodes[1] == node)
3486 portalpointer = (void **) &t->next[1];
3488 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3493 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3494 static double *portalpointsbuffer;
3495 static int portalpointsbufferoffset;
3496 static int portalpointsbuffersize;
3497 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3500 mnode_t *front, *back, *other_node;
3501 mplane_t clipplane, *plane;
3502 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3503 int numfrontpoints, numbackpoints;
3504 double *frontpoints, *backpoints;
3506 // if a leaf, we're done
3510 // get some space for our clipping operations to use
3511 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3513 portalpointsbuffersize = portalpointsbufferoffset * 2;
3514 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3516 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3517 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3518 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3519 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3521 plane = node->plane;
3523 front = node->children[0];
3524 back = node->children[1];
3526 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3528 // create the new portal by generating a polygon for the node plane,
3529 // and clipping it by all of the other portals(which came from nodes above this one)
3530 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3531 nodeportal->plane = *plane;
3533 // 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)
3534 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);
3535 nodeportal->numpoints = 4;
3536 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3537 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3539 clipplane = portal->plane;
3540 if (portal->nodes[0] == portal->nodes[1])
3541 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3542 if (portal->nodes[0] == node)
3544 else if (portal->nodes[1] == node)
3546 clipplane.dist = -clipplane.dist;
3547 VectorNegate(clipplane.normal, clipplane.normal);
3552 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3553 side = 0; // hush warning
3556 for (i = 0;i < nodeportal->numpoints*3;i++)
3557 frontpoints[i] = nodeportal->points[i];
3558 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);
3559 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3563 if (nodeportal->numpoints < 3)
3565 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3566 nodeportal->numpoints = 0;
3568 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3570 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3571 nodeportal->numpoints = 0;
3574 AddPortalToNodes(nodeportal, front, back);
3576 // split the portals of this node along this node's plane and assign them to the children of this node
3577 // (migrating the portals downward through the tree)
3578 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3580 if (portal->nodes[0] == portal->nodes[1])
3581 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3582 if (portal->nodes[0] == node)
3584 else if (portal->nodes[1] == node)
3588 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3589 side = 0; // hush warning
3591 nextportal = portal->next[side];
3592 if (!portal->numpoints)
3595 other_node = portal->nodes[!side];
3596 RemovePortalFromNodes(portal);
3598 // cut the portal into two portals, one on each side of the node plane
3599 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);
3601 if (!numfrontpoints)
3604 AddPortalToNodes(portal, back, other_node);
3606 AddPortalToNodes(portal, other_node, back);
3612 AddPortalToNodes(portal, front, other_node);
3614 AddPortalToNodes(portal, other_node, front);
3618 // the portal is split
3619 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3620 temp = splitportal->chain;
3621 *splitportal = *portal;
3622 splitportal->chain = temp;
3623 for (i = 0;i < numbackpoints*3;i++)
3624 splitportal->points[i] = backpoints[i];
3625 splitportal->numpoints = numbackpoints;
3626 for (i = 0;i < numfrontpoints*3;i++)
3627 portal->points[i] = frontpoints[i];
3628 portal->numpoints = numfrontpoints;
3632 AddPortalToNodes(portal, front, other_node);
3633 AddPortalToNodes(splitportal, back, other_node);
3637 AddPortalToNodes(portal, other_node, front);
3638 AddPortalToNodes(splitportal, other_node, back);
3642 Mod_Q1BSP_RecursiveNodePortals(front);
3643 Mod_Q1BSP_RecursiveNodePortals(back);
3645 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3648 static void Mod_Q1BSP_MakePortals(void)
3650 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3651 portalpointsbufferoffset = 0;
3652 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3653 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3654 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3655 Mem_Free(portalpointsbuffer);
3656 portalpointsbuffer = NULL;
3657 portalpointsbufferoffset = 0;
3658 portalpointsbuffersize = 0;
3659 Mod_Q1BSP_FinalizePortals();
3660 Mem_ExpandableArray_FreeArray(&portalarray);
3663 //Returns PVS data for a given point
3664 //(note: can return NULL)
3665 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3668 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3670 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3671 if (((mleaf_t *)node)->clusterindex >= 0)
3672 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3677 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)
3681 float d = PlaneDiff(org, node->plane);
3683 node = node->children[0];
3684 else if (d < -radius)
3685 node = node->children[1];
3688 // go down both sides
3689 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3690 node = node->children[1];
3693 // if this leaf is in a cluster, accumulate the pvs bits
3694 if (((mleaf_t *)node)->clusterindex >= 0)
3697 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3698 for (i = 0;i < pvsbytes;i++)
3699 pvsbuffer[i] |= pvs[i];
3703 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3704 //of the given point.
3705 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3707 int bytes = model->brush.num_pvsclusterbytes;
3708 bytes = min(bytes, pvsbufferlength);
3709 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3711 memset(pvsbuffer, 0xFF, bytes);
3715 memset(pvsbuffer, 0, bytes);
3716 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3720 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3725 VectorSubtract(inmaxs, inmins, size);
3726 if (cmodel->brush.ishlbsp)
3729 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3730 else if (size[0] <= 32)
3732 if (size[2] < 54) // pick the nearest of 36 or 72
3733 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3735 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3738 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3743 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3744 else if (size[0] <= 32)
3745 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3747 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3749 VectorCopy(inmins, outmins);
3750 VectorAdd(inmins, hull->clip_size, outmaxs);
3753 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3756 int numshadowmeshtriangles = 0;
3757 msurface_t *surface;
3758 if (cls.state == ca_dedicated)
3760 // make a single combined shadow mesh to allow optimized shadow volume creation
3762 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3764 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3765 numshadowmeshtriangles += surface->num_triangles;
3767 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3768 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3769 if (surface->num_triangles > 0)
3770 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));
3771 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3772 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3773 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3775 return numshadowmeshtriangles;
3778 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);
3780 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3783 sizebuf_t lumpsb[HEADER_LUMPS];
3785 float dist, modelyawradius, modelradius;
3786 msurface_t *surface;
3787 hullinfo_t hullinfo;
3788 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3789 model_brush_lightstyleinfo_t styleinfo[256];
3790 unsigned char *datapointer;
3793 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3795 mod->type = mod_brushq1;
3797 mod->brush.isbsp2 = false;
3798 mod->brush.ishlbsp = false;
3799 i = MSG_ReadLittleLong(&sb);
3803 mod->modeldatatypestring = "Q1BSP";
3806 mod->brush.ishlbsp = true;
3807 mod->modeldatatypestring = "HLBSP";
3809 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3810 mod->brush.isbsp2 = true;
3811 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3812 mod->modeldatatypestring = "Q1BSP2rmqe";
3814 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3815 mod->brush.isbsp2 = true;
3816 mod->modeldatatypestring = "Q1BSP2";
3819 mod->modeldatatypestring = "Unknown BSP";
3820 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);
3824 // fill in hull info
3825 VectorClear (hullinfo.hullsizes[0][0]);
3826 VectorClear (hullinfo.hullsizes[0][1]);
3827 if (mod->brush.ishlbsp)
3829 hullinfo.filehulls = 4;
3830 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3831 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3832 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3833 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3834 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3835 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3839 hullinfo.filehulls = 4;
3840 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3841 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3842 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3843 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3847 for (i = 0; i < HEADER_LUMPS; i++)
3849 int offset = MSG_ReadLittleLong(&sb);
3850 int size = MSG_ReadLittleLong(&sb);
3851 if (offset < 0 || offset + size > sb.cursize)
3852 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);
3853 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3856 mod->soundfromcenter = true;
3857 mod->TraceBox = Mod_Q1BSP_TraceBox;
3858 mod->TraceLine = Mod_Q1BSP_TraceLine;
3859 mod->TracePoint = Mod_Q1BSP_TracePoint;
3860 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3861 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3862 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3863 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3864 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3865 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3866 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3867 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3868 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3869 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3870 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3871 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3872 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3873 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3874 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3875 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3876 mod->Draw = R_Q1BSP_Draw;
3877 mod->DrawDepth = R_Q1BSP_DrawDepth;
3878 mod->DrawDebug = R_Q1BSP_DrawDebug;
3879 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3880 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3881 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3882 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3883 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3884 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3885 mod->DrawLight = R_Q1BSP_DrawLight;
3889 mod->brush.qw_md4sum = 0;
3890 mod->brush.qw_md4sum2 = 0;
3891 for (i = 0;i < HEADER_LUMPS;i++)
3894 if (i == LUMP_ENTITIES)
3896 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3897 mod->brush.qw_md4sum ^= LittleLong(temp);
3898 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3900 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3903 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3904 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3905 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3906 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3907 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3908 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3909 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3910 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3911 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3912 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3913 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3914 // load submodels before leafs because they contain the number of vis leafs
3915 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3916 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3917 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3918 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3920 for (i = 0; i < HEADER_LUMPS; i++)
3921 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3922 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3924 // check if the map supports transparent water rendering
3925 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3927 if (mod->brushq1.data_compressedpvs)
3928 Mem_Free(mod->brushq1.data_compressedpvs);
3929 mod->brushq1.data_compressedpvs = NULL;
3930 mod->brushq1.num_compressedpvs = 0;
3932 Mod_Q1BSP_MakeHull0();
3933 if (mod_bsp_portalize.integer)
3934 Mod_Q1BSP_MakePortals();
3936 mod->numframes = 2; // regular and alternate animation
3939 // make a single combined shadow mesh to allow optimized shadow volume creation
3940 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3942 if (loadmodel->brush.numsubmodels)
3943 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3945 // LordHavoc: to clear the fog around the original quake submodel code, I
3947 // first of all, some background info on the submodels:
3948 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3949 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3950 // now the weird for loop itself:
3951 // the loop functions in an odd way, on each iteration it sets up the
3952 // current 'mod' model (which despite the confusing code IS the model of
3953 // the number i), at the end of the loop it duplicates the model to become
3954 // the next submodel, and loops back to set up the new submodel.
3956 // LordHavoc: now the explanation of my sane way (which works identically):
3957 // set up the world model, then on each submodel copy from the world model
3958 // and set up the submodel with the respective model info.
3959 totalstylesurfaces = 0;
3961 for (i = 0;i < mod->brush.numsubmodels;i++)
3963 memset(stylecounts, 0, sizeof(stylecounts));
3964 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3966 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3967 for (j = 0;j < MAXLIGHTMAPS;j++)
3968 stylecounts[surface->lightmapinfo->styles[j]]++;
3970 for (k = 0;k < 255;k++)
3974 totalstylesurfaces += stylecounts[k];
3977 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3978 for (i = 0;i < mod->brush.numsubmodels;i++)
3980 // LordHavoc: this code was originally at the end of this loop, but
3981 // has been transformed to something more readable at the start here.
3986 // duplicate the basic information
3987 dpsnprintf(name, sizeof(name), "*%i", i);
3988 mod = Mod_FindName(name, loadmodel->name);
3989 // copy the base model to this one
3991 // rename the clone back to its proper name
3992 strlcpy(mod->name, name, sizeof(mod->name));
3993 mod->brush.parentmodel = loadmodel;
3994 // textures and memory belong to the main model
3995 mod->texturepool = NULL;
3996 mod->mempool = NULL;
3997 mod->brush.GetPVS = NULL;
3998 mod->brush.FatPVS = NULL;
3999 mod->brush.BoxTouchingPVS = NULL;
4000 mod->brush.BoxTouchingLeafPVS = NULL;
4001 mod->brush.BoxTouchingVisibleLeafs = NULL;
4002 mod->brush.FindBoxClusters = NULL;
4003 mod->brush.LightPoint = NULL;
4004 mod->brush.AmbientSoundLevelsForPoint = NULL;
4007 mod->brush.submodel = i;
4009 if (loadmodel->brush.submodels)
4010 loadmodel->brush.submodels[i] = mod;
4012 bm = &mod->brushq1.submodels[i];
4014 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4015 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4017 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4018 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4021 mod->firstmodelsurface = bm->firstface;
4022 mod->nummodelsurfaces = bm->numfaces;
4024 // set node/leaf parents for this submodel
4025 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4027 // make the model surface list (used by shadowing/lighting)
4028 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4029 Mod_MakeSortedSurfaces(mod);
4031 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4032 // (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)
4033 VectorCopy(bm->mins, mod->normalmins);
4034 VectorCopy(bm->maxs, mod->normalmaxs);
4035 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4036 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4037 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4038 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4039 modelradius = modelyawradius + modelradius * modelradius;
4040 modelyawradius = sqrt(modelyawradius);
4041 modelradius = sqrt(modelradius);
4042 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4043 mod->yawmins[2] = mod->normalmins[2];
4044 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4045 mod->yawmaxs[2] = mod->normalmaxs[2];
4046 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4047 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4048 mod->radius = modelradius;
4049 mod->radius2 = modelradius * modelradius;
4051 // this gets altered below if sky or water is used
4052 mod->DrawSky = NULL;
4053 mod->DrawAddWaterPlanes = NULL;
4055 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4056 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4057 if (mod->nummodelsurfaces)
4059 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4060 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4062 if (j < mod->nummodelsurfaces)
4063 mod->DrawSky = R_Q1BSP_DrawSky;
4065 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4066 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4068 if (j < mod->nummodelsurfaces)
4069 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4071 // build lightstyle update chains
4072 // (used to rapidly mark lightmapupdateflags on many surfaces
4073 // when d_lightstylevalue changes)
4074 memset(stylecounts, 0, sizeof(stylecounts));
4075 for (k = 0;k < mod->nummodelsurfaces;k++)
4077 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4078 for (j = 0;j < MAXLIGHTMAPS;j++)
4079 stylecounts[surface->lightmapinfo->styles[j]]++;
4081 mod->brushq1.num_lightstyles = 0;
4082 for (k = 0;k < 255;k++)
4086 styleinfo[mod->brushq1.num_lightstyles].style = k;
4087 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4088 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4089 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4090 remapstyles[k] = mod->brushq1.num_lightstyles;
4091 mod->brushq1.num_lightstyles++;
4094 for (k = 0;k < mod->nummodelsurfaces;k++)
4096 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4097 for (j = 0;j < MAXLIGHTMAPS;j++)
4099 if (surface->lightmapinfo->styles[j] != 255)
4101 int r = remapstyles[surface->lightmapinfo->styles[j]];
4102 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4106 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4107 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4111 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4112 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4114 //mod->brushq1.num_visleafs = bm->visleafs;
4116 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4117 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4119 if (mod_q1bsp_polygoncollisions.integer)
4121 mod->collision_bih = mod->render_bih;
4122 // point traces and contents checks still use the bsp tree
4123 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4124 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4125 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4126 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4129 // generate VBOs and other shared data before cloning submodels
4133 Mod_Q1BSP_LoadMapBrushes();
4134 //Mod_Q1BSP_ProcessLightList();
4138 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);
4141 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4145 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4152 in = (void *)(mod_base + l->fileofs);
4153 if (l->filelen % sizeof(*in))
4154 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4155 count = l->filelen / sizeof(*in);
4156 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4159 loadmodel->num = count;
4161 for (i = 0;i < count;i++, in++, out++)
4167 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4174 in = (void *)(mod_base + l->fileofs);
4175 if (l->filelen % sizeof(*in))
4176 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4177 count = l->filelen / sizeof(*in);
4178 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4181 loadmodel->num = count;
4183 for (i = 0;i < count;i++, in++, out++)
4189 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4196 in = (void *)(mod_base + l->fileofs);
4197 if (l->filelen % sizeof(*in))
4198 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4199 count = l->filelen / sizeof(*in);
4200 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4203 loadmodel->num = count;
4205 for (i = 0;i < count;i++, in++, out++)
4211 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4218 in = (void *)(mod_base + l->fileofs);
4219 if (l->filelen % sizeof(*in))
4220 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4221 count = l->filelen / sizeof(*in);
4222 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4225 loadmodel->num = count;
4227 for (i = 0;i < count;i++, in++, out++)
4233 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4240 in = (void *)(mod_base + l->fileofs);
4241 if (l->filelen % sizeof(*in))
4242 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4243 count = l->filelen / sizeof(*in);
4244 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4247 loadmodel->num = count;
4249 for (i = 0;i < count;i++, in++, out++)
4255 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4262 in = (void *)(mod_base + l->fileofs);
4263 if (l->filelen % sizeof(*in))
4264 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4265 count = l->filelen / sizeof(*in);
4266 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4269 loadmodel->num = count;
4271 for (i = 0;i < count;i++, in++, out++)
4277 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4284 in = (void *)(mod_base + l->fileofs);
4285 if (l->filelen % sizeof(*in))
4286 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4287 count = l->filelen / sizeof(*in);
4288 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4291 loadmodel->num = count;
4293 for (i = 0;i < count;i++, in++, out++)
4299 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4306 in = (void *)(mod_base + l->fileofs);
4307 if (l->filelen % sizeof(*in))
4308 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4309 count = l->filelen / sizeof(*in);
4310 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4313 loadmodel->num = count;
4315 for (i = 0;i < count;i++, in++, out++)
4321 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4328 in = (void *)(mod_base + l->fileofs);
4329 if (l->filelen % sizeof(*in))
4330 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4331 count = l->filelen / sizeof(*in);
4332 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4335 loadmodel->num = count;
4337 for (i = 0;i < count;i++, in++, out++)
4343 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4350 in = (void *)(mod_base + l->fileofs);
4351 if (l->filelen % sizeof(*in))
4352 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4353 count = l->filelen / sizeof(*in);
4354 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4357 loadmodel->num = count;
4359 for (i = 0;i < count;i++, in++, out++)
4365 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4372 in = (void *)(mod_base + l->fileofs);
4373 if (l->filelen % sizeof(*in))
4374 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4375 count = l->filelen / sizeof(*in);
4376 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4379 loadmodel->num = count;
4381 for (i = 0;i < count;i++, in++, out++)
4387 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4394 in = (void *)(mod_base + l->fileofs);
4395 if (l->filelen % sizeof(*in))
4396 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4397 count = l->filelen / sizeof(*in);
4398 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4401 loadmodel->num = count;
4403 for (i = 0;i < count;i++, in++, out++)
4409 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4416 in = (void *)(mod_base + l->fileofs);
4417 if (l->filelen % sizeof(*in))
4418 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4419 count = l->filelen / sizeof(*in);
4420 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4423 loadmodel->num = count;
4425 for (i = 0;i < count;i++, in++, out++)
4431 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4438 in = (void *)(mod_base + l->fileofs);
4439 if (l->filelen % sizeof(*in))
4440 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4441 count = l->filelen / sizeof(*in);
4442 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4445 loadmodel->num = count;
4447 for (i = 0;i < count;i++, in++, out++)
4453 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4460 in = (void *)(mod_base + l->fileofs);
4461 if (l->filelen % sizeof(*in))
4462 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4463 count = l->filelen / sizeof(*in);
4464 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4467 loadmodel->num = count;
4469 for (i = 0;i < count;i++, in++, out++)
4475 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4482 in = (void *)(mod_base + l->fileofs);
4483 if (l->filelen % sizeof(*in))
4484 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4485 count = l->filelen / sizeof(*in);
4486 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4489 loadmodel->num = count;
4491 for (i = 0;i < count;i++, in++, out++)
4497 static void Mod_Q2BSP_LoadModels(lump_t *l)
4504 in = (void *)(mod_base + l->fileofs);
4505 if (l->filelen % sizeof(*in))
4506 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4507 count = l->filelen / sizeof(*in);
4508 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4511 loadmodel->num = count;
4513 for (i = 0;i < count;i++, in++, out++)
4519 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4522 q2dheader_t *header;
4524 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4526 mod->modeldatatypestring = "Q2BSP";
4528 mod->type = mod_brushq2;
4530 header = (q2dheader_t *)buffer;
4532 i = LittleLong(header->version);
4533 if (i != Q2BSPVERSION)
4534 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4536 mod_base = (unsigned char *)header;
4538 // swap all the lumps
4539 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4540 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4542 mod->brush.qw_md4sum = 0;
4543 mod->brush.qw_md4sum2 = 0;
4544 for (i = 0;i < Q2HEADER_LUMPS;i++)
4546 if (i == Q2LUMP_ENTITIES)
4548 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4549 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4551 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4554 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4555 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4556 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4557 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4558 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4559 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4560 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4561 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4562 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4563 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4564 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4565 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4566 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4567 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4568 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4569 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4570 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4571 // LordHavoc: must go last because this makes the submodels
4572 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4575 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4576 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4578 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4581 char key[128], value[MAX_INPUTLINE];
4583 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4584 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4585 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4588 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4589 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4590 loadmodel->brush.entities[l->filelen] = 0;
4591 data = loadmodel->brush.entities;
4592 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4593 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4594 loadmodel->brushq3.deluxemapping = false;
4595 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4599 if (!COM_ParseToken_Simple(&data, false, false, true))
4601 if (com_token[0] == '}')
4602 break; // end of worldspawn
4603 if (com_token[0] == '_')
4604 strlcpy(key, com_token + 1, sizeof(key));
4606 strlcpy(key, com_token, sizeof(key));
4607 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4608 key[strlen(key)-1] = 0;
4609 if (!COM_ParseToken_Simple(&data, false, false, true))
4611 strlcpy(value, com_token, sizeof(value));
4612 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4614 #if _MSC_VER >= 1400
4615 #define sscanf sscanf_s
4618 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4619 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4621 VectorSet(v, 64, 64, 128);
4622 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4623 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]);
4624 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4625 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4628 else if (!strcmp("deluxeMaps", key))
4630 if (!strcmp(com_token, "1"))
4632 loadmodel->brushq3.deluxemapping = true;
4633 loadmodel->brushq3.deluxemapping_modelspace = true;
4635 else if (!strcmp(com_token, "2"))
4637 loadmodel->brushq3.deluxemapping = true;
4638 loadmodel->brushq3.deluxemapping_modelspace = false;
4645 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4651 in = (q3dtexture_t *)(mod_base + l->fileofs);
4652 if (l->filelen % sizeof(*in))
4653 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4654 count = l->filelen / sizeof(*in);
4655 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4657 loadmodel->data_textures = out;
4658 loadmodel->num_textures = count;
4659 loadmodel->num_texturesperskin = loadmodel->num_textures;
4661 for (i = 0;i < count;i++)
4663 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4664 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4665 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4666 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4667 // restore the surfaceflags and supercontents
4668 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4669 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4673 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4679 in = (q3dplane_t *)(mod_base + l->fileofs);
4680 if (l->filelen % sizeof(*in))
4681 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4682 count = l->filelen / sizeof(*in);
4683 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4685 loadmodel->brush.data_planes = out;
4686 loadmodel->brush.num_planes = count;
4688 for (i = 0;i < count;i++, in++, out++)
4690 out->normal[0] = LittleFloat(in->normal[0]);
4691 out->normal[1] = LittleFloat(in->normal[1]);
4692 out->normal[2] = LittleFloat(in->normal[2]);
4693 out->dist = LittleFloat(in->dist);
4698 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4701 q3mbrushside_t *out;
4704 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4705 if (l->filelen % sizeof(*in))
4706 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4707 count = l->filelen / sizeof(*in);
4708 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4710 loadmodel->brush.data_brushsides = out;
4711 loadmodel->brush.num_brushsides = count;
4713 for (i = 0;i < count;i++, in++, out++)
4715 n = LittleLong(in->planeindex);
4716 if (n < 0 || n >= loadmodel->brush.num_planes)
4717 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4718 out->plane = loadmodel->brush.data_planes + n;
4719 n = LittleLong(in->textureindex);
4720 if (n < 0 || n >= loadmodel->num_textures)
4721 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4722 out->texture = loadmodel->data_textures + n;
4726 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4728 q3dbrushside_ig_t *in;
4729 q3mbrushside_t *out;
4732 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4733 if (l->filelen % sizeof(*in))
4734 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4735 count = l->filelen / sizeof(*in);
4736 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4738 loadmodel->brush.data_brushsides = out;
4739 loadmodel->brush.num_brushsides = count;
4741 for (i = 0;i < count;i++, in++, out++)
4743 n = LittleLong(in->planeindex);
4744 if (n < 0 || n >= loadmodel->brush.num_planes)
4745 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4746 out->plane = loadmodel->brush.data_planes + n;
4747 n = LittleLong(in->textureindex);
4748 if (n < 0 || n >= loadmodel->num_textures)
4749 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4750 out->texture = loadmodel->data_textures + n;
4754 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4758 int i, j, n, c, count, maxplanes, q3surfaceflags;
4759 colplanef_t *planes;
4761 in = (q3dbrush_t *)(mod_base + l->fileofs);
4762 if (l->filelen % sizeof(*in))
4763 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4764 count = l->filelen / sizeof(*in);
4765 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4767 loadmodel->brush.data_brushes = out;
4768 loadmodel->brush.num_brushes = count;
4773 for (i = 0;i < count;i++, in++, out++)
4775 n = LittleLong(in->firstbrushside);
4776 c = LittleLong(in->numbrushsides);
4777 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4778 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4779 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4780 out->numbrushsides = c;
4781 n = LittleLong(in->textureindex);
4782 if (n < 0 || n >= loadmodel->num_textures)
4783 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4784 out->texture = loadmodel->data_textures + n;
4786 // make a list of mplane_t structs to construct a colbrush from
4787 if (maxplanes < out->numbrushsides)
4789 maxplanes = out->numbrushsides;
4792 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4795 for (j = 0;j < out->numbrushsides;j++)
4797 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4798 planes[j].dist = out->firstbrushside[j].plane->dist;
4799 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4800 planes[j].texture = out->firstbrushside[j].texture;
4801 q3surfaceflags |= planes[j].q3surfaceflags;
4803 // make the colbrush from the planes
4804 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4806 // this whole loop can take a while (e.g. on redstarrepublic4)
4807 CL_KeepaliveMessage(false);
4813 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4819 in = (q3deffect_t *)(mod_base + l->fileofs);
4820 if (l->filelen % sizeof(*in))
4821 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4822 count = l->filelen / sizeof(*in);
4823 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4825 loadmodel->brushq3.data_effects = out;
4826 loadmodel->brushq3.num_effects = count;
4828 for (i = 0;i < count;i++, in++, out++)
4830 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4831 n = LittleLong(in->brushindex);
4832 if (n >= loadmodel->brush.num_brushes)
4834 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4837 out->brushindex = n;
4838 out->unknown = LittleLong(in->unknown);
4842 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4847 in = (q3dvertex_t *)(mod_base + l->fileofs);
4848 if (l->filelen % sizeof(*in))
4849 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4850 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4851 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4852 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4853 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4854 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4855 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4857 for (i = 0;i < count;i++, in++)
4859 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4860 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4861 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4862 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4863 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4864 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4865 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4866 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4867 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4868 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4869 // svector/tvector are calculated later in face loading
4870 if(mod_q3bsp_sRGBlightmaps.integer)
4872 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
4873 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
4874 // working like this may be odd, but matches q3map2 -gamma 2.2
4875 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4877 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4878 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4879 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4880 // we fix the brightness consistently via lightmapscale
4884 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
4885 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
4886 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
4891 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4893 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4894 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4895 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4899 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4900 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4901 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4904 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4905 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4906 loadmodel->lit = true;
4910 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4916 in = (int *)(mod_base + l->fileofs);
4917 if (l->filelen % sizeof(int[3]))
4918 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4919 count = l->filelen / sizeof(*in);
4921 if(!loadmodel->brushq3.num_vertices)
4924 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4925 loadmodel->brushq3.num_triangles = 0;
4929 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4930 loadmodel->brushq3.num_triangles = count / 3;
4931 loadmodel->brushq3.data_element3i = out;
4933 for (i = 0;i < count;i++, in++, out++)
4935 *out = LittleLong(*in);
4936 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4938 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4944 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4946 q3dlightmap_t *input_pointer;
4964 int mergedrowsxcolumns;
4969 unsigned char *mergedpixels;
4970 unsigned char *mergeddeluxepixels;
4971 unsigned char *mergebuf;
4972 char mapname[MAX_QPATH];
4974 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4977 // defaults for q3bsp
4984 loadmodel->brushq3.lightmapsize = 128;
4986 if (cls.state == ca_dedicated)
4989 if(mod_q3bsp_nolightmaps.integer)
4995 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4996 if (developer_loading.integer)
4997 Con_Printf("Using internal lightmaps\n");
4998 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4999 if (l->filelen % sizeof(*input_pointer))
5000 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5001 count = l->filelen / sizeof(*input_pointer);
5002 for(i = 0; i < count; ++i)
5003 inpixels[i] = input_pointer[i].rgb;
5007 // no internal lightmaps
5008 // try external lightmaps
5009 if (developer_loading.integer)
5010 Con_Printf("Using external lightmaps\n");
5011 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5012 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5016 // using EXTERNAL lightmaps instead
5017 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5019 Mem_Free(inpixels[0]);
5020 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5030 for(count = 1; ; ++count)
5032 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5033 if(!inpixels[count])
5034 break; // we got all of them
5035 if(image_width != size || image_height != size)
5037 Mem_Free(inpixels[count]);
5038 inpixels[count] = NULL;
5039 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);
5045 loadmodel->brushq3.lightmapsize = size;
5046 loadmodel->brushq3.num_originallightmaps = count;
5048 // now check the surfaces to see if any of them index an odd numbered
5049 // lightmap, if so this is not a deluxemapped bsp file
5051 // also check what lightmaps are actually used, because q3map2 sometimes
5052 // (always?) makes an unused one at the end, which
5053 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5054 // reason when only one lightmap is used, which can throw off the
5055 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5056 // to see if the second lightmap is blank, if so it is not deluxemapped.
5057 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5058 // in Mod_Q3BSP_LoadEntities was failed
5059 if (!loadmodel->brushq3.deluxemapping)
5061 loadmodel->brushq3.deluxemapping = !(count & 1);
5062 loadmodel->brushq3.deluxemapping_modelspace = true;
5064 if (loadmodel->brushq3.deluxemapping)
5066 int facecount = faceslump->filelen / sizeof(q3dface_t);
5067 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5068 for (i = 0;i < facecount;i++)
5070 j = LittleLong(faces[i].lightmapindex);
5073 endlightmap = max(endlightmap, j + 1);
5074 if ((j & 1) || j + 1 >= count)
5076 loadmodel->brushq3.deluxemapping = false;
5083 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5084 // reason when only one lightmap is used, which can throw off the
5085 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5086 // to see if the second lightmap is blank, if so it is not deluxemapped.
5088 // further research has shown q3map2 sometimes creates a deluxemap and two
5089 // blank lightmaps, which must be handled properly as well
5090 if (endlightmap == 1 && count > 1)
5093 for (i = 0;i < size*size;i++)
5095 if (c[bytesperpixel*i + rgbmap[0]])
5097 if (c[bytesperpixel*i + rgbmap[1]])
5099 if (c[bytesperpixel*i + rgbmap[2]])
5104 // all pixels in the unused lightmap were black...
5105 loadmodel->brushq3.deluxemapping = false;
5110 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5112 // figure out what the most reasonable merge power is within limits
5114 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5115 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5117 // figure out how big the merged texture has to be
5118 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5119 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5120 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5122 mergedwidth = mergegoal;
5123 mergedheight = mergegoal;
5124 // choose non-square size (2x1 aspect) if only half the space is used;
5125 // this really only happens when the entire set fits in one texture, if
5126 // there are multiple textures, we don't worry about shrinking the last
5127 // one to fit, because the driver prefers the same texture size on
5128 // consecutive draw calls...
5129 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5132 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5133 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5134 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5135 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5136 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5137 loadmodel->brushq3.num_lightmapmergedheightpower++;
5138 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5140 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5141 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5142 powerxy = powerx+powery;
5143 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5145 mergedcolumns = 1 << powerx;
5146 mergedrows = 1 << powery;
5147 mergedrowsxcolumns = 1 << powerxy;
5149 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5150 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5151 if (loadmodel->brushq3.deluxemapping)
5152 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5154 // allocate a texture pool if we need it
5155 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5156 loadmodel->texturepool = R_AllocTexturePool();
5158 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5159 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5160 for (i = 0;i < count;i++)
5162 // figure out which merged lightmap texture this fits into
5163 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5164 lightmapindex = i >> powerdxy;
5166 // choose the destination address
5167 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5168 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5169 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5170 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);
5172 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5173 for (j = 0;j < size;j++)
5174 for (k = 0;k < size;k++)
5176 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5177 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5178 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5179 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5182 // upload texture if this was the last tile being written to the texture
5183 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5185 if (loadmodel->brushq3.deluxemapping && (i & 1))
5186 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);
5189 if(mod_q3bsp_sRGBlightmaps.integer)
5192 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5194 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5195 // we fix the brightness consistently via lightmapscale
5198 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5199 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);
5203 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5204 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5205 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);
5211 if (mergeddeluxepixels)
5212 Mem_Free(mergeddeluxepixels);
5213 Mem_Free(mergedpixels);
5216 for(i = 0; i < count; ++i)
5217 Mem_Free(inpixels[i]);
5221 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5226 *collisionstride = stride;
5229 cnt = (num_triangles + stride - 1) / stride;
5230 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5231 for(j = 0; j < cnt; ++j)
5233 mins = &((*collisionbbox6f)[6 * j + 0]);
5234 maxs = &((*collisionbbox6f)[6 * j + 3]);
5235 for(k = 0; k < stride; ++k)
5237 tri = j * stride + k;
5238 if(tri >= num_triangles)
5240 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5241 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5242 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5243 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5244 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5245 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5246 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5247 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5248 if(vert[0] < mins[0]) mins[0] = vert[0];
5249 if(vert[1] < mins[1]) mins[1] = vert[1];
5250 if(vert[2] < mins[2]) mins[2] = vert[2];
5251 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5252 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5253 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5254 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5255 if(vert[0] < mins[0]) mins[0] = vert[0];
5256 if(vert[1] < mins[1]) mins[1] = vert[1];
5257 if(vert[2] < mins[2]) mins[2] = vert[2];
5258 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5259 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5260 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5265 *collisionbbox6f = NULL;
5268 typedef struct patchtess_s
5272 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5275 float *originalvertex3f;
5278 #define PATCHTESS_SAME_LODGROUP(a,b) \
5280 (a).lodgroup[0] == (b).lodgroup[0] && \
5281 (a).lodgroup[1] == (b).lodgroup[1] && \
5282 (a).lodgroup[2] == (b).lodgroup[2] && \
5283 (a).lodgroup[3] == (b).lodgroup[3] && \
5284 (a).lodgroup[4] == (b).lodgroup[4] && \
5285 (a).lodgroup[5] == (b).lodgroup[5] \
5288 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5290 q3dface_t *in, *oldin;
5291 msurface_t *out, *oldout;
5292 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;
5293 float lightmaptcbase[2], lightmaptcscale[2];
5294 //int *originalelement3i;
5295 //int *originalneighbor3i;
5296 float *originalvertex3f;
5297 //float *originalsvector3f;
5298 //float *originaltvector3f;
5299 float *originalnormal3f;
5300 float *originalcolor4f;
5301 float *originaltexcoordtexture2f;
5302 float *originaltexcoordlightmap2f;
5303 float *surfacecollisionvertex3f;
5304 int *surfacecollisionelement3i;
5306 patchtess_t *patchtess = NULL;
5307 int patchtesscount = 0;
5310 in = (q3dface_t *)(mod_base + l->fileofs);
5311 if (l->filelen % sizeof(*in))
5312 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5313 count = l->filelen / sizeof(*in);
5314 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5316 loadmodel->data_surfaces = out;
5317 loadmodel->num_surfaces = count;
5320 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5328 for (;i < count;i++, in++, out++)
5330 // check face type first
5331 type = LittleLong(in->type);
5332 if (type != Q3FACETYPE_FLAT
5333 && type != Q3FACETYPE_PATCH
5334 && type != Q3FACETYPE_MESH
5335 && type != Q3FACETYPE_FLARE)
5337 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5341 n = LittleLong(in->textureindex);
5342 if (n < 0 || n >= loadmodel->num_textures)
5344 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5347 out->texture = loadmodel->data_textures + n;
5348 n = LittleLong(in->effectindex);
5349 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5351 if (developer_extra.integer)
5352 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5358 out->effect = loadmodel->brushq3.data_effects + n;
5360 if (cls.state != ca_dedicated)
5362 out->lightmaptexture = NULL;
5363 out->deluxemaptexture = r_texture_blanknormalmap;
5364 n = LittleLong(in->lightmapindex);
5367 else if (n >= loadmodel->brushq3.num_originallightmaps)
5369 if(loadmodel->brushq3.num_originallightmaps != 0)
5370 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5375 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5376 if (loadmodel->brushq3.deluxemapping)
5377 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5378 loadmodel->lit = true;
5382 firstvertex = LittleLong(in->firstvertex);
5383 numvertices = LittleLong(in->numvertices);
5384 firstelement = LittleLong(in->firstelement);
5385 numtriangles = LittleLong(in->numelements) / 3;
5386 if (numtriangles * 3 != LittleLong(in->numelements))
5388 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));
5391 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5393 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);
5396 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5398 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);
5403 case Q3FACETYPE_FLAT:
5404 case Q3FACETYPE_MESH:
5405 // no processing necessary
5407 case Q3FACETYPE_PATCH:
5408 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5409 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5410 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))
5412 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5415 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5417 // convert patch to Q3FACETYPE_MESH
5418 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5419 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5420 // bound to user settings
5421 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5422 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5423 // bound to sanity settings
5424 xtess = bound(0, xtess, 1024);
5425 ytess = bound(0, ytess, 1024);
5427 // lower quality collision patches! Same procedure as before, but different cvars
5428 // convert patch to Q3FACETYPE_MESH
5429 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5430 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5431 // bound to user settings
5432 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5433 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5434 // bound to sanity settings
5435 cxtess = bound(0, cxtess, 1024);
5436 cytess = bound(0, cytess, 1024);
5438 // store it for the LOD grouping step
5439 patchtess[patchtesscount].info.xsize = patchsize[0];
5440 patchtess[patchtesscount].info.ysize = patchsize[1];
5441 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5442 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5443 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5444 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5446 patchtess[patchtesscount].surface_id = i;
5447 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5448 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5449 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5450 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5451 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5452 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5453 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5456 case Q3FACETYPE_FLARE:
5457 if (developer_extra.integer)
5458 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5462 out->num_vertices = numvertices;
5463 out->num_triangles = numtriangles;
5464 meshvertices += out->num_vertices;
5465 meshtriangles += out->num_triangles;
5468 // Fix patches tesselations so that they make no seams
5472 for(i = 0; i < patchtesscount; ++i)
5474 for(j = i+1; j < patchtesscount; ++j)
5476 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5479 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5486 // Calculate resulting number of triangles
5487 collisionvertices = 0;
5488 collisiontriangles = 0;
5489 for(i = 0; i < patchtesscount; ++i)
5491 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5492 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5493 numvertices = finalwidth * finalheight;
5494 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5496 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5497 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5498 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5499 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5501 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5502 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5503 numvertices = finalwidth * finalheight;
5504 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5506 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5507 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5508 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5509 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5515 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5516 if (collisiontriangles)
5518 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5519 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5523 collisionvertices = 0;
5524 collisiontriangles = 0;
5525 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5527 if (out->num_vertices < 3 || out->num_triangles < 1)
5530 type = LittleLong(in->type);
5531 firstvertex = LittleLong(in->firstvertex);
5532 firstelement = LittleLong(in->firstelement);
5533 out->num_firstvertex = meshvertices;
5534 out->num_firsttriangle = meshtriangles;
5535 out->num_firstcollisiontriangle = collisiontriangles;
5538 case Q3FACETYPE_FLAT:
5539 case Q3FACETYPE_MESH:
5540 // no processing necessary, except for lightmap merging
5541 for (j = 0;j < out->num_vertices;j++)
5543 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5544 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5545 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5546 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5547 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5548 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5549 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5550 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5551 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5552 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5553 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5554 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5555 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5556 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5558 for (j = 0;j < out->num_triangles*3;j++)
5559 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5561 case Q3FACETYPE_PATCH:
5562 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5563 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5564 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5565 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5566 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5567 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5568 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5570 xtess = ytess = cxtess = cytess = -1;
5571 for(j = 0; j < patchtesscount; ++j)
5572 if(patchtess[j].surface_id == i)
5574 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5575 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5576 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5577 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5582 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5583 xtess = ytess = cxtess = cytess = 0;
5586 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5587 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5588 finalvertices = finalwidth * finalheight;
5589 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5590 type = Q3FACETYPE_MESH;
5591 // generate geometry
5592 // (note: normals are skipped because they get recalculated)
5593 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5594 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5595 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5596 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5597 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5598 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5600 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);
5602 if (developer_extra.integer)
5604 if (out->num_triangles < finaltriangles)
5605 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);
5607 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);
5609 // q3map does not put in collision brushes for curves... ugh
5610 // build the lower quality collision geometry
5611 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5612 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5613 finalvertices = finalwidth * finalheight;
5614 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5616 // legacy collision geometry implementation
5617 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5618 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5619 out->num_collisionvertices = finalvertices;
5620 out->num_collisiontriangles = finaltriangles;
5621 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5622 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5624 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5625 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5627 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5629 // now optimize the collision mesh by finding triangle bboxes...
5630 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5631 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);
5633 // store collision geometry for BIH collision tree
5634 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5635 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5636 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5637 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5638 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5640 // remove this once the legacy code is removed
5642 int nc = out->num_collisiontriangles;
5644 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5646 if(nc != out->num_collisiontriangles)
5648 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5653 if (developer_extra.integer)
5654 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);
5656 collisionvertices += finalvertices;
5657 collisiontriangles += out->num_collisiontriangles;
5662 meshvertices += out->num_vertices;
5663 meshtriangles += out->num_triangles;
5664 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5665 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)
5667 if (invalidelements)
5669 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);
5670 for (j = 0;j < out->num_triangles * 3;j++)
5672 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5673 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)
5674 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5678 // calculate a bounding box
5679 VectorClear(out->mins);
5680 VectorClear(out->maxs);
5681 if (out->num_vertices)
5683 if (cls.state != ca_dedicated && out->lightmaptexture)
5685 // figure out which part of the merged lightmap this fits into
5686 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5687 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5688 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5689 lightmapindex &= mergewidth * mergeheight - 1;
5690 lightmaptcscale[0] = 1.0f / mergewidth;
5691 lightmaptcscale[1] = 1.0f / mergeheight;
5692 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5693 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5694 // modify the lightmap texcoords to match this region of the merged lightmap
5695 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5697 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5698 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5701 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5702 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5703 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5705 out->mins[0] = min(out->mins[0], v[0]);
5706 out->maxs[0] = max(out->maxs[0], v[0]);
5707 out->mins[1] = min(out->mins[1], v[1]);
5708 out->maxs[1] = max(out->maxs[1], v[1]);
5709 out->mins[2] = min(out->mins[2], v[2]);
5710 out->maxs[2] = max(out->maxs[2], v[2]);
5712 out->mins[0] -= 1.0f;
5713 out->mins[1] -= 1.0f;
5714 out->mins[2] -= 1.0f;
5715 out->maxs[0] += 1.0f;
5716 out->maxs[1] += 1.0f;
5717 out->maxs[2] += 1.0f;
5719 // set lightmap styles for consistency with q1bsp
5720 //out->lightmapinfo->styles[0] = 0;
5721 //out->lightmapinfo->styles[1] = 255;
5722 //out->lightmapinfo->styles[2] = 255;
5723 //out->lightmapinfo->styles[3] = 255;
5728 for (;i < count;i++, out++)
5730 if(out->num_vertices && out->num_triangles)
5732 if(out->num_vertices == 0)
5734 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5735 if(out->num_triangles == 0)
5736 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5738 else if(out->num_triangles == 0)
5739 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)",
5740 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5741 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5742 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5745 // for per pixel lighting
5746 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);
5748 // generate ushort elements array if possible
5749 if (loadmodel->surfmesh.data_element3s)
5750 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5751 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5753 // free the no longer needed vertex data
5754 loadmodel->brushq3.num_vertices = 0;
5755 if (loadmodel->brushq3.data_vertex3f)
5756 Mem_Free(loadmodel->brushq3.data_vertex3f);
5757 loadmodel->brushq3.data_vertex3f = NULL;
5758 loadmodel->brushq3.data_normal3f = NULL;
5759 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5760 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5761 loadmodel->brushq3.data_color4f = NULL;
5762 // free the no longer needed triangle data
5763 loadmodel->brushq3.num_triangles = 0;
5764 if (loadmodel->brushq3.data_element3i)
5765 Mem_Free(loadmodel->brushq3.data_element3i);
5766 loadmodel->brushq3.data_element3i = NULL;
5769 Mem_Free(patchtess);
5772 static void Mod_Q3BSP_LoadModels(lump_t *l)
5776 int i, j, n, c, count;
5778 in = (q3dmodel_t *)(mod_base + l->fileofs);
5779 if (l->filelen % sizeof(*in))
5780 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5781 count = l->filelen / sizeof(*in);
5782 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5784 loadmodel->brushq3.data_models = out;
5785 loadmodel->brushq3.num_models = count;
5787 for (i = 0;i < count;i++, in++, out++)
5789 for (j = 0;j < 3;j++)
5791 out->mins[j] = LittleFloat(in->mins[j]);
5792 out->maxs[j] = LittleFloat(in->maxs[j]);
5794 n = LittleLong(in->firstface);
5795 c = LittleLong(in->numfaces);
5796 if (n < 0 || n + c > loadmodel->num_surfaces)
5797 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5800 n = LittleLong(in->firstbrush);
5801 c = LittleLong(in->numbrushes);
5802 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5803 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5804 out->firstbrush = n;
5805 out->numbrushes = c;
5809 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5815 in = (int *)(mod_base + l->fileofs);
5816 if (l->filelen % sizeof(*in))
5817 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5818 count = l->filelen / sizeof(*in);
5819 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5821 loadmodel->brush.data_leafbrushes = out;
5822 loadmodel->brush.num_leafbrushes = count;
5824 for (i = 0;i < count;i++, in++, out++)
5826 n = LittleLong(*in);
5827 if (n < 0 || n >= loadmodel->brush.num_brushes)
5828 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5833 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5839 in = (int *)(mod_base + l->fileofs);
5840 if (l->filelen % sizeof(*in))
5841 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5842 count = l->filelen / sizeof(*in);
5843 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5845 loadmodel->brush.data_leafsurfaces = out;
5846 loadmodel->brush.num_leafsurfaces = count;
5848 for (i = 0;i < count;i++, in++, out++)
5850 n = LittleLong(*in);
5851 if (n < 0 || n >= loadmodel->num_surfaces)
5852 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5857 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5861 int i, j, n, c, count;
5863 in = (q3dleaf_t *)(mod_base + l->fileofs);
5864 if (l->filelen % sizeof(*in))
5865 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5866 count = l->filelen / sizeof(*in);
5867 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5869 loadmodel->brush.data_leafs = out;
5870 loadmodel->brush.num_leafs = count;
5872 for (i = 0;i < count;i++, in++, out++)
5876 out->clusterindex = LittleLong(in->clusterindex);
5877 out->areaindex = LittleLong(in->areaindex);
5878 for (j = 0;j < 3;j++)
5880 // yes the mins/maxs are ints
5881 out->mins[j] = LittleLong(in->mins[j]) - 1;
5882 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5884 n = LittleLong(in->firstleafface);
5885 c = LittleLong(in->numleaffaces);
5886 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5887 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5888 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5889 out->numleafsurfaces = c;
5890 n = LittleLong(in->firstleafbrush);
5891 c = LittleLong(in->numleafbrushes);
5892 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5893 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5894 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5895 out->numleafbrushes = c;
5899 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5905 in = (q3dnode_t *)(mod_base + l->fileofs);
5906 if (l->filelen % sizeof(*in))
5907 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5908 count = l->filelen / sizeof(*in);
5910 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5911 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5913 loadmodel->brush.data_nodes = out;
5914 loadmodel->brush.num_nodes = count;
5916 for (i = 0;i < count;i++, in++, out++)
5919 n = LittleLong(in->planeindex);
5920 if (n < 0 || n >= loadmodel->brush.num_planes)
5921 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5922 out->plane = loadmodel->brush.data_planes + n;
5923 for (j = 0;j < 2;j++)
5925 n = LittleLong(in->childrenindex[j]);
5928 if (n >= loadmodel->brush.num_nodes)
5929 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5930 out->children[j] = loadmodel->brush.data_nodes + n;
5935 if (n >= loadmodel->brush.num_leafs)
5936 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5937 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5940 for (j = 0;j < 3;j++)
5942 // yes the mins/maxs are ints
5943 out->mins[j] = LittleLong(in->mins[j]) - 1;
5944 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5948 // set the parent pointers
5949 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5952 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5955 q3dlightgrid_t *out;
5959 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5960 if (l->filelen % sizeof(*in))
5961 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5962 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5963 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5964 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5965 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5966 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5967 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5968 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5969 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5970 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5971 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5972 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5973 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5974 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5975 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]);
5976 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]);
5978 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5981 if (l->filelen < count * (int)sizeof(*in))
5983 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]);
5984 return; // ignore the grid if we cannot understand it
5986 if (l->filelen != count * (int)sizeof(*in))
5987 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5988 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5989 loadmodel->brushq3.data_lightgrid = out;
5990 loadmodel->brushq3.num_lightgrid = count;
5991 // no swapping or validation necessary
5992 memcpy(out, in, count * (int)sizeof(*out));
5994 if(mod_q3bsp_sRGBlightmaps.integer)
5996 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5998 // we fix the brightness consistently via lightmapscale
6002 for(i = 0; i < count; ++i)
6004 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6005 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6006 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6007 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6008 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6009 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6015 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6017 for(i = 0; i < count; ++i)
6019 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6020 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6021 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6022 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6023 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6024 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6035 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6040 if (l->filelen == 0)
6043 // unvised maps often have cluster indices even without pvs, so check
6044 // leafs to find real number of clusters
6045 loadmodel->brush.num_pvsclusters = 1;
6046 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6047 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6050 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6051 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6052 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6053 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6057 in = (q3dpvs_t *)(mod_base + l->fileofs);
6059 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6061 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6062 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6063 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6064 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6065 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6066 if (l->filelen < totalchains + (int)sizeof(*in))
6067 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);
6069 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6070 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6073 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6075 int i, j, k, index[3];
6076 float transformed[3], blend1, blend2, blend, stylescale = 1;
6077 q3dlightgrid_t *a, *s;
6079 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6080 switch(vid.renderpath)
6082 case RENDERPATH_GL20:
6083 case RENDERPATH_D3D9:
6084 case RENDERPATH_D3D10:
6085 case RENDERPATH_D3D11:
6086 case RENDERPATH_SOFT:
6087 case RENDERPATH_GLES2:
6088 // LordHavoc: FIXME: is this true?
6089 stylescale = 1; // added while render
6091 case RENDERPATH_GL11:
6092 case RENDERPATH_GL13:
6093 case RENDERPATH_GLES1:
6094 stylescale = r_refdef.scene.rtlightstylevalue[0];
6098 if (!model->brushq3.num_lightgrid)
6100 ambientcolor[0] = stylescale;
6101 ambientcolor[1] = stylescale;
6102 ambientcolor[2] = stylescale;
6106 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6107 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6108 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6109 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6110 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6111 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6112 index[0] = (int)floor(transformed[0]);
6113 index[1] = (int)floor(transformed[1]);
6114 index[2] = (int)floor(transformed[2]);
6115 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6117 // now lerp the values
6118 VectorClear(diffusenormal);
6119 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6120 for (k = 0;k < 2;k++)
6122 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6123 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6125 for (j = 0;j < 2;j++)
6127 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6128 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6130 for (i = 0;i < 2;i++)
6132 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6133 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6135 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6136 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6137 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6138 // this uses the mod_md3_sin table because the values are
6139 // already in the 0-255 range, the 64+ bias fetches a cosine
6140 // instead of a sine value
6141 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6142 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6143 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6144 //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)));
6149 // normalize the light direction before turning
6150 VectorNormalize(diffusenormal);
6151 //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]);
6154 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6157 double midf, mid[3];
6163 // find the point distances
6164 mplane_t *plane = node->plane;
6165 if (plane->type < 3)
6167 t1 = p1[plane->type] - plane->dist;
6168 t2 = p2[plane->type] - plane->dist;
6172 t1 = DotProduct (plane->normal, p1) - plane->dist;
6173 t2 = DotProduct (plane->normal, p2) - plane->dist;
6180 node = node->children[1];
6189 node = node->children[0];
6195 midf = t1 / (t1 - t2);
6196 VectorLerp(p1, midf, p2, mid);
6198 // recurse both sides, front side first
6199 // return 2 if empty is followed by solid (hit something)
6200 // do not return 2 if both are solid or both empty,
6201 // or if start is solid and end is empty
6202 // as these degenerate cases usually indicate the eye is in solid and
6203 // should see the target point anyway
6204 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6207 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6212 return ((mleaf_t *)node)->clusterindex < 0;
6215 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6217 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6220 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6221 return trace.fraction == 1;
6225 double tracestart[3], traceend[3];
6226 VectorCopy(start, tracestart);
6227 VectorCopy(end, traceend);
6228 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6232 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)
6235 const bih_leaf_t *leaf;
6236 const bih_node_t *node;
6237 const colbrushf_t *brush;
6240 int nodestackpos = 0;
6241 int nodestack[1024];
6243 memset(trace, 0, sizeof(*trace));
6244 trace->fraction = 1;
6245 trace->realfraction = 1;
6246 trace->hitsupercontentsmask = hitsupercontentsmask;
6248 bih = &model->collision_bih;
6252 nodenum = bih->rootnode;
6253 nodestack[nodestackpos++] = nodenum;
6254 while (nodestackpos)
6256 nodenum = nodestack[--nodestackpos];
6257 node = bih->nodes + nodenum;
6259 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6262 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6264 axis = node->type - BIH_SPLITX;
6265 if (start[axis] >= node->frontmin)
6266 nodestack[nodestackpos++] = node->front;
6267 if (start[axis] <= node->backmax)
6268 nodestack[nodestackpos++] = node->back;
6270 else if (node->type == BIH_UNORDERED)
6272 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6274 leaf = bih->leafs + node->children[axis];
6276 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6282 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6283 Collision_TracePointBrushFloat(trace, start, brush);
6285 case BIH_COLLISIONTRIANGLE:
6286 // collision triangle - skipped because they have no volume
6288 case BIH_RENDERTRIANGLE:
6289 // render triangle - skipped because they have no volume
6297 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, const bih_t *bih)
6299 const bih_leaf_t *leaf;
6300 const bih_node_t *node;
6301 const colbrushf_t *brush;
6303 const texture_t *texture;
6304 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6305 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6306 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6311 if (VectorCompare(start, end))
6313 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6317 nodenum = bih->rootnode;
6319 memset(trace, 0, sizeof(*trace));
6320 trace->fraction = 1;
6321 trace->realfraction = 1;
6322 trace->hitsupercontentsmask = hitsupercontentsmask;
6325 nodestackline[nodestackpos][0] = start[0];
6326 nodestackline[nodestackpos][1] = start[1];
6327 nodestackline[nodestackpos][2] = start[2];
6328 nodestackline[nodestackpos][3] = end[0];
6329 nodestackline[nodestackpos][4] = end[1];
6330 nodestackline[nodestackpos][5] = end[2];
6331 nodestack[nodestackpos++] = nodenum;
6332 while (nodestackpos)
6334 nodenum = nodestack[--nodestackpos];
6335 node = bih->nodes + nodenum;
6336 VectorCopy(nodestackline[nodestackpos], nodestart);
6337 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6338 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6339 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6341 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6343 // recurse children of the split
6344 axis = node->type - BIH_SPLITX;
6345 d1 = node->backmax - nodestart[axis];
6346 d2 = node->backmax - nodeend[axis];
6347 d3 = nodestart[axis] - node->frontmin;
6348 d4 = nodeend[axis] - node->frontmin;
6349 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6351 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;
6352 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;
6353 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;
6354 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6355 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;
6356 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;
6357 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;
6358 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6359 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;
6360 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;
6361 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;
6362 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6363 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6364 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6365 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6366 case 15: /* <<<< */ break;
6369 else if (node->type == BIH_UNORDERED)
6371 // calculate sweep bounds for this node
6372 // copy node bounds into local variables
6373 VectorCopy(node->mins, nodebigmins);
6374 VectorCopy(node->maxs, nodebigmaxs);
6375 // clip line to this node bounds
6376 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); }
6377 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); }
6378 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); }
6379 // some of the line intersected the enlarged node box
6380 // calculate sweep bounds for this node
6381 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6382 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6384 leaf = bih->leafs + node->children[axis];
6385 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6390 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6391 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6393 case BIH_COLLISIONTRIANGLE:
6394 if (!mod_q3bsp_curves_collisions.integer)
6396 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6397 texture = model->data_textures + leaf->textureindex;
6398 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);
6400 case BIH_RENDERTRIANGLE:
6401 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6402 texture = model->data_textures + leaf->textureindex;
6403 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);
6411 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)
6413 if (VectorCompare(start, end))
6415 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6418 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6421 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)
6424 const bih_leaf_t *leaf;
6425 const bih_node_t *node;
6426 const colbrushf_t *brush;
6428 const texture_t *texture;
6429 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6430 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6431 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6432 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6434 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6436 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6437 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6439 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6443 bih = &model->collision_bih;
6446 nodenum = bih->rootnode;
6448 // box trace, performed as brush trace
6449 memset(trace, 0, sizeof(*trace));
6450 trace->fraction = 1;
6451 trace->realfraction = 1;
6452 trace->hitsupercontentsmask = hitsupercontentsmask;
6454 // calculate tracebox-like parameters for efficient culling
6455 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6456 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6457 VectorSubtract(thisbrush_start->mins, start, startmins);
6458 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6459 VectorSubtract(thisbrush_end->mins, end, endmins);
6460 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6461 mins[0] = min(startmins[0], endmins[0]);
6462 mins[1] = min(startmins[1], endmins[1]);
6463 mins[2] = min(startmins[2], endmins[2]);
6464 maxs[0] = max(startmaxs[0], endmaxs[0]);
6465 maxs[1] = max(startmaxs[1], endmaxs[1]);
6466 maxs[2] = max(startmaxs[2], endmaxs[2]);
6469 nodestackline[nodestackpos][0] = start[0];
6470 nodestackline[nodestackpos][1] = start[1];
6471 nodestackline[nodestackpos][2] = start[2];
6472 nodestackline[nodestackpos][3] = end[0];
6473 nodestackline[nodestackpos][4] = end[1];
6474 nodestackline[nodestackpos][5] = end[2];
6475 nodestack[nodestackpos++] = nodenum;
6476 while (nodestackpos)
6478 nodenum = nodestack[--nodestackpos];
6479 node = bih->nodes + nodenum;
6480 VectorCopy(nodestackline[nodestackpos], nodestart);
6481 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6482 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6483 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6485 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6487 // recurse children of the split
6488 axis = node->type - BIH_SPLITX;
6489 d1 = node->backmax - nodestart[axis] - mins[axis];
6490 d2 = node->backmax - nodeend[axis] - mins[axis];
6491 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6492 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6493 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6495 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;
6496 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;
6497 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;
6498 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6499 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;
6500 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;
6501 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;
6502 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6503 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;
6504 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;
6505 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;
6506 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6507 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6508 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6509 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6510 case 15: /* <<<< */ break;
6513 else if (node->type == BIH_UNORDERED)
6515 // calculate sweep bounds for this node
6516 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6517 VectorSubtract(node->mins, maxs, nodebigmins);
6518 VectorSubtract(node->maxs, mins, nodebigmaxs);
6519 // clip line to this node bounds
6520 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); }
6521 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); }
6522 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); }
6523 // some of the line intersected the enlarged node box
6524 // calculate sweep bounds for this node
6525 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6526 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6528 leaf = bih->leafs + node->children[axis];
6529 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6534 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6535 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6537 case BIH_COLLISIONTRIANGLE:
6538 if (!mod_q3bsp_curves_collisions.integer)
6540 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6541 texture = model->data_textures + leaf->textureindex;
6542 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);
6544 case BIH_RENDERTRIANGLE:
6545 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6546 texture = model->data_textures + leaf->textureindex;
6547 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);
6555 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)
6557 colboxbrushf_t thisbrush_start, thisbrush_end;
6558 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6560 // box trace, performed as brush trace
6561 VectorAdd(start, boxmins, boxstartmins);
6562 VectorAdd(start, boxmaxs, boxstartmaxs);
6563 VectorAdd(end, boxmins, boxendmins);
6564 VectorAdd(end, boxmaxs, boxendmaxs);
6565 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6566 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6567 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6571 static int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6574 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6575 return trace.startsupercontents;
6578 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)
6581 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6583 int hitsupercontents;
6584 VectorSet(end, start[0], start[1], model->normalmins[2]);
6586 memset(trace, 0, sizeof(*trace));
6587 trace->fraction = 1;
6588 trace->realfraction = 1;
6589 trace->hitsupercontentsmask = hitsupercontentsmask;
6591 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6592 hitsupercontents = trace->hitsupercontents;
6593 memset(trace, 0, sizeof(*trace));
6594 trace->fraction = 1;
6595 trace->realfraction = 1;
6596 trace->hitsupercontentsmask = hitsupercontentsmask;
6597 trace->startsupercontents = hitsupercontents;
6601 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6604 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6607 VectorSet(end, start[0], start[1], model->normalmins[2]);
6608 memset(&trace, 0, sizeof(trace));
6610 trace.realfraction = 1;
6611 trace.hitsupercontentsmask = 0;
6612 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6613 return trace.hitsupercontents;
6619 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6624 // find which leaf the point is in
6626 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6627 // point trace the brushes
6628 leaf = (mleaf_t *)node;
6629 for (i = 0;i < leaf->numleafbrushes;i++)
6631 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6632 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6634 brush->markframe = markframe;
6635 Collision_TracePointBrushFloat(trace, point, brush);
6638 // can't do point traces on curves (they have no thickness)
6641 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)
6643 int i, startside, endside;
6644 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6646 msurface_t *surface;
6649 // walk the tree until we hit a leaf, recursing for any split cases
6653 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6655 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6656 node = node->children[1];
6658 // abort if this part of the bsp tree can not be hit by this trace
6659 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6661 plane = node->plane;
6662 // axial planes are much more common than non-axial, so an optimized
6663 // axial case pays off here
6664 if (plane->type < 3)
6666 dist1 = start[plane->type] - plane->dist;
6667 dist2 = end[plane->type] - plane->dist;
6671 dist1 = DotProduct(start, plane->normal) - plane->dist;
6672 dist2 = DotProduct(end, plane->normal) - plane->dist;
6674 startside = dist1 < 0;
6675 endside = dist2 < 0;
6676 if (startside == endside)
6678 // most of the time the line fragment is on one side of the plane
6679 node = node->children[startside];
6683 // line crosses node plane, split the line
6684 dist1 = PlaneDiff(linestart, plane);
6685 dist2 = PlaneDiff(lineend, plane);
6686 midfrac = dist1 / (dist1 - dist2);
6687 VectorLerp(linestart, midfrac, lineend, mid);
6688 // take the near side first
6689 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6690 // if we found an impact on the front side, don't waste time
6691 // exploring the far side
6692 if (midfrac <= trace->realfraction)
6693 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6698 // abort if this part of the bsp tree can not be hit by this trace
6699 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6702 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6703 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6704 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6705 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6706 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6707 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6708 // line trace the brushes
6709 leaf = (mleaf_t *)node;
6711 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6714 for (i = 0;i < leaf->numleafbrushes;i++)
6716 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6717 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6719 brush->markframe = markframe;
6720 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6723 // can't do point traces on curves (they have no thickness)
6724 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6726 // line trace the curves
6727 for (i = 0;i < leaf->numleafsurfaces;i++)
6729 surface = model->data_surfaces + leaf->firstleafsurface[i];
6730 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6732 surface->deprecatedq3collisionmarkframe = markframe;
6733 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);
6739 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)
6745 msurface_t *surface;
6747 float nodesegmentmins[3], nodesegmentmaxs[3];
6748 // walk the tree until we hit a leaf, recursing for any split cases
6752 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6754 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6755 node = node->children[1];
6757 // abort if this part of the bsp tree can not be hit by this trace
6758 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6760 plane = node->plane;
6761 // axial planes are much more common than non-axial, so an optimized
6762 // axial case pays off here
6763 if (plane->type < 3)
6765 // this is an axial plane, compare bounding box directly to it and
6766 // recurse sides accordingly
6767 // recurse down node sides
6768 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6769 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6770 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6771 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6775 // this is a non-axial plane, so check if the start and end boxes
6776 // are both on one side of the plane to handle 'diagonal' cases
6777 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6781 // segment crosses plane
6782 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6785 // if sides == 0 then the trace itself is bogus (Not A Number values),
6786 // in this case we simply pretend the trace hit nothing
6788 return; // ERROR: NAN bounding box!
6789 // take whichever side the segment box is on
6790 node = node->children[sides - 1];
6793 // abort if this part of the bsp tree can not be hit by this trace
6794 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6796 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6797 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6798 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6799 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6800 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6801 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6803 leaf = (mleaf_t *)node;
6805 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6808 for (i = 0;i < leaf->numleafbrushes;i++)
6810 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6811 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6813 brush->markframe = markframe;
6814 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6817 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6819 for (i = 0;i < leaf->numleafsurfaces;i++)
6821 surface = model->data_surfaces + leaf->firstleafsurface[i];
6822 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6824 surface->deprecatedq3collisionmarkframe = markframe;
6825 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);
6832 static int markframe = 0;
6834 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)
6838 memset(trace, 0, sizeof(*trace));
6839 trace->fraction = 1;
6840 trace->realfraction = 1;
6841 trace->hitsupercontentsmask = hitsupercontentsmask;
6842 if (mod_collision_bih.integer)
6843 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6844 else if (model->brush.submodel)
6846 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6847 if (brush->colbrushf)
6848 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6851 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6854 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)
6857 float segmentmins[3], segmentmaxs[3];
6858 msurface_t *surface;
6861 if (VectorCompare(start, end))
6863 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6867 memset(trace, 0, sizeof(*trace));
6868 trace->fraction = 1;
6869 trace->realfraction = 1;
6870 trace->hitsupercontentsmask = hitsupercontentsmask;
6871 segmentmins[0] = min(start[0], end[0]) - 1;
6872 segmentmins[1] = min(start[1], end[1]) - 1;
6873 segmentmins[2] = min(start[2], end[2]) - 1;
6874 segmentmaxs[0] = max(start[0], end[0]) + 1;
6875 segmentmaxs[1] = max(start[1], end[1]) + 1;
6876 segmentmaxs[2] = max(start[2], end[2]) + 1;
6877 if (mod_collision_bih.integer)
6878 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6879 else if (model->brush.submodel)
6881 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6882 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6883 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6884 if (mod_q3bsp_curves_collisions.integer)
6885 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6886 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6887 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);
6890 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6893 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)
6895 float segmentmins[3], segmentmaxs[3];
6897 msurface_t *surface;
6900 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6902 if (VectorCompare(start->mins, end->mins))
6903 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6905 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6909 // box trace, performed as brush trace
6910 memset(trace, 0, sizeof(*trace));
6911 trace->fraction = 1;
6912 trace->realfraction = 1;
6913 trace->hitsupercontentsmask = hitsupercontentsmask;
6914 segmentmins[0] = min(start->mins[0], end->mins[0]);
6915 segmentmins[1] = min(start->mins[1], end->mins[1]);
6916 segmentmins[2] = min(start->mins[2], end->mins[2]);
6917 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6918 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6919 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6920 if (mod_collision_bih.integer)
6921 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6922 else if (model->brush.submodel)
6924 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6925 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6926 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6927 if (mod_q3bsp_curves_collisions.integer)
6928 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6929 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6930 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);
6933 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6936 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)
6938 colboxbrushf_t thisbrush_start, thisbrush_end;
6939 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6941 // box trace, performed as brush trace
6942 VectorAdd(start, boxmins, boxstartmins);
6943 VectorAdd(start, boxmaxs, boxstartmaxs);
6944 VectorAdd(end, boxmins, boxendmins);
6945 VectorAdd(end, boxmaxs, boxendmaxs);
6946 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6947 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6948 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6951 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6954 int supercontents = 0;
6956 if (mod_collision_bih.integer)
6958 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
6960 // test if the point is inside each brush
6961 else if (model->brush.submodel)
6963 // submodels are effectively one leaf
6964 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6965 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6966 supercontents |= brush->colbrushf->supercontents;
6970 mnode_t *node = model->brush.data_nodes;
6972 // find which leaf the point is in
6974 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6975 leaf = (mleaf_t *)node;
6976 // now check the brushes in the leaf
6977 for (i = 0;i < leaf->numleafbrushes;i++)
6979 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6980 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6981 supercontents |= brush->colbrushf->supercontents;
6984 return supercontents;
6987 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)
6989 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6993 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7001 int nummodelbrushes = model->nummodelbrushes;
7002 int nummodelsurfaces = model->nummodelsurfaces;
7004 const int *collisionelement3i;
7005 const float *collisionvertex3f;
7006 const int *renderelement3i;
7007 const float *rendervertex3f;
7008 bih_leaf_t *bihleafs;
7009 bih_node_t *bihnodes;
7011 int *temp_leafsortscratch;
7012 const msurface_t *surface;
7013 const q3mbrush_t *brush;
7015 // find out how many BIH leaf nodes we need
7017 if (userendersurfaces)
7019 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7020 bihnumleafs += surface->num_triangles;
7024 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7025 if (brush->colbrushf)
7027 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7029 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7030 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7032 bihnumleafs += surface->num_collisiontriangles;
7039 // allocate the memory for the BIH leaf nodes
7040 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7042 // now populate the BIH leaf nodes
7045 // add render surfaces
7046 renderelement3i = model->surfmesh.data_element3i;
7047 rendervertex3f = model->surfmesh.data_vertex3f;
7048 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7050 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7052 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7054 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7055 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7056 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7057 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7058 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7059 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7060 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7061 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7062 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7063 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7068 if (!userendersurfaces)
7070 // add collision brushes
7071 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7073 if (!brush->colbrushf)
7075 bihleafs[bihleafindex].type = BIH_BRUSH;
7076 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7077 bihleafs[bihleafindex].surfaceindex = -1;
7078 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7079 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7080 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7084 // add collision surfaces
7085 collisionelement3i = model->brush.data_collisionelement3i;
7086 collisionvertex3f = model->brush.data_collisionvertex3f;
7087 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7089 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7091 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7092 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7093 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7094 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7095 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7096 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7097 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7098 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7099 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7100 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7106 // allocate buffers for the produced and temporary data
7107 bihmaxnodes = bihnumleafs + 1;
7108 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7109 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7110 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7113 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7115 // we're done with the temporary data
7116 Mem_Free(temp_leafsort);
7118 // resize the BIH nodes array if it over-allocated
7119 if (out->maxnodes > out->numnodes)
7121 out->maxnodes = out->numnodes;
7122 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7128 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7130 int supercontents = 0;
7131 if (nativecontents & CONTENTSQ3_SOLID)
7132 supercontents |= SUPERCONTENTS_SOLID;
7133 if (nativecontents & CONTENTSQ3_WATER)
7134 supercontents |= SUPERCONTENTS_WATER;
7135 if (nativecontents & CONTENTSQ3_SLIME)
7136 supercontents |= SUPERCONTENTS_SLIME;
7137 if (nativecontents & CONTENTSQ3_LAVA)
7138 supercontents |= SUPERCONTENTS_LAVA;
7139 if (nativecontents & CONTENTSQ3_BODY)
7140 supercontents |= SUPERCONTENTS_BODY;
7141 if (nativecontents & CONTENTSQ3_CORPSE)
7142 supercontents |= SUPERCONTENTS_CORPSE;
7143 if (nativecontents & CONTENTSQ3_NODROP)
7144 supercontents |= SUPERCONTENTS_NODROP;
7145 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7146 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7147 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7148 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7149 if (nativecontents & CONTENTSQ3_DONOTENTER)
7150 supercontents |= SUPERCONTENTS_DONOTENTER;
7151 if (nativecontents & CONTENTSQ3_BOTCLIP)
7152 supercontents |= SUPERCONTENTS_BOTCLIP;
7153 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7154 supercontents |= SUPERCONTENTS_OPAQUE;
7155 return supercontents;
7158 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7160 int nativecontents = 0;
7161 if (supercontents & SUPERCONTENTS_SOLID)
7162 nativecontents |= CONTENTSQ3_SOLID;
7163 if (supercontents & SUPERCONTENTS_WATER)
7164 nativecontents |= CONTENTSQ3_WATER;
7165 if (supercontents & SUPERCONTENTS_SLIME)
7166 nativecontents |= CONTENTSQ3_SLIME;
7167 if (supercontents & SUPERCONTENTS_LAVA)
7168 nativecontents |= CONTENTSQ3_LAVA;
7169 if (supercontents & SUPERCONTENTS_BODY)
7170 nativecontents |= CONTENTSQ3_BODY;
7171 if (supercontents & SUPERCONTENTS_CORPSE)
7172 nativecontents |= CONTENTSQ3_CORPSE;
7173 if (supercontents & SUPERCONTENTS_NODROP)
7174 nativecontents |= CONTENTSQ3_NODROP;
7175 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7176 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7177 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7178 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7179 if (supercontents & SUPERCONTENTS_DONOTENTER)
7180 nativecontents |= CONTENTSQ3_DONOTENTER;
7181 if (supercontents & SUPERCONTENTS_BOTCLIP)
7182 nativecontents |= CONTENTSQ3_BOTCLIP;
7183 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7184 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7185 return nativecontents;
7188 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7193 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7194 node = node->children[1];
7196 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7197 if (loadmodel->brush.num_leafs < numleafs)
7198 loadmodel->brush.num_leafs = numleafs;
7201 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7204 q3dheader_t *header;
7205 float corner[3], yawradius, modelradius;
7207 mod->modeldatatypestring = "Q3BSP";
7209 mod->type = mod_brushq3;
7210 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7213 header = (q3dheader_t *)buffer;
7214 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7215 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7217 i = LittleLong(header->version);
7218 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7219 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7221 mod->soundfromcenter = true;
7222 mod->TraceBox = Mod_Q3BSP_TraceBox;
7223 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7224 mod->TraceLine = Mod_Q3BSP_TraceLine;
7225 mod->TracePoint = Mod_Q3BSP_TracePoint;
7226 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7227 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7228 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7229 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7230 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7231 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7232 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7233 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7234 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7235 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7236 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7237 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7238 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7239 mod->brush.AmbientSoundLevelsForPoint = NULL;
7240 mod->brush.RoundUpToHullSize = NULL;
7241 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7242 mod->Draw = R_Q1BSP_Draw;
7243 mod->DrawDepth = R_Q1BSP_DrawDepth;
7244 mod->DrawDebug = R_Q1BSP_DrawDebug;
7245 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7246 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7247 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7248 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7249 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7250 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7251 mod->DrawLight = R_Q1BSP_DrawLight;
7253 mod_base = (unsigned char *)header;
7255 // swap all the lumps
7256 header->ident = LittleLong(header->ident);
7257 header->version = LittleLong(header->version);
7258 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7259 for (i = 0;i < lumps;i++)
7261 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7262 if((char *) bufferend < (char *) buffer + j)
7263 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7264 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7265 if((char *) bufferend < (char *) buffer + j)
7266 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7269 * NO, do NOT clear them!
7270 * they contain actual data referenced by other stuff.
7271 * Instead, before using the advertisements lump, check header->versio
7273 * Sorry, but otherwise it breaks memory of the first lump.
7274 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7276 header->lumps[i].fileofs = 0;
7277 header->lumps[i].filelen = 0;
7281 mod->brush.qw_md4sum = 0;
7282 mod->brush.qw_md4sum2 = 0;
7283 for (i = 0;i < lumps;i++)
7285 if (i == Q3LUMP_ENTITIES)
7287 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7288 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7290 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7292 // all this checksumming can take a while, so let's send keepalives here too
7293 CL_KeepaliveMessage(false);
7296 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7297 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7298 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7299 if (header->version == Q3BSPVERSION_IG)
7300 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7302 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7303 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7304 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7305 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7306 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7307 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7308 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7309 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7310 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7311 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7312 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7313 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7314 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7315 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7316 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7318 // the MakePortals code works fine on the q3bsp data as well
7319 if (mod_bsp_portalize.integer)
7320 Mod_Q1BSP_MakePortals();
7322 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7323 loadmodel->brush.supportwateralpha = true;
7325 // make a single combined shadow mesh to allow optimized shadow volume creation
7326 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7328 loadmodel->brush.num_leafs = 0;
7329 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7331 if (loadmodel->brush.numsubmodels)
7332 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7335 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7340 // duplicate the basic information
7341 dpsnprintf(name, sizeof(name), "*%i", i);
7342 mod = Mod_FindName(name, loadmodel->name);
7343 // copy the base model to this one
7345 // rename the clone back to its proper name
7346 strlcpy(mod->name, name, sizeof(mod->name));
7347 mod->brush.parentmodel = loadmodel;
7348 // textures and memory belong to the main model
7349 mod->texturepool = NULL;
7350 mod->mempool = NULL;
7351 mod->brush.GetPVS = NULL;
7352 mod->brush.FatPVS = NULL;
7353 mod->brush.BoxTouchingPVS = NULL;
7354 mod->brush.BoxTouchingLeafPVS = NULL;
7355 mod->brush.BoxTouchingVisibleLeafs = NULL;
7356 mod->brush.FindBoxClusters = NULL;
7357 mod->brush.LightPoint = NULL;
7358 mod->brush.AmbientSoundLevelsForPoint = NULL;
7360 mod->brush.submodel = i;
7361 if (loadmodel->brush.submodels)
7362 loadmodel->brush.submodels[i] = mod;
7364 // make the model surface list (used by shadowing/lighting)
7365 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7366 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7367 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7368 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7369 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7370 Mod_MakeSortedSurfaces(mod);
7372 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7373 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7374 // enlarge the bounding box to enclose all geometry of this model,
7375 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7376 // which can in turn mess up the farclip (as well as culling when
7377 // outside the level - an unimportant concern)
7379 //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]);
7380 for (j = 0;j < mod->nummodelsurfaces;j++)
7382 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7383 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7385 if (!surface->num_vertices)
7387 for (k = 0;k < surface->num_vertices;k++, v += 3)
7389 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7390 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7391 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7392 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7393 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7394 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7397 //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]);
7398 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7399 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7400 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7401 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7402 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7403 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7404 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7405 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7406 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7407 mod->yawmins[2] = mod->normalmins[2];
7408 mod->yawmaxs[2] = mod->normalmaxs[2];
7409 mod->radius = modelradius;
7410 mod->radius2 = modelradius * modelradius;
7412 // this gets altered below if sky or water is used
7413 mod->DrawSky = NULL;
7414 mod->DrawAddWaterPlanes = NULL;
7416 for (j = 0;j < mod->nummodelsurfaces;j++)
7417 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7419 if (j < mod->nummodelsurfaces)
7420 mod->DrawSky = R_Q1BSP_DrawSky;
7422 for (j = 0;j < mod->nummodelsurfaces;j++)
7423 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7425 if (j < mod->nummodelsurfaces)
7426 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7428 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7429 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7431 // generate VBOs and other shared data before cloning submodels
7436 if (mod_q3bsp_sRGBlightmaps.integer)
7438 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7440 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7441 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7442 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7443 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7444 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7446 else // if this is NOT set, regular rendering looks right by this requirement anyway
7449 // we want color 1 to do the same as without sRGB
7450 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7451 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7454 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7455 // we need to undo that
7456 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7460 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);
7463 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7465 int i = LittleLong(((int *)buffer)[1]);
7466 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7467 Mod_Q3BSP_Load(mod,buffer, bufferend);
7468 else if (i == Q2BSPVERSION)
7469 Mod_Q2BSP_Load(mod,buffer, bufferend);
7471 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7474 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7476 Host_Error("Mod_MAP_Load: not yet implemented");
7479 typedef struct objvertex_s
7490 static unsigned char nobsp_pvs[1] = {1};
7492 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7494 const char *textbase = (char *)buffer, *text = textbase;
7498 char materialname[MAX_QPATH];
7499 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7500 int index1, index2, index3;
7501 objvertex_t vfirst, vprev, vcurrent;
7504 int numtriangles = 0;
7505 int maxtriangles = 0;
7506 objvertex_t *vertices = NULL;
7508 int maxtextures = 0, numtextures = 0, textureindex = 0;
7509 int maxv = 0, numv = 1;
7510 int maxvt = 0, numvt = 1;
7511 int maxvn = 0, numvn = 1;
7512 char *texturenames = NULL;
7513 float dist, modelradius, modelyawradius, yawradius;
7520 objvertex_t *thisvertex = NULL;
7521 int vertexhashindex;
7522 int *vertexhashtable = NULL;
7523 objvertex_t *vertexhashdata = NULL;
7524 objvertex_t *vdata = NULL;
7525 int vertexhashsize = 0;
7526 int vertexhashcount = 0;
7527 skinfile_t *skinfiles = NULL;
7528 unsigned char *data = NULL;
7529 int *submodelfirstsurface;
7530 msurface_t *surface;
7531 msurface_t *tempsurfaces;
7533 memset(&vfirst, 0, sizeof(vfirst));
7534 memset(&vprev, 0, sizeof(vprev));
7535 memset(&vcurrent, 0, sizeof(vcurrent));
7537 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7539 loadmodel->modeldatatypestring = "OBJ";
7541 loadmodel->type = mod_obj;
7542 loadmodel->soundfromcenter = true;
7543 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7544 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7545 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7546 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7547 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7548 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7549 loadmodel->brush.TraceLineOfSight = NULL;
7550 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7551 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7552 loadmodel->brush.GetPVS = NULL;
7553 loadmodel->brush.FatPVS = NULL;
7554 loadmodel->brush.BoxTouchingPVS = NULL;
7555 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7556 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7557 loadmodel->brush.FindBoxClusters = NULL;
7558 loadmodel->brush.LightPoint = NULL;
7559 loadmodel->brush.FindNonSolidLocation = NULL;
7560 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7561 loadmodel->brush.RoundUpToHullSize = NULL;
7562 loadmodel->brush.PointInLeaf = NULL;
7563 loadmodel->Draw = R_Q1BSP_Draw;
7564 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7565 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7566 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7567 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7568 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7569 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7570 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7571 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7572 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7574 skinfiles = Mod_LoadSkinFiles();
7575 if (loadmodel->numskins < 1)
7576 loadmodel->numskins = 1;
7578 // make skinscenes for the skins (no groups)
7579 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7580 for (i = 0;i < loadmodel->numskins;i++)
7582 loadmodel->skinscenes[i].firstframe = i;
7583 loadmodel->skinscenes[i].framecount = 1;
7584 loadmodel->skinscenes[i].loop = true;
7585 loadmodel->skinscenes[i].framerate = 10;
7591 // we always have model 0, i.e. the first "submodel"
7592 loadmodel->brush.numsubmodels = 1;
7594 // parse the OBJ text now
7597 static char emptyarg[1] = "";
7602 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7603 line[linelen] = text[linelen];
7605 for (argc = 0;argc < 4;argc++)
7606 argv[argc] = emptyarg;
7609 while (*s == ' ' || *s == '\t')
7619 while (*s == ' ' || *s == '\t')
7629 if (argv[0][0] == '#')
7631 if (!strcmp(argv[0], "v"))
7635 maxv = max(maxv * 2, 1024);
7636 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7638 if(mod_obj_orientation.integer)
7640 v[numv*3+0] = atof(argv[1]);
7641 v[numv*3+2] = atof(argv[2]);
7642 v[numv*3+1] = atof(argv[3]);
7646 v[numv*3+0] = atof(argv[1]);
7647 v[numv*3+1] = atof(argv[2]);
7648 v[numv*3+2] = atof(argv[3]);
7652 else if (!strcmp(argv[0], "vt"))
7656 maxvt = max(maxvt * 2, 1024);
7657 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7659 vt[numvt*2+0] = atof(argv[1]);
7660 vt[numvt*2+1] = 1-atof(argv[2]);
7663 else if (!strcmp(argv[0], "vn"))
7667 maxvn = max(maxvn * 2, 1024);
7668 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7670 if(mod_obj_orientation.integer)
7672 vn[numvn*3+0] = atof(argv[1]);
7673 vn[numvn*3+2] = atof(argv[2]);
7674 vn[numvn*3+1] = atof(argv[3]);
7678 vn[numvn*3+0] = atof(argv[1]);
7679 vn[numvn*3+1] = atof(argv[2]);
7680 vn[numvn*3+2] = atof(argv[3]);
7684 else if (!strcmp(argv[0], "f"))
7688 if (maxtextures <= numtextures)
7690 maxtextures = max(maxtextures * 2, 256);
7691 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7693 textureindex = numtextures++;
7694 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7696 for (j = 1;j < argc;j++)
7698 index1 = atoi(argv[j]);
7699 while(argv[j][0] && argv[j][0] != '/')
7703 index2 = atoi(argv[j]);
7704 while(argv[j][0] && argv[j][0] != '/')
7708 index3 = atoi(argv[j]);
7709 // negative refers to a recent vertex
7710 // zero means not specified
7711 // positive means an absolute vertex index
7713 index1 = numv - index1;
7715 index2 = numvt - index2;
7717 index3 = numvn - index3;
7718 vcurrent.nextindex = -1;
7719 vcurrent.textureindex = textureindex;
7720 vcurrent.submodelindex = submodelindex;
7721 if (v && index1 >= 0 && index1 < numv)
7722 VectorCopy(v + 3*index1, vcurrent.v);
7723 if (vt && index2 >= 0 && index2 < numvt)
7724 Vector2Copy(vt + 2*index2, vcurrent.vt);
7725 if (vn && index3 >= 0 && index3 < numvn)
7726 VectorCopy(vn + 3*index3, vcurrent.vn);
7727 if (numtriangles == 0)
7729 VectorCopy(vcurrent.v, mins);
7730 VectorCopy(vcurrent.v, maxs);
7734 mins[0] = min(mins[0], vcurrent.v[0]);
7735 mins[1] = min(mins[1], vcurrent.v[1]);
7736 mins[2] = min(mins[2], vcurrent.v[2]);
7737 maxs[0] = max(maxs[0], vcurrent.v[0]);
7738 maxs[1] = max(maxs[1], vcurrent.v[1]);
7739 maxs[2] = max(maxs[2], vcurrent.v[2]);
7745 if (maxtriangles <= numtriangles)
7747 maxtriangles = max(maxtriangles * 2, 32768);
7748 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7750 if(mod_obj_orientation.integer)
7752 vertices[numtriangles*3+0] = vfirst;
7753 vertices[numtriangles*3+1] = vprev;
7754 vertices[numtriangles*3+2] = vcurrent;
7758 vertices[numtriangles*3+0] = vfirst;
7759 vertices[numtriangles*3+2] = vprev;
7760 vertices[numtriangles*3+1] = vcurrent;
7767 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7769 submodelindex = atof(argv[1]);
7770 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7772 else if (!strcmp(argv[0], "usemtl"))
7774 for (i = 0;i < numtextures;i++)
7775 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7777 if (i < numtextures)
7781 if (maxtextures <= numtextures)
7783 maxtextures = max(maxtextures * 2, 256);
7784 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7786 textureindex = numtextures++;
7787 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7792 // now that we have the OBJ data loaded as-is, we can convert it
7794 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7795 VectorCopy(mins, loadmodel->normalmins);
7796 VectorCopy(maxs, loadmodel->normalmaxs);
7797 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7798 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7799 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7800 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7801 modelradius = modelyawradius + modelradius * modelradius;
7802 modelyawradius = sqrt(modelyawradius);
7803 modelradius = sqrt(modelradius);
7804 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7805 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7806 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7807 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7808 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7809 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7810 loadmodel->radius = modelradius;
7811 loadmodel->radius2 = modelradius * modelradius;
7813 // allocate storage for triangles
7814 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7815 // allocate vertex hash structures to build an optimal vertex subset
7816 vertexhashsize = numtriangles*2;
7817 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7818 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7819 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7820 vertexhashcount = 0;
7822 // gather surface stats for assigning vertex/triangle ranges
7826 loadmodel->num_surfaces = 0;
7827 // allocate storage for the worst case number of surfaces, later we resize
7828 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7829 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7830 surface = tempsurfaces;
7831 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7833 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7834 for (textureindex = 0;textureindex < numtextures;textureindex++)
7836 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7838 thisvertex = vertices + vertexindex;
7839 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7842 // skip the surface creation if there are no triangles for it
7843 if (vertexindex == numtriangles*3)
7845 // create a surface for these vertices
7846 surfacevertices = 0;
7847 surfaceelements = 0;
7848 // we hack in a texture index in the surface to be fixed up later...
7849 surface->texture = (texture_t *)((size_t)textureindex);
7850 // calculate bounds as we go
7851 VectorCopy(thisvertex->v, surface->mins);
7852 VectorCopy(thisvertex->v, surface->maxs);
7853 for (;vertexindex < numtriangles*3;vertexindex++)
7855 thisvertex = vertices + vertexindex;
7856 if (thisvertex->submodelindex != submodelindex)
7858 if (thisvertex->textureindex != textureindex)
7860 // add vertex to surface bounds
7861 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7862 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7863 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7864 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7865 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7866 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7867 // add the vertex if it is not found in the merged set, and
7868 // get its index (triangle element) for the surface
7869 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7870 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7872 vdata = vertexhashdata + i;
7873 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7878 i = vertexhashcount++;
7879 vdata = vertexhashdata + i;
7880 *vdata = *thisvertex;
7881 vdata->nextindex = vertexhashtable[vertexhashindex];
7882 vertexhashtable[vertexhashindex] = i;
7885 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7888 surfacetriangles = surfaceelements / 3;
7889 surface->num_vertices = surfacevertices;
7890 surface->num_triangles = surfacetriangles;
7891 surface->num_firstvertex = firstvertex;
7892 surface->num_firsttriangle = firsttriangle;
7893 firstvertex += surface->num_vertices;
7894 firsttriangle += surface->num_triangles;
7896 loadmodel->num_surfaces++;
7899 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7900 numvertices = firstvertex;
7901 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7902 tempsurfaces = NULL;
7904 // allocate storage for final mesh data
7905 loadmodel->num_textures = numtextures * loadmodel->numskins;
7906 loadmodel->num_texturesperskin = numtextures;
7907 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 *));
7908 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7909 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7910 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7911 loadmodel->surfmesh.num_vertices = numvertices;
7912 loadmodel->surfmesh.num_triangles = numtriangles;
7913 if (r_enableshadowvolumes.integer)
7914 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7915 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7916 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7917 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7918 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7919 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7920 if (loadmodel->surfmesh.num_vertices <= 65536)
7921 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7923 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7925 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7926 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7927 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7930 // load the textures
7931 for (textureindex = 0;textureindex < numtextures;textureindex++)
7932 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7933 Mod_FreeSkinFiles(skinfiles);
7935 // set the surface textures to their real values now that we loaded them...
7936 for (i = 0;i < loadmodel->num_surfaces;i++)
7937 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7941 Mem_Free(texturenames);
7945 Mem_Free(vertexhashtable);
7946 Mem_Free(vertexhashdata);
7948 // make a single combined shadow mesh to allow optimized shadow volume creation
7949 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7951 // compute all the mesh information that was not loaded from the file
7952 if (loadmodel->surfmesh.data_element3s)
7953 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7954 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7955 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7956 // generate normals if the file did not have them
7957 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7958 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);
7959 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);
7960 if (loadmodel->surfmesh.data_neighbor3i)
7961 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7963 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7964 loadmodel->brush.num_visleafs = 1;
7965 loadmodel->brush.num_leafs = 1;
7966 loadmodel->brush.num_nodes = 0;
7967 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7968 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7969 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7970 loadmodel->brush.num_pvsclusters = 1;
7971 loadmodel->brush.num_pvsclusterbytes = 1;
7972 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7973 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7974 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7975 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7976 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7977 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7978 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7979 loadmodel->brush.data_leafs->clusterindex = 0;
7980 loadmodel->brush.data_leafs->areaindex = 0;
7981 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7982 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7983 loadmodel->brush.data_leafs->numleafbrushes = 0;
7984 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7985 loadmodel->brush.supportwateralpha = true;
7987 if (loadmodel->brush.numsubmodels)
7988 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7991 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7996 // duplicate the basic information
7997 dpsnprintf(name, sizeof(name), "*%i", i);
7998 mod = Mod_FindName(name, loadmodel->name);
7999 // copy the base model to this one
8001 // rename the clone back to its proper name
8002 strlcpy(mod->name, name, sizeof(mod->name));
8003 mod->brush.parentmodel = loadmodel;
8004 // textures and memory belong to the main model
8005 mod->texturepool = NULL;
8006 mod->mempool = NULL;
8007 mod->brush.GetPVS = NULL;
8008 mod->brush.FatPVS = NULL;
8009 mod->brush.BoxTouchingPVS = NULL;
8010 mod->brush.BoxTouchingLeafPVS = NULL;
8011 mod->brush.BoxTouchingVisibleLeafs = NULL;
8012 mod->brush.FindBoxClusters = NULL;
8013 mod->brush.LightPoint = NULL;
8014 mod->brush.AmbientSoundLevelsForPoint = NULL;
8016 mod->brush.submodel = i;
8017 if (loadmodel->brush.submodels)
8018 loadmodel->brush.submodels[i] = mod;
8020 // make the model surface list (used by shadowing/lighting)
8021 mod->firstmodelsurface = submodelfirstsurface[i];
8022 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8023 mod->firstmodelbrush = 0;
8024 mod->nummodelbrushes = 0;
8025 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8026 Mod_MakeSortedSurfaces(mod);
8028 VectorClear(mod->normalmins);
8029 VectorClear(mod->normalmaxs);
8031 for (j = 0;j < mod->nummodelsurfaces;j++)
8033 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8034 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8036 if (!surface->num_vertices)
8041 VectorCopy(v, mod->normalmins);
8042 VectorCopy(v, mod->normalmaxs);
8044 for (k = 0;k < surface->num_vertices;k++, v += 3)
8046 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
8047 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
8048 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
8049 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
8050 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
8051 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
8054 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8055 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8056 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8057 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8058 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8059 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8060 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8061 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8062 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8063 mod->yawmins[2] = mod->normalmins[2];
8064 mod->yawmaxs[2] = mod->normalmaxs[2];
8065 mod->radius = modelradius;
8066 mod->radius2 = modelradius * modelradius;
8068 // this gets altered below if sky or water is used
8069 mod->DrawSky = NULL;
8070 mod->DrawAddWaterPlanes = NULL;
8072 for (j = 0;j < mod->nummodelsurfaces;j++)
8073 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8075 if (j < mod->nummodelsurfaces)
8076 mod->DrawSky = R_Q1BSP_DrawSky;
8078 for (j = 0;j < mod->nummodelsurfaces;j++)
8079 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8081 if (j < mod->nummodelsurfaces)
8082 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8084 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8085 mod->render_bih = mod->collision_bih;
8087 // generate VBOs and other shared data before cloning submodels
8092 Mem_Free(submodelfirstsurface);
8094 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);