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 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
698 // status variables, these don't need to be saved on the stack when
699 // recursing... but are because this should be thread-safe
700 // (note: tracing against a bbox is not thread-safe, yet)
705 // variables that need to be stored on the stack when recursing
710 // keep looping until we hit a leaf
713 // find the point distances
714 node = t->hull->clipnodes + num;
715 plane = t->hull->planes + node->planenum;
717 // axial planes can be calculated more quickly without the DotProduct
720 t1 = p1[plane->type] - plane->dist;
721 t2 = p2[plane->type] - plane->dist;
725 t1 = DotProduct (plane->normal, p1) - plane->dist;
726 t2 = DotProduct (plane->normal, p2) - plane->dist;
729 // negative plane distances indicate children[1] (behind plane)
733 // if the line starts and ends on the same side of the plane, recurse
734 // into that child instantly
735 if (p1side == p2side)
737 #if COLLISIONPARANOID >= 3
743 // loop back and process the start child
744 num = node->children[p1side];
748 // find the midpoint where the line crosses the plane, use the
749 // original line for best accuracy
750 #if COLLISIONPARANOID >= 3
755 t1 = t->start[plane->type] - plane->dist;
756 t2 = t->end[plane->type] - plane->dist;
760 t1 = DotProduct (plane->normal, t->start) - plane->dist;
761 t2 = DotProduct (plane->normal, t->end) - plane->dist;
763 midf = t1 / (t1 - t2);
764 midf = bound(p1f, midf, p2f);
765 VectorMA(t->start, midf, t->dist, mid);
767 // we now have a mid point, essentially splitting the line into
768 // the segments in the near child and the far child, we can now
769 // recurse those in order and get their results
771 // recurse both sides, front side first
772 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
773 // if this side is not empty, return what it is (solid or done)
774 if (ret != HULLCHECKSTATE_EMPTY)
777 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
778 // if other side is not solid, return what it is (empty or done)
779 if (ret != HULLCHECKSTATE_SOLID)
782 // front is air and back is solid, this is the impact point...
784 // copy the plane information, flipping it if needed
787 t->trace->plane.dist = -plane->dist;
788 VectorNegate (plane->normal, t->trace->plane.normal);
792 t->trace->plane.dist = plane->dist;
793 VectorCopy (plane->normal, t->trace->plane.normal);
796 // calculate the true fraction
797 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
798 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
799 midf = t1 / (t1 - t2);
800 t->trace->realfraction = bound(0, midf, 1);
802 // calculate the return fraction which is nudged off the surface a bit
803 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
804 t->trace->fraction = bound(0, midf, 1);
806 if (collision_prefernudgedfraction.integer)
807 t->trace->realfraction = t->trace->fraction;
809 #if COLLISIONPARANOID >= 3
812 return HULLCHECKSTATE_DONE;
816 // we reached a leaf contents
819 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
820 if (!t->trace->startfound)
822 t->trace->startfound = true;
823 t->trace->startsupercontents |= num;
825 if (num & SUPERCONTENTS_LIQUIDSMASK)
826 t->trace->inwater = true;
828 t->trace->inopen = true;
829 if (num & SUPERCONTENTS_SOLID)
830 t->trace->hittexture = &mod_q1bsp_texture_solid;
831 else if (num & SUPERCONTENTS_SKY)
832 t->trace->hittexture = &mod_q1bsp_texture_sky;
833 else if (num & SUPERCONTENTS_LAVA)
834 t->trace->hittexture = &mod_q1bsp_texture_lava;
835 else if (num & SUPERCONTENTS_SLIME)
836 t->trace->hittexture = &mod_q1bsp_texture_slime;
838 t->trace->hittexture = &mod_q1bsp_texture_water;
839 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
840 t->trace->hitsupercontents = num;
841 if (num & t->trace->hitsupercontentsmask)
843 // if the first leaf is solid, set startsolid
844 if (t->trace->allsolid)
845 t->trace->startsolid = true;
846 #if COLLISIONPARANOID >= 3
849 return HULLCHECKSTATE_SOLID;
853 t->trace->allsolid = false;
854 #if COLLISIONPARANOID >= 3
857 return HULLCHECKSTATE_EMPTY;
861 //#if COLLISIONPARANOID < 2
862 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
865 mclipnode_t *nodes = t->hull->clipnodes;
866 mplane_t *planes = t->hull->planes;
868 VectorCopy(t->start, point);
871 plane = planes + nodes[num].planenum;
872 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
874 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
875 t->trace->startsupercontents |= num;
876 if (num & SUPERCONTENTS_LIQUIDSMASK)
877 t->trace->inwater = true;
879 t->trace->inopen = true;
880 if (num & t->trace->hitsupercontentsmask)
882 t->trace->allsolid = t->trace->startsolid = true;
883 return HULLCHECKSTATE_SOLID;
887 t->trace->allsolid = t->trace->startsolid = false;
888 return HULLCHECKSTATE_EMPTY;
893 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)
895 RecursiveHullCheckTraceInfo_t rhc;
897 memset(&rhc, 0, sizeof(rhc));
898 memset(trace, 0, sizeof(trace_t));
900 rhc.trace->fraction = 1;
901 rhc.trace->realfraction = 1;
902 rhc.trace->allsolid = true;
903 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
904 VectorCopy(start, rhc.start);
905 VectorCopy(start, rhc.end);
906 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
909 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);
911 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)
913 RecursiveHullCheckTraceInfo_t rhc;
915 if (VectorCompare(start, end))
917 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
921 // 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...
922 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
924 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
928 memset(&rhc, 0, sizeof(rhc));
929 memset(trace, 0, sizeof(trace_t));
931 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
932 rhc.trace->fraction = 1;
933 rhc.trace->realfraction = 1;
934 rhc.trace->allsolid = true;
935 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
936 VectorCopy(start, rhc.start);
937 VectorCopy(end, rhc.end);
938 VectorSubtract(rhc.end, rhc.start, rhc.dist);
939 #if COLLISIONPARANOID >= 2
940 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]);
941 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
946 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
947 memset(&testtrace, 0, sizeof(trace_t));
948 rhc.trace = &testtrace;
949 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
950 rhc.trace->fraction = 1;
951 rhc.trace->realfraction = 1;
952 rhc.trace->allsolid = true;
953 VectorCopy(test, rhc.start);
954 VectorCopy(test, rhc.end);
955 VectorClear(rhc.dist);
956 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
957 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
958 if (!trace->startsolid && testtrace.startsolid)
959 Con_Printf(" - ended in solid!\n");
963 if (VectorLength2(rhc.dist))
964 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
966 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
970 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)
972 // this function currently only supports same size start and end
974 RecursiveHullCheckTraceInfo_t rhc;
976 if (VectorCompare(boxmins, boxmaxs))
978 if (VectorCompare(start, end))
979 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
981 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
985 memset(&rhc, 0, sizeof(rhc));
986 memset(trace, 0, sizeof(trace_t));
988 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
989 rhc.trace->fraction = 1;
990 rhc.trace->realfraction = 1;
991 rhc.trace->allsolid = true;
992 VectorSubtract(boxmaxs, boxmins, boxsize);
994 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
995 else if (model->brush.ishlbsp)
997 // LordHavoc: this has to have a minor tolerance (the .1) because of
998 // minor float precision errors from the box being transformed around
999 if (boxsize[0] < 32.1)
1001 if (boxsize[2] < 54) // pick the nearest of 36 or 72
1002 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
1004 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1007 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1011 // LordHavoc: this has to have a minor tolerance (the .1) because of
1012 // minor float precision errors from the box being transformed around
1013 if (boxsize[0] < 32.1)
1014 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1016 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1018 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1019 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1020 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1021 #if COLLISIONPARANOID >= 2
1022 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]);
1023 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1028 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1029 memset(&testtrace, 0, sizeof(trace_t));
1030 rhc.trace = &testtrace;
1031 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1032 rhc.trace->fraction = 1;
1033 rhc.trace->realfraction = 1;
1034 rhc.trace->allsolid = true;
1035 VectorCopy(test, rhc.start);
1036 VectorCopy(test, rhc.end);
1037 VectorClear(rhc.dist);
1038 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1039 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1040 if (!trace->startsolid && testtrace.startsolid)
1041 Con_Printf(" - ended in solid!\n");
1045 if (VectorLength2(rhc.dist))
1046 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1048 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1052 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1054 int num = model->brushq1.hulls[0].firstclipnode;
1056 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1057 mplane_t *planes = model->brushq1.hulls[0].planes;
1060 plane = planes + nodes[num].planenum;
1061 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1063 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1066 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)
1070 colplanef_t cbox_planes[6];
1072 cbox.hasaabbplanes = true;
1073 cbox.supercontents = boxsupercontents;
1076 cbox.numtriangles = 0;
1077 cbox.planes = cbox_planes;
1079 cbox.elements = NULL;
1087 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];
1088 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];
1089 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];
1090 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];
1091 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];
1092 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];
1093 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1094 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1095 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1096 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1097 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1098 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1099 memset(trace, 0, sizeof(trace_t));
1100 trace->hitsupercontentsmask = hitsupercontentsmask;
1101 trace->fraction = 1;
1102 trace->realfraction = 1;
1103 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1105 RecursiveHullCheckTraceInfo_t rhc;
1106 static hull_t box_hull;
1107 static mclipnode_t box_clipnodes[6];
1108 static mplane_t box_planes[6];
1109 // fill in a default trace
1110 memset(&rhc, 0, sizeof(rhc));
1111 memset(trace, 0, sizeof(trace_t));
1112 //To keep everything totally uniform, bounding boxes are turned into small
1113 //BSP trees instead of being compared directly.
1114 // create a temp hull from bounding box sizes
1115 box_planes[0].dist = cmaxs[0] - mins[0];
1116 box_planes[1].dist = cmins[0] - maxs[0];
1117 box_planes[2].dist = cmaxs[1] - mins[1];
1118 box_planes[3].dist = cmins[1] - maxs[1];
1119 box_planes[4].dist = cmaxs[2] - mins[2];
1120 box_planes[5].dist = cmins[2] - maxs[2];
1121 #if COLLISIONPARANOID >= 3
1122 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]);
1125 if (box_hull.clipnodes == NULL)
1129 //Set up the planes and clipnodes so that the six floats of a bounding box
1130 //can just be stored out and get a proper hull_t structure.
1132 box_hull.clipnodes = box_clipnodes;
1133 box_hull.planes = box_planes;
1134 box_hull.firstclipnode = 0;
1135 box_hull.lastclipnode = 5;
1137 for (i = 0;i < 6;i++)
1139 box_clipnodes[i].planenum = i;
1143 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1145 box_clipnodes[i].children[side^1] = i + 1;
1147 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1149 box_planes[i].type = i>>1;
1150 box_planes[i].normal[i>>1] = 1;
1154 // trace a line through the generated clipping hull
1155 //rhc.boxsupercontents = boxsupercontents;
1156 rhc.hull = &box_hull;
1158 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1159 rhc.trace->fraction = 1;
1160 rhc.trace->realfraction = 1;
1161 rhc.trace->allsolid = true;
1162 VectorCopy(start, rhc.start);
1163 VectorCopy(end, rhc.end);
1164 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1165 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1166 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1167 if (rhc.trace->startsupercontents)
1168 rhc.trace->startsupercontents = boxsupercontents;
1172 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)
1174 memset(trace, 0, sizeof(trace_t));
1175 trace->fraction = 1;
1176 trace->realfraction = 1;
1177 if (BoxesOverlap(start, start, cmins, cmaxs))
1179 trace->startsupercontents |= boxsupercontents;
1180 if (hitsupercontentsmask & boxsupercontents)
1182 trace->startsolid = true;
1183 trace->allsolid = true;
1188 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1191 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1192 return trace.fraction == 1;
1195 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)
1199 float mid, distz = endz - startz;
1203 switch (node->plane->type)
1206 node = node->children[x < node->plane->dist];
1207 continue; // loop back and process the new node
1209 node = node->children[y < node->plane->dist];
1210 continue; // loop back and process the new node
1212 side = startz < node->plane->dist;
1213 if ((endz < node->plane->dist) == side)
1215 node = node->children[side];
1216 continue; // loop back and process the new node
1218 // found an intersection
1219 mid = node->plane->dist;
1222 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1223 front += startz * node->plane->normal[2];
1224 back += endz * node->plane->normal[2];
1225 side = front < node->plane->dist;
1226 if ((back < node->plane->dist) == side)
1228 node = node->children[side];
1229 continue; // loop back and process the new node
1231 // found an intersection
1232 mid = startz + distz * (front - node->plane->dist) / (front - back);
1236 // go down front side
1237 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1238 return true; // hit something
1240 // check for impact on this node
1241 if (node->numsurfaces)
1244 int dsi, dti, lmwidth, lmheight;
1246 msurface_t *surface;
1247 unsigned char *lightmap;
1248 int maps, line3, size3;
1251 float scale, w, w00, w01, w10, w11;
1253 surface = model->data_surfaces + node->firstsurface;
1254 for (i = 0;i < node->numsurfaces;i++, surface++)
1256 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1257 continue; // no lightmaps
1259 // location we want to sample in the lightmap
1260 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;
1261 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;
1264 // thanks to jitspoe for pointing out that this int cast was
1265 // rounding toward zero, so we floor it
1266 dsi = (int)floor(ds);
1267 dti = (int)floor(dt);
1268 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1269 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1272 // we have to tolerate a position of lmwidth-1 for some rare
1273 // cases - in which case the sampling position still gets
1274 // clamped but the color gets interpolated to that edge.
1275 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1277 // in the rare cases where we're sampling slightly off
1278 // the polygon, clamp the sampling position (we can still
1279 // interpolate outside it, where it becomes extrapolation)
1284 if (dsi > lmwidth-2)
1286 if (dti > lmheight-2)
1289 // calculate bilinear interpolation factors
1290 // and also multiply by fixedpoint conversion factors to
1291 // compensate for lightmaps being 0-255 (as 0-2), we use
1292 // r_refdef.scene.rtlightstylevalue here which is already
1293 // 0.000-2.148 range
1294 // (if we used r_refdef.scene.lightstylevalue this
1295 // divisor would be 32768 rather than 128)
1298 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1299 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1300 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1301 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1303 // values for pointer math
1304 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1305 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1307 // look up the pixel
1308 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1310 // bilinear filter each lightmap style, and sum them
1311 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1313 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1314 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1315 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1316 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1317 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1321 return true; // success
1326 // go down back side
1327 node = node->children[side ^ 1];
1329 distz = endz - startz;
1330 // loop back and process the new node
1333 // did not hit anything
1337 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1339 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1340 VectorSet(diffusenormal, 0, 0, 1);
1342 if (!model->brushq1.lightdata)
1344 VectorSet(ambientcolor, 1, 1, 1);
1345 VectorSet(diffusecolor, 0, 0, 0);
1349 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);
1352 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1357 const msurface_t *surface;
1362 float edgenormal[3];
1369 surface = model->data_surfaces + node->firstsurface;
1370 for (i = 0;i < node->numsurfaces;i++, surface++)
1372 // skip surfaces whose bounding box does not include the point
1373 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1375 // skip faces with contents we don't care about
1376 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1378 // get the surface normal - since it is flat we know any vertex normal will suffice
1379 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1381 if (DotProduct(t->dist, normal) > 0)
1383 // iterate edges and see if the point is outside one of them
1384 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1386 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1387 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1388 VectorSubtract(v0, v1, edgedir);
1389 CrossProduct(edgedir, normal, edgenormal);
1390 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1393 // if the point is outside one of the edges, it is not within the surface
1394 if (j < surface->num_vertices)
1397 // we hit a surface, this is the impact point...
1398 VectorCopy(normal, t->trace->plane.normal);
1399 t->trace->plane.dist = DotProduct(normal, p);
1401 // calculate the true fraction
1402 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1403 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1404 midf = t1 / (t1 - t2);
1405 t->trace->realfraction = midf;
1407 // calculate the return fraction which is nudged off the surface a bit
1408 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1409 t->trace->fraction = bound(0, midf, 1);
1411 if (collision_prefernudgedfraction.integer)
1412 t->trace->realfraction = t->trace->fraction;
1414 t->trace->hittexture = surface->texture->currentframe;
1415 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1416 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1417 return surface->texture->currentframe;
1422 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])
1424 const mplane_t *plane;
1427 double midf, mid[3];
1428 const mleaf_t *leaf;
1432 plane = node->plane;
1433 if (plane->type < 3)
1435 t1 = p1[plane->type] - plane->dist;
1436 t2 = p2[plane->type] - plane->dist;
1440 t1 = DotProduct (plane->normal, p1) - plane->dist;
1441 t2 = DotProduct (plane->normal, p2) - plane->dist;
1447 node = node->children[1];
1456 node = node->children[0];
1462 // the line intersects, find intersection point
1463 // LordHavoc: this uses the original trace for maximum accuracy
1464 if (plane->type < 3)
1466 t1 = t->start[plane->type] - plane->dist;
1467 t2 = t->end[plane->type] - plane->dist;
1471 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1472 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1475 midf = t1 / (t1 - t2);
1476 VectorMA(t->start, midf, t->dist, mid);
1478 // recurse both sides, front side first, return if we hit a surface
1479 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1480 return HULLCHECKSTATE_DONE;
1482 // test each surface on the node
1483 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1484 if (t->trace->hittexture)
1485 return HULLCHECKSTATE_DONE;
1487 // recurse back side
1488 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1490 leaf = (const mleaf_t *)node;
1491 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1492 if (!t->trace->startfound)
1494 t->trace->startfound = true;
1495 t->trace->startsupercontents |= side;
1497 if (side & SUPERCONTENTS_LIQUIDSMASK)
1498 t->trace->inwater = true;
1500 t->trace->inopen = true;
1501 if (side & t->trace->hitsupercontentsmask)
1503 // if the first leaf is solid, set startsolid
1504 if (t->trace->allsolid)
1505 t->trace->startsolid = true;
1506 return HULLCHECKSTATE_SOLID;
1510 t->trace->allsolid = false;
1511 return HULLCHECKSTATE_EMPTY;
1515 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)
1517 RecursiveHullCheckTraceInfo_t rhc;
1519 memset(&rhc, 0, sizeof(rhc));
1520 memset(trace, 0, sizeof(trace_t));
1522 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1523 rhc.trace->fraction = 1;
1524 rhc.trace->realfraction = 1;
1525 rhc.trace->allsolid = true;
1526 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1527 VectorCopy(start, rhc.start);
1528 VectorCopy(end, rhc.end);
1529 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1530 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1531 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1534 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1537 unsigned char *outstart = out;
1538 while (out < outend)
1542 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));
1552 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));
1555 for (c = *in++;c > 0;c--)
1559 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));
1570 R_Q1BSP_LoadSplitSky
1572 A sky texture is 256*128, with the right side being a masked overlay
1575 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1580 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1581 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1583 // allocate a texture pool if we need it
1584 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1585 loadmodel->texturepool = R_AllocTexturePool();
1587 if (bytesperpixel == 4)
1589 for (y = 0;y < h;y++)
1591 for (x = 0;x < w;x++)
1593 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1594 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1600 // make an average value for the back to avoid
1601 // a fringe on the top level
1610 for (y = 0;y < h;y++)
1612 for (x = 0;x < w;x++)
1614 p = src[x*width+y+w];
1615 r += palette_rgb[p][0];
1616 g += palette_rgb[p][1];
1617 b += palette_rgb[p][2];
1620 bgra.b[2] = r/(w*h);
1621 bgra.b[1] = g/(w*h);
1622 bgra.b[0] = b/(w*h);
1624 for (y = 0;y < h;y++)
1626 for (x = 0;x < w;x++)
1628 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1630 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1635 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1636 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1637 Mem_Free(solidpixels);
1638 Mem_Free(alphapixels);
1641 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1643 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1644 skinframe_t *skinframe;
1645 texture_t *tx, *tx2, *anims[10], *altanims[10];
1646 texture_t backuptex;
1647 unsigned char *data, *mtdata;
1649 char mapname[MAX_QPATH], name[MAX_QPATH];
1650 unsigned char zeroopaque[4], zerotrans[4];
1653 Vector4Set(zeroopaque, 0, 0, 0, 255);
1654 Vector4Set(zerotrans, 0, 0, 0, 128);
1656 loadmodel->data_textures = NULL;
1658 // add two slots for notexture walls and notexture liquids
1661 nummiptex = MSG_ReadLittleLong(sb);
1662 loadmodel->num_textures = nummiptex + 2;
1663 loadmodel->num_texturesperskin = loadmodel->num_textures;
1667 loadmodel->num_textures = 2;
1668 loadmodel->num_texturesperskin = loadmodel->num_textures;
1671 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1673 // fill out all slots with notexture
1674 if (cls.state != ca_dedicated)
1675 skinframe = R_SkinFrame_LoadMissing();
1678 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1680 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1683 if (cls.state != ca_dedicated)
1685 tx->numskinframes = 1;
1686 tx->skinframerate = 1;
1687 tx->skinframes[0] = skinframe;
1688 tx->currentskinframe = tx->skinframes[0];
1690 tx->basematerialflags = MATERIALFLAG_WALL;
1691 if (i == loadmodel->num_textures - 1)
1693 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1694 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1695 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1699 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1700 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1702 tx->currentframe = tx;
1704 // clear water settings
1707 tx->refractfactor = 1;
1708 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1709 tx->reflectfactor = 1;
1710 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1711 tx->r_water_wateralpha = 1;
1712 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1713 tx->offsetscale = 1;
1715 tx->specularscalemod = 1;
1716 tx->specularpowermod = 1;
1717 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1718 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1719 // JUST GREP FOR "specularscalemod = 1".
1724 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1728 s = loadmodel->name;
1729 if (!strncasecmp(s, "maps/", 5))
1731 FS_StripExtension(s, mapname, sizeof(mapname));
1733 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1734 // LordHavoc: mostly rewritten map texture loader
1735 for (i = 0;i < nummiptex;i++)
1737 doffset = MSG_ReadLittleLong(sb);
1738 if (r_nosurftextures.integer)
1742 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1746 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1748 // copy name, but only up to 16 characters
1749 // (the output buffer can hold more than this, but the input buffer is
1751 for (j = 0;j < 16;j++)
1752 name[j] = MSG_ReadByte(&miptexsb);
1754 // pretty up the buffer (replacing any trailing garbage with 0)
1755 for (j = strlen(name);j < 16;j++)
1760 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1761 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1764 mtwidth = MSG_ReadLittleLong(&miptexsb);
1765 mtheight = MSG_ReadLittleLong(&miptexsb);
1767 j = MSG_ReadLittleLong(&miptexsb);
1771 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1773 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1776 mtdata = miptexsb.data + j;
1779 if ((mtwidth & 15) || (mtheight & 15))
1780 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1782 // LordHavoc: force all names to lowercase
1783 for (j = 0;name[j];j++)
1784 if (name[j] >= 'A' && name[j] <= 'Z')
1785 name[j] += 'a' - 'A';
1787 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1788 backuptex = loadmodel->data_textures[i];
1789 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1791 loadmodel->data_textures[i] = backuptex;
1793 tx = loadmodel->data_textures + i;
1794 strlcpy(tx->name, name, sizeof(tx->name));
1795 tx->width = mtwidth;
1796 tx->height = mtheight;
1798 if (tx->name[0] == '*')
1800 if (!strncmp(tx->name, "*lava", 5))
1802 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1803 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1805 else if (!strncmp(tx->name, "*slime", 6))
1807 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1808 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1812 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1813 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1816 else if (!strncmp(tx->name, "sky", 3))
1818 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1819 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1820 // for the surface traceline we need to hit this surface as a solid...
1821 tx->supercontents |= SUPERCONTENTS_SOLID;
1825 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1826 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1829 if (cls.state != ca_dedicated)
1831 // LordHavoc: HL sky textures are entirely different than quake
1832 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1834 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1836 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1837 if (data && image_width == image_height * 2)
1839 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1842 else if (mtdata != NULL)
1843 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1847 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);
1849 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);
1851 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1854 // did not find external texture, load it from the bsp or wad3
1855 if (loadmodel->brush.ishlbsp)
1857 // internal texture overrides wad
1858 unsigned char *pixels, *freepixels;
1859 pixels = freepixels = NULL;
1861 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1863 pixels = freepixels = W_GetTextureBGRA(tx->name);
1866 tx->width = image_width;
1867 tx->height = image_height;
1868 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1871 Mem_Free(freepixels);
1873 else if (mtdata) // texture included
1874 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1876 // if skinframe is still NULL the "missing" texture will be used
1878 tx->skinframes[0] = skinframe;
1880 // LordHavoc: some Tenebrae textures get replaced by black
1881 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1882 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1883 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1884 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1887 tx->basematerialflags = MATERIALFLAG_WALL;
1888 if (tx->name[0] == '*')
1890 // LordHavoc: some turbulent textures should not be affected by wateralpha
1891 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1892 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1893 else if (!strncmp(tx->name,"*lava",5)
1894 || !strncmp(tx->name,"*teleport",9)
1895 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1896 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1898 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1899 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1900 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1902 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1904 // replace the texture with black
1905 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1907 else if (!strncmp(tx->name, "sky", 3))
1908 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1909 else if (!strcmp(tx->name, "caulk"))
1910 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1911 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1912 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1914 // start out with no animation
1915 tx->currentframe = tx;
1916 tx->currentskinframe = tx->skinframes[0];
1917 tx->currentmaterialflags = tx->basematerialflags;
1920 // sequence the animations
1921 for (i = 0;i < nummiptex;i++)
1923 tx = loadmodel->data_textures + i;
1924 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1926 if (tx->anim_total[0] || tx->anim_total[1])
1927 continue; // already sequenced
1929 // find the number of frames in the animation
1930 memset(anims, 0, sizeof(anims));
1931 memset(altanims, 0, sizeof(altanims));
1933 for (j = i;j < nummiptex;j++)
1935 tx2 = loadmodel->data_textures + j;
1936 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1940 if (num >= '0' && num <= '9')
1941 anims[num - '0'] = tx2;
1942 else if (num >= 'a' && num <= 'j')
1943 altanims[num - 'a'] = tx2;
1945 Con_Printf("Bad animating texture %s\n", tx->name);
1949 for (j = 0;j < 10;j++)
1956 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1959 for (j = 0;j < max;j++)
1963 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1967 for (j = 0;j < altmax;j++)
1971 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1980 // if there is no alternate animation, duplicate the primary
1981 // animation into the alternate
1983 for (k = 0;k < 10;k++)
1984 altanims[k] = anims[k];
1987 // link together the primary animation
1988 for (j = 0;j < max;j++)
1991 tx2->animated = true;
1992 tx2->anim_total[0] = max;
1993 tx2->anim_total[1] = altmax;
1994 for (k = 0;k < 10;k++)
1996 tx2->anim_frames[0][k] = anims[k];
1997 tx2->anim_frames[1][k] = altanims[k];
2001 // if there really is an alternate anim...
2002 if (anims[0] != altanims[0])
2004 // link together the alternate animation
2005 for (j = 0;j < altmax;j++)
2008 tx2->animated = true;
2009 // the primary/alternate are reversed here
2010 tx2->anim_total[0] = altmax;
2011 tx2->anim_total[1] = max;
2012 for (k = 0;k < 10;k++)
2014 tx2->anim_frames[0][k] = altanims[k];
2015 tx2->anim_frames[1][k] = anims[k];
2022 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2025 unsigned char *in, *out, *data, d;
2026 char litfilename[MAX_QPATH];
2027 char dlitfilename[MAX_QPATH];
2028 fs_offset_t filesize;
2029 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2031 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2032 for (i = 0;i < sb->cursize;i++)
2033 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2035 else // LordHavoc: bsp version 29 (normal white lighting)
2037 // LordHavoc: hope is not lost yet, check for a .lit file to load
2038 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2039 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2040 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2041 strlcat (litfilename, ".lit", sizeof (litfilename));
2042 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2043 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2046 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2048 i = LittleLong(((int *)data)[1]);
2051 if (developer_loading.integer)
2052 Con_Printf("loaded %s\n", litfilename);
2053 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2054 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2056 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2059 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2061 i = LittleLong(((int *)data)[1]);
2064 if (developer_loading.integer)
2065 Con_Printf("loaded %s\n", dlitfilename);
2066 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2067 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2068 loadmodel->brushq3.deluxemapping_modelspace = false;
2069 loadmodel->brushq3.deluxemapping = true;
2078 Con_Printf("Unknown .lit file version (%d)\n", i);
2080 else if (filesize == 8)
2081 Con_Print("Empty .lit file, ignoring\n");
2083 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2090 // LordHavoc: oh well, expand the white lighting data
2093 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2095 out = loadmodel->brushq1.lightdata;
2096 for (i = 0;i < sb->cursize;i++)
2106 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2108 loadmodel->brushq1.num_compressedpvs = 0;
2109 loadmodel->brushq1.data_compressedpvs = NULL;
2112 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2113 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2114 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2117 // used only for HalfLife maps
2118 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2120 char key[128], value[4096];
2124 if (!COM_ParseToken_Simple(&data, false, false, true))
2126 if (com_token[0] != '{')
2130 if (!COM_ParseToken_Simple(&data, false, false, true))
2132 if (com_token[0] == '}')
2133 break; // end of worldspawn
2134 if (com_token[0] == '_')
2135 strlcpy(key, com_token + 1, sizeof(key));
2137 strlcpy(key, com_token, sizeof(key));
2138 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2139 key[strlen(key)-1] = 0;
2140 if (!COM_ParseToken_Simple(&data, false, false, true))
2142 dpsnprintf(value, sizeof(value), "%s", com_token);
2143 if (!strcmp("wad", key)) // for HalfLife maps
2145 if (loadmodel->brush.ishlbsp)
2148 for (i = 0;i < (int)sizeof(value);i++)
2149 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2153 for (;i < (int)sizeof(value);i++)
2155 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2156 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2158 else if (value[i] == ';' || value[i] == 0)
2162 W_LoadTextureWadFile(&value[j], false);
2174 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2176 loadmodel->brush.entities = NULL;
2179 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2180 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2181 loadmodel->brush.entities[sb->cursize] = 0;
2182 if (loadmodel->brush.ishlbsp)
2183 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2187 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2191 size_t structsize = 12;
2193 if (sb->cursize % structsize)
2194 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2195 count = sb->cursize / structsize;
2196 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2198 loadmodel->brushq1.vertexes = out;
2199 loadmodel->brushq1.numvertexes = count;
2201 for ( i=0 ; i<count ; i++, out++)
2203 out->position[0] = MSG_ReadLittleFloat(sb);
2204 out->position[1] = MSG_ReadLittleFloat(sb);
2205 out->position[2] = MSG_ReadLittleFloat(sb);
2209 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2213 size_t structsize = (48+4*hullinfo->filehulls);
2215 if (sb->cursize % structsize)
2216 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2218 count = sb->cursize / structsize;
2219 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2221 loadmodel->brushq1.submodels = out;
2222 loadmodel->brush.numsubmodels = count;
2224 for (i = 0; i < count; i++, out++)
2226 // spread out the mins / maxs by a pixel
2227 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2228 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2229 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2230 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2231 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2232 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2233 out->origin[0] = MSG_ReadLittleFloat(sb);
2234 out->origin[1] = MSG_ReadLittleFloat(sb);
2235 out->origin[2] = MSG_ReadLittleFloat(sb);
2236 for (j = 0; j < hullinfo->filehulls; j++)
2237 out->headnode[j] = MSG_ReadLittleLong(sb);
2238 out->visleafs = MSG_ReadLittleLong(sb);
2239 out->firstface = MSG_ReadLittleLong(sb);
2240 out->numfaces = MSG_ReadLittleLong(sb);
2244 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2248 size_t structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2250 if (sb->cursize % structsize)
2251 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2252 count = sb->cursize / structsize;
2253 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2255 loadmodel->brushq1.edges = out;
2256 loadmodel->brushq1.numedges = count;
2258 for ( i=0 ; i<count ; i++, out++)
2260 if (loadmodel->brush.isbsp2)
2262 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2263 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2267 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2268 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2270 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2272 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);
2273 if(!loadmodel->brushq1.numvertexes)
2274 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2282 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2285 int i, j, k, count, miptex;
2286 size_t structsize = 40;
2288 if (sb->cursize % structsize)
2289 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2290 count = sb->cursize / structsize;
2291 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2293 loadmodel->brushq1.texinfo = out;
2294 loadmodel->brushq1.numtexinfo = count;
2296 for (i = 0;i < count;i++, out++)
2298 for (k = 0;k < 2;k++)
2299 for (j = 0;j < 4;j++)
2300 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2302 miptex = MSG_ReadLittleLong(sb);
2303 out->flags = MSG_ReadLittleLong(sb);
2305 out->texture = NULL;
2306 if (loadmodel->data_textures)
2308 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2309 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2311 out->texture = loadmodel->data_textures + miptex;
2313 if (out->flags & TEX_SPECIAL)
2315 // if texture chosen is NULL or the shader needs a lightmap,
2316 // force to notexture water shader
2317 if (out->texture == NULL)
2318 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2322 // if texture chosen is NULL, force to notexture
2323 if (out->texture == NULL)
2324 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2330 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2335 mins[0] = mins[1] = mins[2] = 9999;
2336 maxs[0] = maxs[1] = maxs[2] = -9999;
2338 for (i = 0;i < numverts;i++)
2340 for (j = 0;j < 3;j++, v++)
2350 #define MAX_SUBDIVPOLYTRIANGLES 4096
2351 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2353 static int subdivpolyverts, subdivpolytriangles;
2354 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2355 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2357 static int subdivpolylookupvert(vec3_t v)
2360 for (i = 0;i < subdivpolyverts;i++)
2361 if (subdivpolyvert[i][0] == v[0]
2362 && subdivpolyvert[i][1] == v[1]
2363 && subdivpolyvert[i][2] == v[2])
2365 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2366 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2367 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2368 return subdivpolyverts++;
2371 static void SubdividePolygon(int numverts, float *verts)
2373 int i, i1, i2, i3, f, b, c, p;
2374 vec3_t mins, maxs, front[256], back[256];
2375 float m, *pv, *cv, dist[256], frac;
2378 Host_Error("SubdividePolygon: ran out of verts in buffer");
2380 BoundPoly(numverts, verts, mins, maxs);
2382 for (i = 0;i < 3;i++)
2384 m = (mins[i] + maxs[i]) * 0.5;
2385 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2386 if (maxs[i] - m < 8)
2388 if (m - mins[i] < 8)
2392 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2393 dist[c] = cv[i] - m;
2396 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2400 VectorCopy(pv, front[f]);
2405 VectorCopy(pv, back[b]);
2408 if (dist[p] == 0 || dist[c] == 0)
2410 if ((dist[p] > 0) != (dist[c] > 0) )
2413 frac = dist[p] / (dist[p] - dist[c]);
2414 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2415 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2416 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2422 SubdividePolygon(f, front[0]);
2423 SubdividePolygon(b, back[0]);
2427 i1 = subdivpolylookupvert(verts);
2428 i2 = subdivpolylookupvert(verts + 3);
2429 for (i = 2;i < numverts;i++)
2431 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2433 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2437 i3 = subdivpolylookupvert(verts + i * 3);
2438 subdivpolyindex[subdivpolytriangles][0] = i1;
2439 subdivpolyindex[subdivpolytriangles][1] = i2;
2440 subdivpolyindex[subdivpolytriangles][2] = i3;
2442 subdivpolytriangles++;
2446 //Breaks a polygon up along axial 64 unit
2447 //boundaries so that turbulent and sky warps
2448 //can be done reasonably.
2449 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2455 subdivpolytriangles = 0;
2456 subdivpolyverts = 0;
2457 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2458 if (subdivpolytriangles < 1)
2459 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2461 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2462 mesh->num_vertices = subdivpolyverts;
2463 mesh->num_triangles = subdivpolytriangles;
2464 mesh->vertex = (surfvertex_t *)(mesh + 1);
2465 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2466 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2468 for (i = 0;i < mesh->num_triangles;i++)
2469 for (j = 0;j < 3;j++)
2470 mesh->index[i*3+j] = subdivpolyindex[i][j];
2472 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2474 VectorCopy(subdivpolyvert[i], v->v);
2475 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2476 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2481 extern cvar_t gl_max_lightmapsize;
2482 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2484 msurface_t *surface;
2485 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2486 float texmins[2], texmaxs[2], val;
2487 rtexture_t *lightmaptexture, *deluxemaptexture;
2489 size_t structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2491 if (sb->cursize % structsize)
2492 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2493 count = sb->cursize / structsize;
2494 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2495 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2497 loadmodel->num_surfaces = count;
2499 loadmodel->brushq1.firstrender = true;
2500 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2504 for (surfacenum = 0;surfacenum < count;surfacenum++)
2506 if (loadmodel->brush.isbsp2)
2507 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2509 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2510 totalverts += numedges;
2511 totaltris += numedges - 2;
2514 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2516 lightmaptexture = NULL;
2517 deluxemaptexture = r_texture_blanknormalmap;
2519 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2520 totallightmapsamples = 0;
2524 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2526 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2527 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2528 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2529 firstedge = MSG_ReadLittleLong(sb);
2530 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2531 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2532 for (i = 0;i < MAXLIGHTMAPS;i++)
2533 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2534 lightmapoffset = MSG_ReadLittleLong(sb);
2536 // FIXME: validate edges, texinfo, etc?
2537 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)
2538 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2539 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2540 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2541 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2542 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2544 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2545 surface->texture = surface->lightmapinfo->texinfo->texture;
2547 //surface->flags = surface->texture->flags;
2548 //if (LittleShort(in->side))
2549 // surface->flags |= SURF_PLANEBACK;
2550 //surface->plane = loadmodel->brush.data_planes + planenum;
2552 surface->num_firstvertex = totalverts;
2553 surface->num_vertices = numedges;
2554 surface->num_firsttriangle = totaltris;
2555 surface->num_triangles = numedges - 2;
2556 totalverts += numedges;
2557 totaltris += numedges - 2;
2559 // convert edges back to a normal polygon
2560 for (i = 0;i < surface->num_vertices;i++)
2562 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2564 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2566 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2568 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2569 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2570 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2571 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2572 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2573 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2574 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2575 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2578 for (i = 0;i < surface->num_triangles;i++)
2580 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2581 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2582 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2585 // compile additional data about the surface geometry
2586 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);
2587 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);
2588 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2590 // generate surface extents information
2591 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2592 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2593 for (i = 1;i < surface->num_vertices;i++)
2595 for (j = 0;j < 2;j++)
2597 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2598 texmins[j] = min(texmins[j], val);
2599 texmaxs[j] = max(texmaxs[j], val);
2602 for (i = 0;i < 2;i++)
2604 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2605 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2608 smax = surface->lightmapinfo->extents[0] >> 4;
2609 tmax = surface->lightmapinfo->extents[1] >> 4;
2610 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2611 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2614 surface->lightmaptexture = NULL;
2615 surface->deluxemaptexture = r_texture_blanknormalmap;
2616 if (lightmapoffset == -1)
2618 surface->lightmapinfo->samples = NULL;
2620 // give non-lightmapped water a 1x white lightmap
2621 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2623 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2624 surface->lightmapinfo->styles[0] = 0;
2625 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2629 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2630 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2631 else // LordHavoc: white lighting (bsp version 29)
2633 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2634 if (loadmodel->brushq1.nmaplightdata)
2635 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2638 // check if we should apply a lightmap to this
2639 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2641 if (ssize > 256 || tsize > 256)
2642 Host_Error("Bad surface extents");
2644 if (lightmapsize < ssize)
2645 lightmapsize = ssize;
2646 if (lightmapsize < tsize)
2647 lightmapsize = tsize;
2649 totallightmapsamples += ssize*tsize;
2651 // force lightmap upload on first time seeing the surface
2653 // additionally this is used by the later code to see if a
2654 // lightmap is needed on this surface (rather than duplicating the
2656 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2657 loadmodel->lit = true;
2661 // small maps (such as ammo boxes especially) don't need big lightmap
2662 // textures, so this code tries to guess a good size based on
2663 // totallightmapsamples (size of the lightmaps lump basically), as well as
2664 // trying to max out the size if there is a lot of lightmap data to store
2665 // additionally, never choose a lightmapsize that is smaller than the
2666 // largest surface encountered (as it would fail)
2668 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2671 // now that we've decided the lightmap texture size, we can do the rest
2672 if (cls.state != ca_dedicated)
2674 int stainmapsize = 0;
2675 mod_alloclightmap_state_t allocState;
2677 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2678 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2680 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2681 float u, v, ubase, vbase, uscale, vscale;
2683 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2686 smax = surface->lightmapinfo->extents[0] >> 4;
2687 tmax = surface->lightmapinfo->extents[1] >> 4;
2688 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2689 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2690 stainmapsize += ssize * tsize * 3;
2692 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2694 // allocate a texture pool if we need it
2695 if (loadmodel->texturepool == NULL)
2696 loadmodel->texturepool = R_AllocTexturePool();
2697 // could not find room, make a new lightmap
2698 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2699 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2700 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2701 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);
2702 if (loadmodel->brushq1.nmaplightdata)
2703 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);
2705 Mod_AllocLightmap_Reset(&allocState);
2706 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2708 surface->lightmaptexture = lightmaptexture;
2709 surface->deluxemaptexture = deluxemaptexture;
2710 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2711 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2713 uscale = 1.0f / (float)lightmapsize;
2714 vscale = 1.0f / (float)lightmapsize;
2715 ubase = lightmapx * uscale;
2716 vbase = lightmapy * vscale;
2718 for (i = 0;i < surface->num_vertices;i++)
2720 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);
2721 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);
2722 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2723 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2724 // LordHavoc: calc lightmap data offset for vertex lighting to use
2727 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2731 if (cl_stainmaps.integer)
2733 // allocate stainmaps for permanent marks on walls and clear white
2734 unsigned char *stainsamples = NULL;
2735 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2736 memset(stainsamples, 255, stainmapsize);
2738 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2740 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2742 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2743 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2744 surface->lightmapinfo->stainsamples = stainsamples;
2745 stainsamples += ssize * tsize * 3;
2750 // generate ushort elements array if possible
2751 if (loadmodel->surfmesh.data_element3s)
2752 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2753 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2756 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2759 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2760 node->parent = parent;
2763 // this is a node, recurse to children
2764 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2765 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2766 // combine supercontents of children
2767 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2772 mleaf_t *leaf = (mleaf_t *)node;
2773 // if this is a leaf, calculate supercontents mask from all collidable
2774 // primitives in the leaf (brushes and collision surfaces)
2775 // also flag if the leaf contains any collision surfaces
2776 leaf->combinedsupercontents = 0;
2777 // combine the supercontents values of all brushes in this leaf
2778 for (j = 0;j < leaf->numleafbrushes;j++)
2779 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2780 // check if this leaf contains any collision surfaces (q3 patches)
2781 for (j = 0;j < leaf->numleafsurfaces;j++)
2783 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2784 if (surface->num_collisiontriangles)
2786 leaf->containscollisionsurfaces = true;
2787 leaf->combinedsupercontents |= surface->texture->supercontents;
2793 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2795 int i, j, count, p, child[2];
2797 size_t structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2799 if (sb->cursize % structsize)
2800 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2801 count = sb->cursize / structsize;
2803 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2804 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2806 loadmodel->brush.data_nodes = out;
2807 loadmodel->brush.num_nodes = count;
2809 for ( i=0 ; i<count ; i++, out++)
2811 p = MSG_ReadLittleLong(sb);
2812 out->plane = loadmodel->brush.data_planes + p;
2814 if (loadmodel->brush.isbsp2rmqe)
2816 child[0] = MSG_ReadLittleLong(sb);
2817 child[1] = MSG_ReadLittleLong(sb);
2818 out->mins[0] = MSG_ReadLittleShort(sb);
2819 out->mins[1] = MSG_ReadLittleShort(sb);
2820 out->mins[2] = MSG_ReadLittleShort(sb);
2821 out->maxs[0] = MSG_ReadLittleShort(sb);
2822 out->maxs[1] = MSG_ReadLittleShort(sb);
2823 out->maxs[2] = MSG_ReadLittleShort(sb);
2824 out->firstsurface = MSG_ReadLittleLong(sb);
2825 out->numsurfaces = MSG_ReadLittleLong(sb);
2827 else if (loadmodel->brush.isbsp2)
2829 child[0] = MSG_ReadLittleLong(sb);
2830 child[1] = MSG_ReadLittleLong(sb);
2831 out->mins[0] = MSG_ReadLittleFloat(sb);
2832 out->mins[1] = MSG_ReadLittleFloat(sb);
2833 out->mins[2] = MSG_ReadLittleFloat(sb);
2834 out->maxs[0] = MSG_ReadLittleFloat(sb);
2835 out->maxs[1] = MSG_ReadLittleFloat(sb);
2836 out->maxs[2] = MSG_ReadLittleFloat(sb);
2837 out->firstsurface = MSG_ReadLittleLong(sb);
2838 out->numsurfaces = MSG_ReadLittleLong(sb);
2842 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2843 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2844 if (child[0] >= count)
2846 if (child[1] >= count)
2849 out->mins[0] = MSG_ReadLittleShort(sb);
2850 out->mins[1] = MSG_ReadLittleShort(sb);
2851 out->mins[2] = MSG_ReadLittleShort(sb);
2852 out->maxs[0] = MSG_ReadLittleShort(sb);
2853 out->maxs[1] = MSG_ReadLittleShort(sb);
2854 out->maxs[2] = MSG_ReadLittleShort(sb);
2856 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2857 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2860 for (j=0 ; j<2 ; j++)
2862 // LordHavoc: this code supports broken bsp files produced by
2863 // arguire qbsp which can produce more than 32768 nodes, any value
2864 // below count is assumed to be a node number, any other value is
2865 // assumed to be a leaf number
2869 if (p < loadmodel->brush.num_nodes)
2870 out->children[j] = loadmodel->brush.data_nodes + p;
2873 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2874 // map it to the solid leaf
2875 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2880 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2882 if (p < loadmodel->brush.num_leafs)
2883 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2886 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2887 // map it to the solid leaf
2888 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2894 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2897 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2900 int i, j, count, p, firstmarksurface, nummarksurfaces;
2901 size_t structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2903 if (sb->cursize % structsize)
2904 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2905 count = sb->cursize / structsize;
2906 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2908 loadmodel->brush.data_leafs = out;
2909 loadmodel->brush.num_leafs = count;
2910 // get visleafs from the submodel data
2911 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2912 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2913 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2914 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2916 // FIXME: this function could really benefit from some error checking
2917 for ( i=0 ; i<count ; i++, out++)
2919 out->contents = MSG_ReadLittleLong(sb);
2921 out->clusterindex = i - 1;
2922 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2923 out->clusterindex = -1;
2925 p = MSG_ReadLittleLong(sb);
2926 // ignore visofs errors on leaf 0 (solid)
2927 if (p >= 0 && out->clusterindex >= 0)
2929 if (p >= loadmodel->brushq1.num_compressedpvs)
2930 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2932 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);
2935 if (loadmodel->brush.isbsp2rmqe)
2937 out->mins[0] = MSG_ReadLittleShort(sb);
2938 out->mins[1] = MSG_ReadLittleShort(sb);
2939 out->mins[2] = MSG_ReadLittleShort(sb);
2940 out->maxs[0] = MSG_ReadLittleShort(sb);
2941 out->maxs[1] = MSG_ReadLittleShort(sb);
2942 out->maxs[2] = MSG_ReadLittleShort(sb);
2944 firstmarksurface = MSG_ReadLittleLong(sb);
2945 nummarksurfaces = MSG_ReadLittleLong(sb);
2947 else if (loadmodel->brush.isbsp2)
2949 out->mins[0] = MSG_ReadLittleFloat(sb);
2950 out->mins[1] = MSG_ReadLittleFloat(sb);
2951 out->mins[2] = MSG_ReadLittleFloat(sb);
2952 out->maxs[0] = MSG_ReadLittleFloat(sb);
2953 out->maxs[1] = MSG_ReadLittleFloat(sb);
2954 out->maxs[2] = MSG_ReadLittleFloat(sb);
2956 firstmarksurface = MSG_ReadLittleLong(sb);
2957 nummarksurfaces = MSG_ReadLittleLong(sb);
2961 out->mins[0] = MSG_ReadLittleShort(sb);
2962 out->mins[1] = MSG_ReadLittleShort(sb);
2963 out->mins[2] = MSG_ReadLittleShort(sb);
2964 out->maxs[0] = MSG_ReadLittleShort(sb);
2965 out->maxs[1] = MSG_ReadLittleShort(sb);
2966 out->maxs[2] = MSG_ReadLittleShort(sb);
2968 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2969 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2972 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2974 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2975 out->numleafsurfaces = nummarksurfaces;
2979 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2980 out->firstleafsurface = NULL;
2981 out->numleafsurfaces = 0;
2984 for (j = 0;j < 4;j++)
2985 out->ambient_sound_level[j] = MSG_ReadByte(sb);
2989 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2993 const unsigned char *pvs;
2994 // if there's no vis data, assume supported (because everything is visible all the time)
2995 if (!loadmodel->brush.data_pvsclusters)
2997 // check all liquid leafs to see if they can see into empty leafs, if any
2998 // can we can assume this map supports r_wateralpha
2999 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3001 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3003 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3004 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3005 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3012 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3017 size_t structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3019 if (sb->cursize % structsize)
3020 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3021 count = sb->cursize / structsize;
3022 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3024 loadmodel->brushq1.clipnodes = out;
3025 loadmodel->brushq1.numclipnodes = count;
3027 for (i = 1; i < MAX_MAP_HULLS; i++)
3029 hull = &loadmodel->brushq1.hulls[i];
3030 hull->clipnodes = out;
3031 hull->firstclipnode = 0;
3032 hull->lastclipnode = count-1;
3033 hull->planes = loadmodel->brush.data_planes;
3034 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3035 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3036 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3037 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3038 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3039 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3040 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3043 for (i=0 ; i<count ; i++, out++)
3045 out->planenum = MSG_ReadLittleLong(sb);
3046 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3047 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3048 if (loadmodel->brush.isbsp2)
3050 out->children[0] = MSG_ReadLittleLong(sb);
3051 out->children[1] = MSG_ReadLittleLong(sb);
3052 if (out->children[0] >= count)
3053 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3054 if (out->children[1] >= count)
3055 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3059 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3060 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3061 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3062 if (out->children[0] >= count)
3063 out->children[0] -= 65536;
3064 if (out->children[1] >= count)
3065 out->children[1] -= 65536;
3070 //Duplicate the drawing hull structure as a clipping hull
3071 static void Mod_Q1BSP_MakeHull0(void)
3078 hull = &loadmodel->brushq1.hulls[0];
3080 in = loadmodel->brush.data_nodes;
3081 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3083 hull->clipnodes = out;
3084 hull->firstclipnode = 0;
3085 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3086 hull->planes = loadmodel->brush.data_planes;
3088 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3090 out->planenum = in->plane - loadmodel->brush.data_planes;
3091 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3092 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3096 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3099 size_t structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3101 if (sb->cursize % structsize)
3102 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3103 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3104 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3106 if (loadmodel->brush.isbsp2)
3108 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3110 j = MSG_ReadLittleLong(sb);
3111 if (j < 0 || j >= loadmodel->num_surfaces)
3112 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3113 loadmodel->brush.data_leafsurfaces[i] = j;
3118 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3120 j = (unsigned short) MSG_ReadLittleShort(sb);
3121 if (j >= loadmodel->num_surfaces)
3122 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3123 loadmodel->brush.data_leafsurfaces[i] = j;
3128 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3131 size_t structsize = 4;
3133 if (sb->cursize % structsize)
3134 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3135 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3136 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3138 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3139 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3143 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3147 size_t structsize = 20;
3149 if (sb->cursize % structsize)
3150 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3151 loadmodel->brush.num_planes = sb->cursize / structsize;
3152 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3154 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3156 out->normal[0] = MSG_ReadLittleFloat(sb);
3157 out->normal[1] = MSG_ReadLittleFloat(sb);
3158 out->normal[2] = MSG_ReadLittleFloat(sb);
3159 out->dist = MSG_ReadLittleFloat(sb);
3160 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3165 static void Mod_Q1BSP_LoadMapBrushes(void)
3169 int submodel, numbrushes;
3170 qboolean firstbrush;
3171 char *text, *maptext;
3172 char mapfilename[MAX_QPATH];
3173 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3174 strlcat (mapfilename, ".map", sizeof (mapfilename));
3175 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3179 if (!COM_ParseToken_Simple(&data, false, false, true))
3184 if (!COM_ParseToken_Simple(&data, false, false, true))
3186 if (com_token[0] != '{')
3192 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3195 if (!COM_ParseToken_Simple(&data, false, false, true))
3197 if (com_token[0] == '}')
3198 break; // end of entity
3199 if (com_token[0] == '{')
3206 if (submodel > loadmodel->brush.numsubmodels)
3208 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3212 model = loadmodel->brush.submodels[submodel];
3219 if (!COM_ParseToken_Simple(&data, false, false, true))
3221 if (com_token[0] == '}')
3222 break; // end of brush
3223 // each brush face should be this format:
3224 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3225 // FIXME: support hl .map format
3226 for (pointnum = 0;pointnum < 3;pointnum++)
3228 COM_ParseToken_Simple(&data, false, false, true);
3229 for (componentnum = 0;componentnum < 3;componentnum++)
3231 COM_ParseToken_Simple(&data, false, false, true);
3232 point[pointnum][componentnum] = atof(com_token);
3234 COM_ParseToken_Simple(&data, false, false, true);
3236 COM_ParseToken_Simple(&data, false, false, true);
3237 strlcpy(facetexture, com_token, sizeof(facetexture));
3238 COM_ParseToken_Simple(&data, false, false, true);
3239 //scroll_s = atof(com_token);
3240 COM_ParseToken_Simple(&data, false, false, true);
3241 //scroll_t = atof(com_token);
3242 COM_ParseToken_Simple(&data, false, false, true);
3243 //rotate = atof(com_token);
3244 COM_ParseToken_Simple(&data, false, false, true);
3245 //scale_s = atof(com_token);
3246 COM_ParseToken_Simple(&data, false, false, true);
3247 //scale_t = atof(com_token);
3248 TriangleNormal(point[0], point[1], point[2], planenormal);
3249 VectorNormalizeDouble(planenormal);
3250 planedist = DotProduct(point[0], planenormal);
3251 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3261 #define MAX_PORTALPOINTS 64
3263 typedef struct portal_s
3266 mnode_t *nodes[2]; // [0] = front side of plane
3267 struct portal_s *next[2];
3269 double points[3*MAX_PORTALPOINTS];
3270 struct portal_s *chain; // all portals are linked into a list
3274 static memexpandablearray_t portalarray;
3276 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3278 // process only nodes (leafs already had their box calculated)
3282 // calculate children first
3283 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3284 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3286 // make combined bounding box from children
3287 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3288 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3289 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3290 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3291 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3292 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3295 static void Mod_Q1BSP_FinalizePortals(void)
3297 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3301 mleaf_t *leaf, *endleaf;
3303 // tally up portal and point counts and recalculate bounding boxes for all
3304 // leafs (because qbsp is very sloppy)
3305 leaf = loadmodel->brush.data_leafs;
3306 endleaf = leaf + loadmodel->brush.num_leafs;
3307 if (mod_recalculatenodeboxes.integer)
3309 for (;leaf < endleaf;leaf++)
3311 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3312 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3317 for (portalindex = 0;portalindex < portalrange;portalindex++)
3319 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3322 // note: this check must match the one below or it will usually corrupt memory
3323 // 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
3324 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3327 numpoints += p->numpoints * 2;
3330 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3331 loadmodel->brush.num_portals = numportals;
3332 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3333 loadmodel->brush.num_portalpoints = numpoints;
3334 // clear all leaf portal chains
3335 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3336 loadmodel->brush.data_leafs[i].portals = NULL;
3337 // process all portals in the global portal chain, while freeing them
3338 portal = loadmodel->brush.data_portals;
3339 point = loadmodel->brush.data_portalpoints;
3340 for (portalindex = 0;portalindex < portalrange;portalindex++)
3342 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3345 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3347 // note: this check must match the one above or it will usually corrupt memory
3348 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3349 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3351 // first make the back to front portal(forward portal)
3352 portal->points = point;
3353 portal->numpoints = p->numpoints;
3354 portal->plane.dist = p->plane.dist;
3355 VectorCopy(p->plane.normal, portal->plane.normal);
3356 portal->here = (mleaf_t *)p->nodes[1];
3357 portal->past = (mleaf_t *)p->nodes[0];
3359 for (j = 0;j < portal->numpoints;j++)
3361 VectorCopy(p->points + j*3, point->position);
3364 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3365 PlaneClassify(&portal->plane);
3367 // link into leaf's portal chain
3368 portal->next = portal->here->portals;
3369 portal->here->portals = portal;
3371 // advance to next portal
3374 // then make the front to back portal(backward portal)
3375 portal->points = point;
3376 portal->numpoints = p->numpoints;
3377 portal->plane.dist = -p->plane.dist;
3378 VectorNegate(p->plane.normal, portal->plane.normal);
3379 portal->here = (mleaf_t *)p->nodes[0];
3380 portal->past = (mleaf_t *)p->nodes[1];
3382 for (j = portal->numpoints - 1;j >= 0;j--)
3384 VectorCopy(p->points + j*3, point->position);
3387 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3388 PlaneClassify(&portal->plane);
3390 // link into leaf's portal chain
3391 portal->next = portal->here->portals;
3392 portal->here->portals = portal;
3394 // advance to next portal
3397 // add the portal's polygon points to the leaf bounding boxes
3398 if (mod_recalculatenodeboxes.integer)
3400 for (i = 0;i < 2;i++)
3402 leaf = (mleaf_t *)p->nodes[i];
3403 for (j = 0;j < p->numpoints;j++)
3405 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3406 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3407 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3408 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3409 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3410 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3416 // now recalculate the node bounding boxes from the leafs
3417 if (mod_recalculatenodeboxes.integer)
3418 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3426 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3429 Host_Error("AddPortalToNodes: NULL front node");
3431 Host_Error("AddPortalToNodes: NULL back node");
3432 if (p->nodes[0] || p->nodes[1])
3433 Host_Error("AddPortalToNodes: already included");
3434 // 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
3436 p->nodes[0] = front;
3437 p->next[0] = (portal_t *)front->portals;
3438 front->portals = (mportal_t *)p;
3441 p->next[1] = (portal_t *)back->portals;
3442 back->portals = (mportal_t *)p;
3447 RemovePortalFromNode
3450 static void RemovePortalFromNodes(portal_t *portal)
3454 void **portalpointer;
3456 for (i = 0;i < 2;i++)
3458 node = portal->nodes[i];
3460 portalpointer = (void **) &node->portals;
3463 t = (portal_t *)*portalpointer;
3465 Host_Error("RemovePortalFromNodes: portal not in leaf");
3469 if (portal->nodes[0] == node)
3471 *portalpointer = portal->next[0];
3472 portal->nodes[0] = NULL;
3474 else if (portal->nodes[1] == node)
3476 *portalpointer = portal->next[1];
3477 portal->nodes[1] = NULL;
3480 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3484 if (t->nodes[0] == node)
3485 portalpointer = (void **) &t->next[0];
3486 else if (t->nodes[1] == node)
3487 portalpointer = (void **) &t->next[1];
3489 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3494 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3495 static double *portalpointsbuffer;
3496 static int portalpointsbufferoffset;
3497 static int portalpointsbuffersize;
3498 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3501 mnode_t *front, *back, *other_node;
3502 mplane_t clipplane, *plane;
3503 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3504 int numfrontpoints, numbackpoints;
3505 double *frontpoints, *backpoints;
3507 // if a leaf, we're done
3511 // get some space for our clipping operations to use
3512 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3514 portalpointsbuffersize = portalpointsbufferoffset * 2;
3515 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3517 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3518 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3519 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3520 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3522 plane = node->plane;
3524 front = node->children[0];
3525 back = node->children[1];
3527 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3529 // create the new portal by generating a polygon for the node plane,
3530 // and clipping it by all of the other portals(which came from nodes above this one)
3531 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3532 nodeportal->plane = *plane;
3534 // 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)
3535 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);
3536 nodeportal->numpoints = 4;
3537 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3538 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3540 clipplane = portal->plane;
3541 if (portal->nodes[0] == portal->nodes[1])
3542 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3543 if (portal->nodes[0] == node)
3545 else if (portal->nodes[1] == node)
3547 clipplane.dist = -clipplane.dist;
3548 VectorNegate(clipplane.normal, clipplane.normal);
3553 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3554 side = 0; // hush warning
3557 for (i = 0;i < nodeportal->numpoints*3;i++)
3558 frontpoints[i] = nodeportal->points[i];
3559 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);
3560 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3564 if (nodeportal->numpoints < 3)
3566 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3567 nodeportal->numpoints = 0;
3569 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3571 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3572 nodeportal->numpoints = 0;
3575 AddPortalToNodes(nodeportal, front, back);
3577 // split the portals of this node along this node's plane and assign them to the children of this node
3578 // (migrating the portals downward through the tree)
3579 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3581 if (portal->nodes[0] == portal->nodes[1])
3582 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3583 if (portal->nodes[0] == node)
3585 else if (portal->nodes[1] == node)
3589 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3590 side = 0; // hush warning
3592 nextportal = portal->next[side];
3593 if (!portal->numpoints)
3596 other_node = portal->nodes[!side];
3597 RemovePortalFromNodes(portal);
3599 // cut the portal into two portals, one on each side of the node plane
3600 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);
3602 if (!numfrontpoints)
3605 AddPortalToNodes(portal, back, other_node);
3607 AddPortalToNodes(portal, other_node, back);
3613 AddPortalToNodes(portal, front, other_node);
3615 AddPortalToNodes(portal, other_node, front);
3619 // the portal is split
3620 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3621 temp = splitportal->chain;
3622 *splitportal = *portal;
3623 splitportal->chain = temp;
3624 for (i = 0;i < numbackpoints*3;i++)
3625 splitportal->points[i] = backpoints[i];
3626 splitportal->numpoints = numbackpoints;
3627 for (i = 0;i < numfrontpoints*3;i++)
3628 portal->points[i] = frontpoints[i];
3629 portal->numpoints = numfrontpoints;
3633 AddPortalToNodes(portal, front, other_node);
3634 AddPortalToNodes(splitportal, back, other_node);
3638 AddPortalToNodes(portal, other_node, front);
3639 AddPortalToNodes(splitportal, other_node, back);
3643 Mod_Q1BSP_RecursiveNodePortals(front);
3644 Mod_Q1BSP_RecursiveNodePortals(back);
3646 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3649 static void Mod_Q1BSP_MakePortals(void)
3651 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3652 portalpointsbufferoffset = 0;
3653 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3654 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3655 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3656 Mem_Free(portalpointsbuffer);
3657 portalpointsbuffer = NULL;
3658 portalpointsbufferoffset = 0;
3659 portalpointsbuffersize = 0;
3660 Mod_Q1BSP_FinalizePortals();
3661 Mem_ExpandableArray_FreeArray(&portalarray);
3664 //Returns PVS data for a given point
3665 //(note: can return NULL)
3666 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3669 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3671 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3672 if (((mleaf_t *)node)->clusterindex >= 0)
3673 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3678 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)
3682 float d = PlaneDiff(org, node->plane);
3684 node = node->children[0];
3685 else if (d < -radius)
3686 node = node->children[1];
3689 // go down both sides
3690 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3691 node = node->children[1];
3694 // if this leaf is in a cluster, accumulate the pvs bits
3695 if (((mleaf_t *)node)->clusterindex >= 0)
3698 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3699 for (i = 0;i < pvsbytes;i++)
3700 pvsbuffer[i] |= pvs[i];
3704 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3705 //of the given point.
3706 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3708 int bytes = model->brush.num_pvsclusterbytes;
3709 bytes = min(bytes, pvsbufferlength);
3710 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3712 memset(pvsbuffer, 0xFF, bytes);
3716 memset(pvsbuffer, 0, bytes);
3717 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3721 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3726 VectorSubtract(inmaxs, inmins, size);
3727 if (cmodel->brush.ishlbsp)
3730 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3731 else if (size[0] <= 32)
3733 if (size[2] < 54) // pick the nearest of 36 or 72
3734 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3736 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3739 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3744 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3745 else if (size[0] <= 32)
3746 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3748 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3750 VectorCopy(inmins, outmins);
3751 VectorAdd(inmins, hull->clip_size, outmaxs);
3754 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3757 int numshadowmeshtriangles = 0;
3758 msurface_t *surface;
3759 if (cls.state == ca_dedicated)
3761 // make a single combined shadow mesh to allow optimized shadow volume creation
3763 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3765 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3766 numshadowmeshtriangles += surface->num_triangles;
3768 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3769 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3770 if (surface->num_triangles > 0)
3771 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));
3772 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3773 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3774 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3776 return numshadowmeshtriangles;
3779 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);
3781 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3784 sizebuf_t lumpsb[HEADER_LUMPS];
3786 float dist, modelyawradius, modelradius;
3787 msurface_t *surface;
3788 hullinfo_t hullinfo;
3789 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3790 model_brush_lightstyleinfo_t styleinfo[256];
3791 unsigned char *datapointer;
3794 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3796 mod->type = mod_brushq1;
3798 mod->brush.isbsp2 = false;
3799 mod->brush.ishlbsp = false;
3800 i = MSG_ReadLittleLong(&sb);
3804 mod->modeldatatypestring = "Q1BSP";
3807 mod->brush.ishlbsp = true;
3808 mod->modeldatatypestring = "HLBSP";
3810 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3811 mod->brush.isbsp2 = true;
3812 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3813 mod->modeldatatypestring = "Q1BSP2rmqe";
3815 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3816 mod->brush.isbsp2 = true;
3817 mod->modeldatatypestring = "Q1BSP2";
3820 mod->modeldatatypestring = "Unknown BSP";
3821 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);
3825 // fill in hull info
3826 VectorClear (hullinfo.hullsizes[0][0]);
3827 VectorClear (hullinfo.hullsizes[0][1]);
3828 if (mod->brush.ishlbsp)
3830 hullinfo.filehulls = 4;
3831 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3832 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3833 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3834 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3835 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3836 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3840 hullinfo.filehulls = 4;
3841 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3842 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3843 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3844 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3848 for (i = 0; i < HEADER_LUMPS; i++)
3850 int offset = MSG_ReadLittleLong(&sb);
3851 int size = MSG_ReadLittleLong(&sb);
3852 if (offset < 0 || offset + size > sb.cursize)
3853 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);
3854 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3857 mod->soundfromcenter = true;
3858 mod->TraceBox = Mod_Q1BSP_TraceBox;
3859 mod->TraceLine = Mod_Q1BSP_TraceLine;
3860 mod->TracePoint = Mod_Q1BSP_TracePoint;
3861 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3862 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3863 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3864 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3865 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3866 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3867 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3868 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3869 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3870 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3871 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3872 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3873 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3874 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3875 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3876 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3877 mod->Draw = R_Q1BSP_Draw;
3878 mod->DrawDepth = R_Q1BSP_DrawDepth;
3879 mod->DrawDebug = R_Q1BSP_DrawDebug;
3880 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3881 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3882 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3883 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3884 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3885 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3886 mod->DrawLight = R_Q1BSP_DrawLight;
3890 mod->brush.qw_md4sum = 0;
3891 mod->brush.qw_md4sum2 = 0;
3892 for (i = 0;i < HEADER_LUMPS;i++)
3895 if (i == LUMP_ENTITIES)
3897 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3898 mod->brush.qw_md4sum ^= LittleLong(temp);
3899 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3901 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3904 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3905 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3906 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3907 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3908 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3909 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3910 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3911 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3912 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3913 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3914 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3915 // load submodels before leafs because they contain the number of vis leafs
3916 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3917 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3918 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3919 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3921 for (i = 0; i < HEADER_LUMPS; i++)
3922 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3923 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3925 // check if the map supports transparent water rendering
3926 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3928 if (mod->brushq1.data_compressedpvs)
3929 Mem_Free(mod->brushq1.data_compressedpvs);
3930 mod->brushq1.data_compressedpvs = NULL;
3931 mod->brushq1.num_compressedpvs = 0;
3933 Mod_Q1BSP_MakeHull0();
3934 if (mod_bsp_portalize.integer)
3935 Mod_Q1BSP_MakePortals();
3937 mod->numframes = 2; // regular and alternate animation
3940 // make a single combined shadow mesh to allow optimized shadow volume creation
3941 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3943 if (loadmodel->brush.numsubmodels)
3944 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3946 // LordHavoc: to clear the fog around the original quake submodel code, I
3948 // first of all, some background info on the submodels:
3949 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3950 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3951 // now the weird for loop itself:
3952 // the loop functions in an odd way, on each iteration it sets up the
3953 // current 'mod' model (which despite the confusing code IS the model of
3954 // the number i), at the end of the loop it duplicates the model to become
3955 // the next submodel, and loops back to set up the new submodel.
3957 // LordHavoc: now the explanation of my sane way (which works identically):
3958 // set up the world model, then on each submodel copy from the world model
3959 // and set up the submodel with the respective model info.
3960 totalstylesurfaces = 0;
3962 for (i = 0;i < mod->brush.numsubmodels;i++)
3964 memset(stylecounts, 0, sizeof(stylecounts));
3965 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3967 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3968 for (j = 0;j < MAXLIGHTMAPS;j++)
3969 stylecounts[surface->lightmapinfo->styles[j]]++;
3971 for (k = 0;k < 255;k++)
3975 totalstylesurfaces += stylecounts[k];
3978 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3979 for (i = 0;i < mod->brush.numsubmodels;i++)
3981 // LordHavoc: this code was originally at the end of this loop, but
3982 // has been transformed to something more readable at the start here.
3987 // duplicate the basic information
3988 dpsnprintf(name, sizeof(name), "*%i", i);
3989 mod = Mod_FindName(name, loadmodel->name);
3990 // copy the base model to this one
3992 // rename the clone back to its proper name
3993 strlcpy(mod->name, name, sizeof(mod->name));
3994 mod->brush.parentmodel = loadmodel;
3995 // textures and memory belong to the main model
3996 mod->texturepool = NULL;
3997 mod->mempool = NULL;
3998 mod->brush.GetPVS = NULL;
3999 mod->brush.FatPVS = NULL;
4000 mod->brush.BoxTouchingPVS = NULL;
4001 mod->brush.BoxTouchingLeafPVS = NULL;
4002 mod->brush.BoxTouchingVisibleLeafs = NULL;
4003 mod->brush.FindBoxClusters = NULL;
4004 mod->brush.LightPoint = NULL;
4005 mod->brush.AmbientSoundLevelsForPoint = NULL;
4008 mod->brush.submodel = i;
4010 if (loadmodel->brush.submodels)
4011 loadmodel->brush.submodels[i] = mod;
4013 bm = &mod->brushq1.submodels[i];
4015 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4016 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4018 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4019 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4022 mod->firstmodelsurface = bm->firstface;
4023 mod->nummodelsurfaces = bm->numfaces;
4025 // set node/leaf parents for this submodel
4026 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4028 // make the model surface list (used by shadowing/lighting)
4029 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4030 Mod_MakeSortedSurfaces(mod);
4032 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4033 // (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)
4034 VectorCopy(bm->mins, mod->normalmins);
4035 VectorCopy(bm->maxs, mod->normalmaxs);
4036 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4037 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4038 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4039 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4040 modelradius = modelyawradius + modelradius * modelradius;
4041 modelyawradius = sqrt(modelyawradius);
4042 modelradius = sqrt(modelradius);
4043 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4044 mod->yawmins[2] = mod->normalmins[2];
4045 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4046 mod->yawmaxs[2] = mod->normalmaxs[2];
4047 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4048 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4049 mod->radius = modelradius;
4050 mod->radius2 = modelradius * modelradius;
4052 // this gets altered below if sky or water is used
4053 mod->DrawSky = NULL;
4054 mod->DrawAddWaterPlanes = NULL;
4056 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4057 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4058 if (mod->nummodelsurfaces)
4060 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4061 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4063 if (j < mod->nummodelsurfaces)
4064 mod->DrawSky = R_Q1BSP_DrawSky;
4066 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4067 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4069 if (j < mod->nummodelsurfaces)
4070 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4072 // build lightstyle update chains
4073 // (used to rapidly mark lightmapupdateflags on many surfaces
4074 // when d_lightstylevalue changes)
4075 memset(stylecounts, 0, sizeof(stylecounts));
4076 for (k = 0;k < mod->nummodelsurfaces;k++)
4078 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4079 for (j = 0;j < MAXLIGHTMAPS;j++)
4080 stylecounts[surface->lightmapinfo->styles[j]]++;
4082 mod->brushq1.num_lightstyles = 0;
4083 for (k = 0;k < 255;k++)
4087 styleinfo[mod->brushq1.num_lightstyles].style = k;
4088 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4089 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4090 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4091 remapstyles[k] = mod->brushq1.num_lightstyles;
4092 mod->brushq1.num_lightstyles++;
4095 for (k = 0;k < mod->nummodelsurfaces;k++)
4097 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4098 for (j = 0;j < MAXLIGHTMAPS;j++)
4100 if (surface->lightmapinfo->styles[j] != 255)
4102 int r = remapstyles[surface->lightmapinfo->styles[j]];
4103 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4107 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4108 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4112 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4113 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4115 //mod->brushq1.num_visleafs = bm->visleafs;
4117 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4118 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4120 if (mod_q1bsp_polygoncollisions.integer)
4122 mod->collision_bih = mod->render_bih;
4123 // point traces and contents checks still use the bsp tree
4124 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4125 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4126 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4127 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4130 // generate VBOs and other shared data before cloning submodels
4134 Mod_Q1BSP_LoadMapBrushes();
4135 //Mod_Q1BSP_ProcessLightList();
4139 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);
4142 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4146 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4153 in = (void *)(mod_base + l->fileofs);
4154 if (l->filelen % sizeof(*in))
4155 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4156 count = l->filelen / sizeof(*in);
4157 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4160 loadmodel->num = count;
4162 for (i = 0;i < count;i++, in++, out++)
4168 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4175 in = (void *)(mod_base + l->fileofs);
4176 if (l->filelen % sizeof(*in))
4177 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4178 count = l->filelen / sizeof(*in);
4179 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4182 loadmodel->num = count;
4184 for (i = 0;i < count;i++, in++, out++)
4190 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4197 in = (void *)(mod_base + l->fileofs);
4198 if (l->filelen % sizeof(*in))
4199 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4200 count = l->filelen / sizeof(*in);
4201 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4204 loadmodel->num = count;
4206 for (i = 0;i < count;i++, in++, out++)
4212 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4219 in = (void *)(mod_base + l->fileofs);
4220 if (l->filelen % sizeof(*in))
4221 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4222 count = l->filelen / sizeof(*in);
4223 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4226 loadmodel->num = count;
4228 for (i = 0;i < count;i++, in++, out++)
4234 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4241 in = (void *)(mod_base + l->fileofs);
4242 if (l->filelen % sizeof(*in))
4243 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4244 count = l->filelen / sizeof(*in);
4245 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4248 loadmodel->num = count;
4250 for (i = 0;i < count;i++, in++, out++)
4256 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4263 in = (void *)(mod_base + l->fileofs);
4264 if (l->filelen % sizeof(*in))
4265 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4266 count = l->filelen / sizeof(*in);
4267 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4270 loadmodel->num = count;
4272 for (i = 0;i < count;i++, in++, out++)
4278 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4285 in = (void *)(mod_base + l->fileofs);
4286 if (l->filelen % sizeof(*in))
4287 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4288 count = l->filelen / sizeof(*in);
4289 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4292 loadmodel->num = count;
4294 for (i = 0;i < count;i++, in++, out++)
4300 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4307 in = (void *)(mod_base + l->fileofs);
4308 if (l->filelen % sizeof(*in))
4309 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4310 count = l->filelen / sizeof(*in);
4311 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4314 loadmodel->num = count;
4316 for (i = 0;i < count;i++, in++, out++)
4322 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4329 in = (void *)(mod_base + l->fileofs);
4330 if (l->filelen % sizeof(*in))
4331 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4332 count = l->filelen / sizeof(*in);
4333 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4336 loadmodel->num = count;
4338 for (i = 0;i < count;i++, in++, out++)
4344 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4351 in = (void *)(mod_base + l->fileofs);
4352 if (l->filelen % sizeof(*in))
4353 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4354 count = l->filelen / sizeof(*in);
4355 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4358 loadmodel->num = count;
4360 for (i = 0;i < count;i++, in++, out++)
4366 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4373 in = (void *)(mod_base + l->fileofs);
4374 if (l->filelen % sizeof(*in))
4375 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4376 count = l->filelen / sizeof(*in);
4377 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4380 loadmodel->num = count;
4382 for (i = 0;i < count;i++, in++, out++)
4388 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4395 in = (void *)(mod_base + l->fileofs);
4396 if (l->filelen % sizeof(*in))
4397 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4398 count = l->filelen / sizeof(*in);
4399 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4402 loadmodel->num = count;
4404 for (i = 0;i < count;i++, in++, out++)
4410 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4417 in = (void *)(mod_base + l->fileofs);
4418 if (l->filelen % sizeof(*in))
4419 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4420 count = l->filelen / sizeof(*in);
4421 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4424 loadmodel->num = count;
4426 for (i = 0;i < count;i++, in++, out++)
4432 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4439 in = (void *)(mod_base + l->fileofs);
4440 if (l->filelen % sizeof(*in))
4441 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4442 count = l->filelen / sizeof(*in);
4443 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4446 loadmodel->num = count;
4448 for (i = 0;i < count;i++, in++, out++)
4454 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4461 in = (void *)(mod_base + l->fileofs);
4462 if (l->filelen % sizeof(*in))
4463 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4464 count = l->filelen / sizeof(*in);
4465 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4468 loadmodel->num = count;
4470 for (i = 0;i < count;i++, in++, out++)
4476 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4483 in = (void *)(mod_base + l->fileofs);
4484 if (l->filelen % sizeof(*in))
4485 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4486 count = l->filelen / sizeof(*in);
4487 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4490 loadmodel->num = count;
4492 for (i = 0;i < count;i++, in++, out++)
4498 static void Mod_Q2BSP_LoadModels(lump_t *l)
4505 in = (void *)(mod_base + l->fileofs);
4506 if (l->filelen % sizeof(*in))
4507 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4508 count = l->filelen / sizeof(*in);
4509 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4512 loadmodel->num = count;
4514 for (i = 0;i < count;i++, in++, out++)
4520 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4523 q2dheader_t *header;
4525 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4527 mod->modeldatatypestring = "Q2BSP";
4529 mod->type = mod_brushq2;
4531 header = (q2dheader_t *)buffer;
4533 i = LittleLong(header->version);
4534 if (i != Q2BSPVERSION)
4535 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4537 mod_base = (unsigned char *)header;
4539 // swap all the lumps
4540 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4541 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4543 mod->brush.qw_md4sum = 0;
4544 mod->brush.qw_md4sum2 = 0;
4545 for (i = 0;i < Q2HEADER_LUMPS;i++)
4547 if (i == Q2LUMP_ENTITIES)
4549 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4550 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4552 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4555 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4556 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4557 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4558 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4559 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4560 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4561 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4562 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4563 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4564 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4565 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4566 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4567 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4568 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4569 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4570 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4571 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4572 // LordHavoc: must go last because this makes the submodels
4573 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4576 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4577 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4579 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4582 char key[128], value[MAX_INPUTLINE];
4584 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4585 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4586 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4589 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4590 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4591 loadmodel->brush.entities[l->filelen] = 0;
4592 data = loadmodel->brush.entities;
4593 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4594 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4595 loadmodel->brushq3.deluxemapping = false;
4596 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4600 if (!COM_ParseToken_Simple(&data, false, false, true))
4602 if (com_token[0] == '}')
4603 break; // end of worldspawn
4604 if (com_token[0] == '_')
4605 strlcpy(key, com_token + 1, sizeof(key));
4607 strlcpy(key, com_token, sizeof(key));
4608 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4609 key[strlen(key)-1] = 0;
4610 if (!COM_ParseToken_Simple(&data, false, false, true))
4612 strlcpy(value, com_token, sizeof(value));
4613 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4615 #if _MSC_VER >= 1400
4616 #define sscanf sscanf_s
4619 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4620 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4622 VectorSet(v, 64, 64, 128);
4623 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4624 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]);
4625 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4626 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4629 else if (!strcmp("deluxeMaps", key))
4631 if (!strcmp(com_token, "1"))
4633 loadmodel->brushq3.deluxemapping = true;
4634 loadmodel->brushq3.deluxemapping_modelspace = true;
4636 else if (!strcmp(com_token, "2"))
4638 loadmodel->brushq3.deluxemapping = true;
4639 loadmodel->brushq3.deluxemapping_modelspace = false;
4646 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4652 in = (q3dtexture_t *)(mod_base + l->fileofs);
4653 if (l->filelen % sizeof(*in))
4654 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4655 count = l->filelen / sizeof(*in);
4656 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4658 loadmodel->data_textures = out;
4659 loadmodel->num_textures = count;
4660 loadmodel->num_texturesperskin = loadmodel->num_textures;
4662 for (i = 0;i < count;i++)
4664 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4665 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4666 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4667 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4668 // restore the surfaceflags and supercontents
4669 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4670 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4674 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4680 in = (q3dplane_t *)(mod_base + l->fileofs);
4681 if (l->filelen % sizeof(*in))
4682 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4683 count = l->filelen / sizeof(*in);
4684 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4686 loadmodel->brush.data_planes = out;
4687 loadmodel->brush.num_planes = count;
4689 for (i = 0;i < count;i++, in++, out++)
4691 out->normal[0] = LittleFloat(in->normal[0]);
4692 out->normal[1] = LittleFloat(in->normal[1]);
4693 out->normal[2] = LittleFloat(in->normal[2]);
4694 out->dist = LittleFloat(in->dist);
4699 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4702 q3mbrushside_t *out;
4705 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4706 if (l->filelen % sizeof(*in))
4707 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4708 count = l->filelen / sizeof(*in);
4709 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4711 loadmodel->brush.data_brushsides = out;
4712 loadmodel->brush.num_brushsides = count;
4714 for (i = 0;i < count;i++, in++, out++)
4716 n = LittleLong(in->planeindex);
4717 if (n < 0 || n >= loadmodel->brush.num_planes)
4718 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4719 out->plane = loadmodel->brush.data_planes + n;
4720 n = LittleLong(in->textureindex);
4721 if (n < 0 || n >= loadmodel->num_textures)
4722 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4723 out->texture = loadmodel->data_textures + n;
4727 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4729 q3dbrushside_ig_t *in;
4730 q3mbrushside_t *out;
4733 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4734 if (l->filelen % sizeof(*in))
4735 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4736 count = l->filelen / sizeof(*in);
4737 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4739 loadmodel->brush.data_brushsides = out;
4740 loadmodel->brush.num_brushsides = count;
4742 for (i = 0;i < count;i++, in++, out++)
4744 n = LittleLong(in->planeindex);
4745 if (n < 0 || n >= loadmodel->brush.num_planes)
4746 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4747 out->plane = loadmodel->brush.data_planes + n;
4748 n = LittleLong(in->textureindex);
4749 if (n < 0 || n >= loadmodel->num_textures)
4750 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4751 out->texture = loadmodel->data_textures + n;
4755 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4759 int i, j, n, c, count, maxplanes, q3surfaceflags;
4760 colplanef_t *planes;
4762 in = (q3dbrush_t *)(mod_base + l->fileofs);
4763 if (l->filelen % sizeof(*in))
4764 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4765 count = l->filelen / sizeof(*in);
4766 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4768 loadmodel->brush.data_brushes = out;
4769 loadmodel->brush.num_brushes = count;
4774 for (i = 0;i < count;i++, in++, out++)
4776 n = LittleLong(in->firstbrushside);
4777 c = LittleLong(in->numbrushsides);
4778 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4779 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4780 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4781 out->numbrushsides = c;
4782 n = LittleLong(in->textureindex);
4783 if (n < 0 || n >= loadmodel->num_textures)
4784 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4785 out->texture = loadmodel->data_textures + n;
4787 // make a list of mplane_t structs to construct a colbrush from
4788 if (maxplanes < out->numbrushsides)
4790 maxplanes = out->numbrushsides;
4793 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4796 for (j = 0;j < out->numbrushsides;j++)
4798 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4799 planes[j].dist = out->firstbrushside[j].plane->dist;
4800 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4801 planes[j].texture = out->firstbrushside[j].texture;
4802 q3surfaceflags |= planes[j].q3surfaceflags;
4804 // make the colbrush from the planes
4805 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4807 // this whole loop can take a while (e.g. on redstarrepublic4)
4808 CL_KeepaliveMessage(false);
4814 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4820 in = (q3deffect_t *)(mod_base + l->fileofs);
4821 if (l->filelen % sizeof(*in))
4822 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4823 count = l->filelen / sizeof(*in);
4824 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4826 loadmodel->brushq3.data_effects = out;
4827 loadmodel->brushq3.num_effects = count;
4829 for (i = 0;i < count;i++, in++, out++)
4831 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4832 n = LittleLong(in->brushindex);
4833 if (n >= loadmodel->brush.num_brushes)
4835 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4838 out->brushindex = n;
4839 out->unknown = LittleLong(in->unknown);
4843 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4848 in = (q3dvertex_t *)(mod_base + l->fileofs);
4849 if (l->filelen % sizeof(*in))
4850 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4851 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4852 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4853 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4854 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4855 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4856 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4858 for (i = 0;i < count;i++, in++)
4860 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4861 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4862 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4863 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4864 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4865 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4866 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4867 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4868 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4869 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4870 // svector/tvector are calculated later in face loading
4871 if(mod_q3bsp_sRGBlightmaps.integer)
4873 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
4874 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
4875 // working like this may be odd, but matches q3map2 -gamma 2.2
4876 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4878 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4879 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4880 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4881 // we fix the brightness consistently via lightmapscale
4885 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
4886 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
4887 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
4892 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4894 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4895 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4896 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4900 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4901 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4902 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4905 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4906 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4907 loadmodel->lit = true;
4911 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4917 in = (int *)(mod_base + l->fileofs);
4918 if (l->filelen % sizeof(int[3]))
4919 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4920 count = l->filelen / sizeof(*in);
4922 if(!loadmodel->brushq3.num_vertices)
4925 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4926 loadmodel->brushq3.num_triangles = 0;
4930 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4931 loadmodel->brushq3.num_triangles = count / 3;
4932 loadmodel->brushq3.data_element3i = out;
4934 for (i = 0;i < count;i++, in++, out++)
4936 *out = LittleLong(*in);
4937 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4939 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4945 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4947 q3dlightmap_t *input_pointer;
4965 int mergedrowsxcolumns;
4970 unsigned char *mergedpixels;
4971 unsigned char *mergeddeluxepixels;
4972 unsigned char *mergebuf;
4973 char mapname[MAX_QPATH];
4975 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4978 // defaults for q3bsp
4985 loadmodel->brushq3.lightmapsize = 128;
4987 if (cls.state == ca_dedicated)
4990 if(mod_q3bsp_nolightmaps.integer)
4996 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4997 if (developer_loading.integer)
4998 Con_Printf("Using internal lightmaps\n");
4999 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5000 if (l->filelen % sizeof(*input_pointer))
5001 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5002 count = l->filelen / sizeof(*input_pointer);
5003 for(i = 0; i < count; ++i)
5004 inpixels[i] = input_pointer[i].rgb;
5008 // no internal lightmaps
5009 // try external lightmaps
5010 if (developer_loading.integer)
5011 Con_Printf("Using external lightmaps\n");
5012 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5013 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5017 // using EXTERNAL lightmaps instead
5018 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5020 Mem_Free(inpixels[0]);
5021 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5031 for(count = 1; ; ++count)
5033 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5034 if(!inpixels[count])
5035 break; // we got all of them
5036 if(image_width != size || image_height != size)
5038 Mem_Free(inpixels[count]);
5039 inpixels[count] = NULL;
5040 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);
5046 loadmodel->brushq3.lightmapsize = size;
5047 loadmodel->brushq3.num_originallightmaps = count;
5049 // now check the surfaces to see if any of them index an odd numbered
5050 // lightmap, if so this is not a deluxemapped bsp file
5052 // also check what lightmaps are actually used, because q3map2 sometimes
5053 // (always?) makes an unused one at the end, which
5054 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5055 // reason when only one lightmap is used, which can throw off the
5056 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5057 // to see if the second lightmap is blank, if so it is not deluxemapped.
5058 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5059 // in Mod_Q3BSP_LoadEntities was failed
5060 if (!loadmodel->brushq3.deluxemapping)
5062 loadmodel->brushq3.deluxemapping = !(count & 1);
5063 loadmodel->brushq3.deluxemapping_modelspace = true;
5065 if (loadmodel->brushq3.deluxemapping)
5067 int facecount = faceslump->filelen / sizeof(q3dface_t);
5068 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5069 for (i = 0;i < facecount;i++)
5071 j = LittleLong(faces[i].lightmapindex);
5074 endlightmap = max(endlightmap, j + 1);
5075 if ((j & 1) || j + 1 >= count)
5077 loadmodel->brushq3.deluxemapping = false;
5084 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5085 // reason when only one lightmap is used, which can throw off the
5086 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5087 // to see if the second lightmap is blank, if so it is not deluxemapped.
5089 // further research has shown q3map2 sometimes creates a deluxemap and two
5090 // blank lightmaps, which must be handled properly as well
5091 if (endlightmap == 1 && count > 1)
5094 for (i = 0;i < size*size;i++)
5096 if (c[bytesperpixel*i + rgbmap[0]])
5098 if (c[bytesperpixel*i + rgbmap[1]])
5100 if (c[bytesperpixel*i + rgbmap[2]])
5105 // all pixels in the unused lightmap were black...
5106 loadmodel->brushq3.deluxemapping = false;
5111 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5113 // figure out what the most reasonable merge power is within limits
5115 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5116 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5118 // figure out how big the merged texture has to be
5119 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5120 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5121 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5123 mergedwidth = mergegoal;
5124 mergedheight = mergegoal;
5125 // choose non-square size (2x1 aspect) if only half the space is used;
5126 // this really only happens when the entire set fits in one texture, if
5127 // there are multiple textures, we don't worry about shrinking the last
5128 // one to fit, because the driver prefers the same texture size on
5129 // consecutive draw calls...
5130 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5133 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5134 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5135 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5136 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5137 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5138 loadmodel->brushq3.num_lightmapmergedheightpower++;
5139 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5141 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5142 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5143 powerxy = powerx+powery;
5144 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5146 mergedcolumns = 1 << powerx;
5147 mergedrows = 1 << powery;
5148 mergedrowsxcolumns = 1 << powerxy;
5150 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5151 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5152 if (loadmodel->brushq3.deluxemapping)
5153 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5155 // allocate a texture pool if we need it
5156 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5157 loadmodel->texturepool = R_AllocTexturePool();
5159 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5160 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5161 for (i = 0;i < count;i++)
5163 // figure out which merged lightmap texture this fits into
5164 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5165 lightmapindex = i >> powerdxy;
5167 // choose the destination address
5168 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5169 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5170 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5171 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);
5173 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5174 for (j = 0;j < size;j++)
5175 for (k = 0;k < size;k++)
5177 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5178 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5179 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5180 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5183 // upload texture if this was the last tile being written to the texture
5184 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5186 if (loadmodel->brushq3.deluxemapping && (i & 1))
5187 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);
5190 if(mod_q3bsp_sRGBlightmaps.integer)
5193 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5195 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5196 // we fix the brightness consistently via lightmapscale
5199 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5200 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);
5204 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5205 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5206 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);
5212 if (mergeddeluxepixels)
5213 Mem_Free(mergeddeluxepixels);
5214 Mem_Free(mergedpixels);
5217 for(i = 0; i < count; ++i)
5218 Mem_Free(inpixels[i]);
5222 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5227 *collisionstride = stride;
5230 cnt = (num_triangles + stride - 1) / stride;
5231 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5232 for(j = 0; j < cnt; ++j)
5234 mins = &((*collisionbbox6f)[6 * j + 0]);
5235 maxs = &((*collisionbbox6f)[6 * j + 3]);
5236 for(k = 0; k < stride; ++k)
5238 tri = j * stride + k;
5239 if(tri >= num_triangles)
5241 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5242 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5243 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5244 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5245 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5246 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5247 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5248 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5249 if(vert[0] < mins[0]) mins[0] = vert[0];
5250 if(vert[1] < mins[1]) mins[1] = vert[1];
5251 if(vert[2] < mins[2]) mins[2] = vert[2];
5252 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5253 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5254 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5255 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5256 if(vert[0] < mins[0]) mins[0] = vert[0];
5257 if(vert[1] < mins[1]) mins[1] = vert[1];
5258 if(vert[2] < mins[2]) mins[2] = vert[2];
5259 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5260 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5261 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5266 *collisionbbox6f = NULL;
5269 typedef struct patchtess_s
5273 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5276 float *originalvertex3f;
5279 #define PATCHTESS_SAME_LODGROUP(a,b) \
5281 (a).lodgroup[0] == (b).lodgroup[0] && \
5282 (a).lodgroup[1] == (b).lodgroup[1] && \
5283 (a).lodgroup[2] == (b).lodgroup[2] && \
5284 (a).lodgroup[3] == (b).lodgroup[3] && \
5285 (a).lodgroup[4] == (b).lodgroup[4] && \
5286 (a).lodgroup[5] == (b).lodgroup[5] \
5289 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5291 q3dface_t *in, *oldin;
5292 msurface_t *out, *oldout;
5293 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;
5294 float lightmaptcbase[2], lightmaptcscale[2];
5295 //int *originalelement3i;
5296 //int *originalneighbor3i;
5297 float *originalvertex3f;
5298 //float *originalsvector3f;
5299 //float *originaltvector3f;
5300 float *originalnormal3f;
5301 float *originalcolor4f;
5302 float *originaltexcoordtexture2f;
5303 float *originaltexcoordlightmap2f;
5304 float *surfacecollisionvertex3f;
5305 int *surfacecollisionelement3i;
5307 patchtess_t *patchtess = NULL;
5308 int patchtesscount = 0;
5311 in = (q3dface_t *)(mod_base + l->fileofs);
5312 if (l->filelen % sizeof(*in))
5313 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5314 count = l->filelen / sizeof(*in);
5315 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5317 loadmodel->data_surfaces = out;
5318 loadmodel->num_surfaces = count;
5321 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5329 for (;i < count;i++, in++, out++)
5331 // check face type first
5332 type = LittleLong(in->type);
5333 if (type != Q3FACETYPE_FLAT
5334 && type != Q3FACETYPE_PATCH
5335 && type != Q3FACETYPE_MESH
5336 && type != Q3FACETYPE_FLARE)
5338 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5342 n = LittleLong(in->textureindex);
5343 if (n < 0 || n >= loadmodel->num_textures)
5345 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5348 out->texture = loadmodel->data_textures + n;
5349 n = LittleLong(in->effectindex);
5350 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5352 if (developer_extra.integer)
5353 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5359 out->effect = loadmodel->brushq3.data_effects + n;
5361 if (cls.state != ca_dedicated)
5363 out->lightmaptexture = NULL;
5364 out->deluxemaptexture = r_texture_blanknormalmap;
5365 n = LittleLong(in->lightmapindex);
5368 else if (n >= loadmodel->brushq3.num_originallightmaps)
5370 if(loadmodel->brushq3.num_originallightmaps != 0)
5371 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5376 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5377 if (loadmodel->brushq3.deluxemapping)
5378 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5379 loadmodel->lit = true;
5383 firstvertex = LittleLong(in->firstvertex);
5384 numvertices = LittleLong(in->numvertices);
5385 firstelement = LittleLong(in->firstelement);
5386 numtriangles = LittleLong(in->numelements) / 3;
5387 if (numtriangles * 3 != LittleLong(in->numelements))
5389 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));
5392 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5394 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);
5397 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5399 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);
5404 case Q3FACETYPE_FLAT:
5405 case Q3FACETYPE_MESH:
5406 // no processing necessary
5408 case Q3FACETYPE_PATCH:
5409 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5410 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5411 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))
5413 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5416 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5418 // convert patch to Q3FACETYPE_MESH
5419 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5420 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5421 // bound to user settings
5422 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5423 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5424 // bound to sanity settings
5425 xtess = bound(0, xtess, 1024);
5426 ytess = bound(0, ytess, 1024);
5428 // lower quality collision patches! Same procedure as before, but different cvars
5429 // convert patch to Q3FACETYPE_MESH
5430 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5431 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5432 // bound to user settings
5433 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5434 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5435 // bound to sanity settings
5436 cxtess = bound(0, cxtess, 1024);
5437 cytess = bound(0, cytess, 1024);
5439 // store it for the LOD grouping step
5440 patchtess[patchtesscount].info.xsize = patchsize[0];
5441 patchtess[patchtesscount].info.ysize = patchsize[1];
5442 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5443 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5444 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5445 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5447 patchtess[patchtesscount].surface_id = i;
5448 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5449 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5450 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5451 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5452 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5453 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5454 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5457 case Q3FACETYPE_FLARE:
5458 if (developer_extra.integer)
5459 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5463 out->num_vertices = numvertices;
5464 out->num_triangles = numtriangles;
5465 meshvertices += out->num_vertices;
5466 meshtriangles += out->num_triangles;
5469 // Fix patches tesselations so that they make no seams
5473 for(i = 0; i < patchtesscount; ++i)
5475 for(j = i+1; j < patchtesscount; ++j)
5477 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5480 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5487 // Calculate resulting number of triangles
5488 collisionvertices = 0;
5489 collisiontriangles = 0;
5490 for(i = 0; i < patchtesscount; ++i)
5492 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5493 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5494 numvertices = finalwidth * finalheight;
5495 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5497 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5498 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5499 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5500 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5502 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5503 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5504 numvertices = finalwidth * finalheight;
5505 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5507 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5508 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5509 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5510 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5516 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5517 if (collisiontriangles)
5519 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5520 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5524 collisionvertices = 0;
5525 collisiontriangles = 0;
5526 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5528 if (out->num_vertices < 3 || out->num_triangles < 1)
5531 type = LittleLong(in->type);
5532 firstvertex = LittleLong(in->firstvertex);
5533 firstelement = LittleLong(in->firstelement);
5534 out->num_firstvertex = meshvertices;
5535 out->num_firsttriangle = meshtriangles;
5536 out->num_firstcollisiontriangle = collisiontriangles;
5539 case Q3FACETYPE_FLAT:
5540 case Q3FACETYPE_MESH:
5541 // no processing necessary, except for lightmap merging
5542 for (j = 0;j < out->num_vertices;j++)
5544 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5545 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5546 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5547 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5548 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5549 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5550 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5551 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5552 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5553 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5554 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5555 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5556 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5557 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5559 for (j = 0;j < out->num_triangles*3;j++)
5560 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5562 case Q3FACETYPE_PATCH:
5563 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5564 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5565 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5566 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5567 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5568 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5569 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5571 xtess = ytess = cxtess = cytess = -1;
5572 for(j = 0; j < patchtesscount; ++j)
5573 if(patchtess[j].surface_id == i)
5575 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5576 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5577 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5578 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5583 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5584 xtess = ytess = cxtess = cytess = 0;
5587 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5588 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5589 finalvertices = finalwidth * finalheight;
5590 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5591 type = Q3FACETYPE_MESH;
5592 // generate geometry
5593 // (note: normals are skipped because they get recalculated)
5594 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5595 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5596 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5597 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5598 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5599 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5601 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);
5603 if (developer_extra.integer)
5605 if (out->num_triangles < finaltriangles)
5606 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);
5608 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);
5610 // q3map does not put in collision brushes for curves... ugh
5611 // build the lower quality collision geometry
5612 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5613 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5614 finalvertices = finalwidth * finalheight;
5615 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5617 // legacy collision geometry implementation
5618 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5619 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5620 out->num_collisionvertices = finalvertices;
5621 out->num_collisiontriangles = finaltriangles;
5622 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5623 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5625 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5626 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5628 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5630 // now optimize the collision mesh by finding triangle bboxes...
5631 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5632 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);
5634 // store collision geometry for BIH collision tree
5635 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5636 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5637 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5638 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5639 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5641 // remove this once the legacy code is removed
5643 int nc = out->num_collisiontriangles;
5645 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5647 if(nc != out->num_collisiontriangles)
5649 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5654 if (developer_extra.integer)
5655 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);
5657 collisionvertices += finalvertices;
5658 collisiontriangles += out->num_collisiontriangles;
5663 meshvertices += out->num_vertices;
5664 meshtriangles += out->num_triangles;
5665 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5666 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)
5668 if (invalidelements)
5670 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);
5671 for (j = 0;j < out->num_triangles * 3;j++)
5673 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5674 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)
5675 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5679 // calculate a bounding box
5680 VectorClear(out->mins);
5681 VectorClear(out->maxs);
5682 if (out->num_vertices)
5684 if (cls.state != ca_dedicated && out->lightmaptexture)
5686 // figure out which part of the merged lightmap this fits into
5687 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5688 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5689 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5690 lightmapindex &= mergewidth * mergeheight - 1;
5691 lightmaptcscale[0] = 1.0f / mergewidth;
5692 lightmaptcscale[1] = 1.0f / mergeheight;
5693 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5694 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5695 // modify the lightmap texcoords to match this region of the merged lightmap
5696 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5698 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5699 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5702 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5703 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5704 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5706 out->mins[0] = min(out->mins[0], v[0]);
5707 out->maxs[0] = max(out->maxs[0], v[0]);
5708 out->mins[1] = min(out->mins[1], v[1]);
5709 out->maxs[1] = max(out->maxs[1], v[1]);
5710 out->mins[2] = min(out->mins[2], v[2]);
5711 out->maxs[2] = max(out->maxs[2], v[2]);
5713 out->mins[0] -= 1.0f;
5714 out->mins[1] -= 1.0f;
5715 out->mins[2] -= 1.0f;
5716 out->maxs[0] += 1.0f;
5717 out->maxs[1] += 1.0f;
5718 out->maxs[2] += 1.0f;
5720 // set lightmap styles for consistency with q1bsp
5721 //out->lightmapinfo->styles[0] = 0;
5722 //out->lightmapinfo->styles[1] = 255;
5723 //out->lightmapinfo->styles[2] = 255;
5724 //out->lightmapinfo->styles[3] = 255;
5729 for (;i < count;i++, out++)
5731 if(out->num_vertices && out->num_triangles)
5733 if(out->num_vertices == 0)
5735 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5736 if(out->num_triangles == 0)
5737 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5739 else if(out->num_triangles == 0)
5740 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)",
5741 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5742 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5743 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5746 // for per pixel lighting
5747 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);
5749 // generate ushort elements array if possible
5750 if (loadmodel->surfmesh.data_element3s)
5751 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5752 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5754 // free the no longer needed vertex data
5755 loadmodel->brushq3.num_vertices = 0;
5756 if (loadmodel->brushq3.data_vertex3f)
5757 Mem_Free(loadmodel->brushq3.data_vertex3f);
5758 loadmodel->brushq3.data_vertex3f = NULL;
5759 loadmodel->brushq3.data_normal3f = NULL;
5760 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5761 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5762 loadmodel->brushq3.data_color4f = NULL;
5763 // free the no longer needed triangle data
5764 loadmodel->brushq3.num_triangles = 0;
5765 if (loadmodel->brushq3.data_element3i)
5766 Mem_Free(loadmodel->brushq3.data_element3i);
5767 loadmodel->brushq3.data_element3i = NULL;
5770 Mem_Free(patchtess);
5773 static void Mod_Q3BSP_LoadModels(lump_t *l)
5777 int i, j, n, c, count;
5779 in = (q3dmodel_t *)(mod_base + l->fileofs);
5780 if (l->filelen % sizeof(*in))
5781 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5782 count = l->filelen / sizeof(*in);
5783 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5785 loadmodel->brushq3.data_models = out;
5786 loadmodel->brushq3.num_models = count;
5788 for (i = 0;i < count;i++, in++, out++)
5790 for (j = 0;j < 3;j++)
5792 out->mins[j] = LittleFloat(in->mins[j]);
5793 out->maxs[j] = LittleFloat(in->maxs[j]);
5795 n = LittleLong(in->firstface);
5796 c = LittleLong(in->numfaces);
5797 if (n < 0 || n + c > loadmodel->num_surfaces)
5798 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5801 n = LittleLong(in->firstbrush);
5802 c = LittleLong(in->numbrushes);
5803 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5804 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5805 out->firstbrush = n;
5806 out->numbrushes = c;
5810 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5816 in = (int *)(mod_base + l->fileofs);
5817 if (l->filelen % sizeof(*in))
5818 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5819 count = l->filelen / sizeof(*in);
5820 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5822 loadmodel->brush.data_leafbrushes = out;
5823 loadmodel->brush.num_leafbrushes = count;
5825 for (i = 0;i < count;i++, in++, out++)
5827 n = LittleLong(*in);
5828 if (n < 0 || n >= loadmodel->brush.num_brushes)
5829 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5834 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5840 in = (int *)(mod_base + l->fileofs);
5841 if (l->filelen % sizeof(*in))
5842 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5843 count = l->filelen / sizeof(*in);
5844 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5846 loadmodel->brush.data_leafsurfaces = out;
5847 loadmodel->brush.num_leafsurfaces = count;
5849 for (i = 0;i < count;i++, in++, out++)
5851 n = LittleLong(*in);
5852 if (n < 0 || n >= loadmodel->num_surfaces)
5853 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5858 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5862 int i, j, n, c, count;
5864 in = (q3dleaf_t *)(mod_base + l->fileofs);
5865 if (l->filelen % sizeof(*in))
5866 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5867 count = l->filelen / sizeof(*in);
5868 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5870 loadmodel->brush.data_leafs = out;
5871 loadmodel->brush.num_leafs = count;
5873 for (i = 0;i < count;i++, in++, out++)
5877 out->clusterindex = LittleLong(in->clusterindex);
5878 out->areaindex = LittleLong(in->areaindex);
5879 for (j = 0;j < 3;j++)
5881 // yes the mins/maxs are ints
5882 out->mins[j] = LittleLong(in->mins[j]) - 1;
5883 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5885 n = LittleLong(in->firstleafface);
5886 c = LittleLong(in->numleaffaces);
5887 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5888 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5889 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5890 out->numleafsurfaces = c;
5891 n = LittleLong(in->firstleafbrush);
5892 c = LittleLong(in->numleafbrushes);
5893 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5894 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5895 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5896 out->numleafbrushes = c;
5900 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5906 in = (q3dnode_t *)(mod_base + l->fileofs);
5907 if (l->filelen % sizeof(*in))
5908 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5909 count = l->filelen / sizeof(*in);
5911 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5912 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5914 loadmodel->brush.data_nodes = out;
5915 loadmodel->brush.num_nodes = count;
5917 for (i = 0;i < count;i++, in++, out++)
5920 n = LittleLong(in->planeindex);
5921 if (n < 0 || n >= loadmodel->brush.num_planes)
5922 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5923 out->plane = loadmodel->brush.data_planes + n;
5924 for (j = 0;j < 2;j++)
5926 n = LittleLong(in->childrenindex[j]);
5929 if (n >= loadmodel->brush.num_nodes)
5930 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5931 out->children[j] = loadmodel->brush.data_nodes + n;
5936 if (n >= loadmodel->brush.num_leafs)
5937 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5938 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5941 for (j = 0;j < 3;j++)
5943 // yes the mins/maxs are ints
5944 out->mins[j] = LittleLong(in->mins[j]) - 1;
5945 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5949 // set the parent pointers
5950 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5953 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5956 q3dlightgrid_t *out;
5960 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5961 if (l->filelen % sizeof(*in))
5962 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5963 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5964 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5965 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5966 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5967 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5968 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5969 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5970 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5971 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5972 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5973 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5974 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5975 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5976 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]);
5977 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]);
5979 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5982 if (l->filelen < count * (int)sizeof(*in))
5984 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]);
5985 return; // ignore the grid if we cannot understand it
5987 if (l->filelen != count * (int)sizeof(*in))
5988 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5989 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5990 loadmodel->brushq3.data_lightgrid = out;
5991 loadmodel->brushq3.num_lightgrid = count;
5992 // no swapping or validation necessary
5993 memcpy(out, in, count * (int)sizeof(*out));
5995 if(mod_q3bsp_sRGBlightmaps.integer)
5997 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5999 // we fix the brightness consistently via lightmapscale
6003 for(i = 0; i < count; ++i)
6005 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6006 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6007 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6008 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6009 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6010 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6016 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6018 for(i = 0; i < count; ++i)
6020 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6021 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6022 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6023 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6024 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6025 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6036 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6041 if (l->filelen == 0)
6044 // unvised maps often have cluster indices even without pvs, so check
6045 // leafs to find real number of clusters
6046 loadmodel->brush.num_pvsclusters = 1;
6047 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6048 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6051 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6052 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6053 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6054 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6058 in = (q3dpvs_t *)(mod_base + l->fileofs);
6060 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6062 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6063 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6064 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6065 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6066 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6067 if (l->filelen < totalchains + (int)sizeof(*in))
6068 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);
6070 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6071 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6074 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6076 int i, j, k, index[3];
6077 float transformed[3], blend1, blend2, blend, stylescale = 1;
6078 q3dlightgrid_t *a, *s;
6080 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6081 switch(vid.renderpath)
6083 case RENDERPATH_GL20:
6084 case RENDERPATH_D3D9:
6085 case RENDERPATH_D3D10:
6086 case RENDERPATH_D3D11:
6087 case RENDERPATH_SOFT:
6088 case RENDERPATH_GLES2:
6089 // LordHavoc: FIXME: is this true?
6090 stylescale = 1; // added while render
6092 case RENDERPATH_GL11:
6093 case RENDERPATH_GL13:
6094 case RENDERPATH_GLES1:
6095 stylescale = r_refdef.scene.rtlightstylevalue[0];
6099 if (!model->brushq3.num_lightgrid)
6101 ambientcolor[0] = stylescale;
6102 ambientcolor[1] = stylescale;
6103 ambientcolor[2] = stylescale;
6107 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6108 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6109 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6110 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6111 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6112 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6113 index[0] = (int)floor(transformed[0]);
6114 index[1] = (int)floor(transformed[1]);
6115 index[2] = (int)floor(transformed[2]);
6116 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6118 // now lerp the values
6119 VectorClear(diffusenormal);
6120 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6121 for (k = 0;k < 2;k++)
6123 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6124 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6126 for (j = 0;j < 2;j++)
6128 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6129 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6131 for (i = 0;i < 2;i++)
6133 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6134 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6136 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6137 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6138 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6139 // this uses the mod_md3_sin table because the values are
6140 // already in the 0-255 range, the 64+ bias fetches a cosine
6141 // instead of a sine value
6142 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6143 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6144 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6145 //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)));
6150 // normalize the light direction before turning
6151 VectorNormalize(diffusenormal);
6152 //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]);
6155 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6158 double midf, mid[3];
6164 // find the point distances
6165 mplane_t *plane = node->plane;
6166 if (plane->type < 3)
6168 t1 = p1[plane->type] - plane->dist;
6169 t2 = p2[plane->type] - plane->dist;
6173 t1 = DotProduct (plane->normal, p1) - plane->dist;
6174 t2 = DotProduct (plane->normal, p2) - plane->dist;
6181 node = node->children[1];
6190 node = node->children[0];
6196 midf = t1 / (t1 - t2);
6197 VectorLerp(p1, midf, p2, mid);
6199 // recurse both sides, front side first
6200 // return 2 if empty is followed by solid (hit something)
6201 // do not return 2 if both are solid or both empty,
6202 // or if start is solid and end is empty
6203 // as these degenerate cases usually indicate the eye is in solid and
6204 // should see the target point anyway
6205 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6208 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6213 return ((mleaf_t *)node)->clusterindex < 0;
6216 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6218 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6221 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6222 return trace.fraction == 1;
6226 double tracestart[3], traceend[3];
6227 VectorCopy(start, tracestart);
6228 VectorCopy(end, traceend);
6229 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6233 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)
6236 const bih_leaf_t *leaf;
6237 const bih_node_t *node;
6238 const colbrushf_t *brush;
6241 int nodestackpos = 0;
6242 int nodestack[1024];
6244 memset(trace, 0, sizeof(*trace));
6245 trace->fraction = 1;
6246 trace->realfraction = 1;
6247 trace->hitsupercontentsmask = hitsupercontentsmask;
6249 bih = &model->collision_bih;
6253 nodenum = bih->rootnode;
6254 nodestack[nodestackpos++] = nodenum;
6255 while (nodestackpos)
6257 nodenum = nodestack[--nodestackpos];
6258 node = bih->nodes + nodenum;
6260 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6263 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6265 axis = node->type - BIH_SPLITX;
6266 if (start[axis] >= node->frontmin)
6267 nodestack[nodestackpos++] = node->front;
6268 if (start[axis] <= node->backmax)
6269 nodestack[nodestackpos++] = node->back;
6271 else if (node->type == BIH_UNORDERED)
6273 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6275 leaf = bih->leafs + node->children[axis];
6277 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6283 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6284 Collision_TracePointBrushFloat(trace, start, brush);
6286 case BIH_COLLISIONTRIANGLE:
6287 // collision triangle - skipped because they have no volume
6289 case BIH_RENDERTRIANGLE:
6290 // render triangle - skipped because they have no volume
6298 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)
6300 const bih_leaf_t *leaf;
6301 const bih_node_t *node;
6302 const colbrushf_t *brush;
6304 const texture_t *texture;
6305 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6306 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6307 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6312 if (VectorCompare(start, end))
6314 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6318 nodenum = bih->rootnode;
6320 memset(trace, 0, sizeof(*trace));
6321 trace->fraction = 1;
6322 trace->realfraction = 1;
6323 trace->hitsupercontentsmask = hitsupercontentsmask;
6326 nodestackline[nodestackpos][0] = start[0];
6327 nodestackline[nodestackpos][1] = start[1];
6328 nodestackline[nodestackpos][2] = start[2];
6329 nodestackline[nodestackpos][3] = end[0];
6330 nodestackline[nodestackpos][4] = end[1];
6331 nodestackline[nodestackpos][5] = end[2];
6332 nodestack[nodestackpos++] = nodenum;
6333 while (nodestackpos)
6335 nodenum = nodestack[--nodestackpos];
6336 node = bih->nodes + nodenum;
6337 VectorCopy(nodestackline[nodestackpos], nodestart);
6338 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6339 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6340 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6341 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6342 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6343 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6344 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6345 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6347 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6349 // recurse children of the split
6350 axis = node->type - BIH_SPLITX;
6351 d1 = node->backmax - nodestart[axis];
6352 d2 = node->backmax - nodeend[axis];
6353 d3 = nodestart[axis] - node->frontmin;
6354 d4 = nodeend[axis] - node->frontmin;
6355 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6357 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;
6358 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;
6359 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;
6360 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6361 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;
6362 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;
6363 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;
6364 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6365 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;
6366 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;
6367 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;
6368 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6369 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6370 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6371 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6372 case 15: /* <<<< */ break;
6375 else if (node->type == BIH_UNORDERED)
6377 // calculate sweep bounds for this node
6378 // copy node bounds into local variables
6379 VectorCopy(node->mins, nodebigmins);
6380 VectorCopy(node->maxs, nodebigmaxs);
6381 // clip line to this node bounds
6382 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); }
6383 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); }
6384 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); }
6385 // some of the line intersected the enlarged node box
6386 // calculate sweep bounds for this node
6387 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6388 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6389 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6390 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6391 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6392 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6393 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6395 leaf = bih->leafs + node->children[axis];
6396 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6401 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6402 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6404 case BIH_COLLISIONTRIANGLE:
6405 if (!mod_q3bsp_curves_collisions.integer)
6407 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6408 texture = model->data_textures + leaf->textureindex;
6409 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);
6411 case BIH_RENDERTRIANGLE:
6412 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6413 texture = model->data_textures + leaf->textureindex;
6414 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);
6422 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)
6424 if (VectorCompare(start, end))
6426 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6429 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6432 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)
6435 const bih_leaf_t *leaf;
6436 const bih_node_t *node;
6437 const colbrushf_t *brush;
6439 const texture_t *texture;
6440 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6441 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6442 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6443 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6445 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6447 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6448 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6450 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6454 bih = &model->collision_bih;
6457 nodenum = bih->rootnode;
6459 // box trace, performed as brush trace
6460 memset(trace, 0, sizeof(*trace));
6461 trace->fraction = 1;
6462 trace->realfraction = 1;
6463 trace->hitsupercontentsmask = hitsupercontentsmask;
6465 // calculate tracebox-like parameters for efficient culling
6466 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6467 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6468 VectorSubtract(thisbrush_start->mins, start, startmins);
6469 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6470 VectorSubtract(thisbrush_end->mins, end, endmins);
6471 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6472 mins[0] = min(startmins[0], endmins[0]);
6473 mins[1] = min(startmins[1], endmins[1]);
6474 mins[2] = min(startmins[2], endmins[2]);
6475 maxs[0] = max(startmaxs[0], endmaxs[0]);
6476 maxs[1] = max(startmaxs[1], endmaxs[1]);
6477 maxs[2] = max(startmaxs[2], endmaxs[2]);
6480 nodestackline[nodestackpos][0] = start[0];
6481 nodestackline[nodestackpos][1] = start[1];
6482 nodestackline[nodestackpos][2] = start[2];
6483 nodestackline[nodestackpos][3] = end[0];
6484 nodestackline[nodestackpos][4] = end[1];
6485 nodestackline[nodestackpos][5] = end[2];
6486 nodestack[nodestackpos++] = nodenum;
6487 while (nodestackpos)
6489 nodenum = nodestack[--nodestackpos];
6490 node = bih->nodes + nodenum;
6491 VectorCopy(nodestackline[nodestackpos], nodestart);
6492 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6493 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
6494 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
6495 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
6496 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
6497 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
6498 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
6499 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6501 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6503 // recurse children of the split
6504 axis = node->type - BIH_SPLITX;
6505 d1 = node->backmax - nodestart[axis] - mins[axis];
6506 d2 = node->backmax - nodeend[axis] - mins[axis];
6507 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6508 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6509 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6511 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;
6512 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;
6513 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;
6514 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6515 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;
6516 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;
6517 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;
6518 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6519 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;
6520 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;
6521 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;
6522 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6523 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6524 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6525 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6526 case 15: /* <<<< */ break;
6529 else if (node->type == BIH_UNORDERED)
6531 // calculate sweep bounds for this node
6532 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6533 VectorSubtract(node->mins, maxs, nodebigmins);
6534 VectorSubtract(node->maxs, mins, nodebigmaxs);
6535 // clip line to this node bounds
6536 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); }
6537 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); }
6538 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); }
6539 // some of the line intersected the enlarged node box
6540 // calculate sweep bounds for this node
6541 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
6542 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
6543 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
6544 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
6545 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
6546 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
6547 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6549 leaf = bih->leafs + node->children[axis];
6550 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6555 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6556 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6558 case BIH_COLLISIONTRIANGLE:
6559 if (!mod_q3bsp_curves_collisions.integer)
6561 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6562 texture = model->data_textures + leaf->textureindex;
6563 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);
6565 case BIH_RENDERTRIANGLE:
6566 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6567 texture = model->data_textures + leaf->textureindex;
6568 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);
6576 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)
6578 colboxbrushf_t thisbrush_start, thisbrush_end;
6579 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6581 // box trace, performed as brush trace
6582 VectorAdd(start, boxmins, boxstartmins);
6583 VectorAdd(start, boxmaxs, boxstartmaxs);
6584 VectorAdd(end, boxmins, boxendmins);
6585 VectorAdd(end, boxmaxs, boxendmaxs);
6586 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6587 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6588 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6592 static int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6595 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6596 return trace.startsupercontents;
6599 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)
6602 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6604 int hitsupercontents;
6605 VectorSet(end, start[0], start[1], model->normalmins[2]);
6607 memset(trace, 0, sizeof(*trace));
6608 trace->fraction = 1;
6609 trace->realfraction = 1;
6610 trace->hitsupercontentsmask = hitsupercontentsmask;
6612 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6613 hitsupercontents = trace->hitsupercontents;
6614 memset(trace, 0, sizeof(*trace));
6615 trace->fraction = 1;
6616 trace->realfraction = 1;
6617 trace->hitsupercontentsmask = hitsupercontentsmask;
6618 trace->startsupercontents = hitsupercontents;
6622 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6625 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6628 VectorSet(end, start[0], start[1], model->normalmins[2]);
6629 memset(&trace, 0, sizeof(trace));
6631 trace.realfraction = 1;
6632 trace.hitsupercontentsmask = 0;
6633 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6634 return trace.hitsupercontents;
6640 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6645 // find which leaf the point is in
6647 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6648 // point trace the brushes
6649 leaf = (mleaf_t *)node;
6650 for (i = 0;i < leaf->numleafbrushes;i++)
6652 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6653 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6655 brush->markframe = markframe;
6656 Collision_TracePointBrushFloat(trace, point, brush);
6659 // can't do point traces on curves (they have no thickness)
6662 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)
6664 int i, startside, endside;
6665 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6667 msurface_t *surface;
6670 // walk the tree until we hit a leaf, recursing for any split cases
6674 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6676 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6677 node = node->children[1];
6679 // abort if this part of the bsp tree can not be hit by this trace
6680 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6682 plane = node->plane;
6683 // axial planes are much more common than non-axial, so an optimized
6684 // axial case pays off here
6685 if (plane->type < 3)
6687 dist1 = start[plane->type] - plane->dist;
6688 dist2 = end[plane->type] - plane->dist;
6692 dist1 = DotProduct(start, plane->normal) - plane->dist;
6693 dist2 = DotProduct(end, plane->normal) - plane->dist;
6695 startside = dist1 < 0;
6696 endside = dist2 < 0;
6697 if (startside == endside)
6699 // most of the time the line fragment is on one side of the plane
6700 node = node->children[startside];
6704 // line crosses node plane, split the line
6705 dist1 = PlaneDiff(linestart, plane);
6706 dist2 = PlaneDiff(lineend, plane);
6707 midfrac = dist1 / (dist1 - dist2);
6708 VectorLerp(linestart, midfrac, lineend, mid);
6709 // take the near side first
6710 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6711 // if we found an impact on the front side, don't waste time
6712 // exploring the far side
6713 if (midfrac <= trace->realfraction)
6714 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6719 // abort if this part of the bsp tree can not be hit by this trace
6720 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6723 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6724 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6725 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6726 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6727 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6728 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6729 // line trace the brushes
6730 leaf = (mleaf_t *)node;
6732 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6735 for (i = 0;i < leaf->numleafbrushes;i++)
6737 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6738 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6740 brush->markframe = markframe;
6741 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6744 // can't do point traces on curves (they have no thickness)
6745 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6747 // line trace the curves
6748 for (i = 0;i < leaf->numleafsurfaces;i++)
6750 surface = model->data_surfaces + leaf->firstleafsurface[i];
6751 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6753 surface->deprecatedq3collisionmarkframe = markframe;
6754 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);
6760 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)
6766 msurface_t *surface;
6768 float nodesegmentmins[3], nodesegmentmaxs[3];
6769 // walk the tree until we hit a leaf, recursing for any split cases
6773 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6775 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6776 node = node->children[1];
6778 // abort if this part of the bsp tree can not be hit by this trace
6779 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6781 plane = node->plane;
6782 // axial planes are much more common than non-axial, so an optimized
6783 // axial case pays off here
6784 if (plane->type < 3)
6786 // this is an axial plane, compare bounding box directly to it and
6787 // recurse sides accordingly
6788 // recurse down node sides
6789 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6790 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6791 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6792 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6796 // this is a non-axial plane, so check if the start and end boxes
6797 // are both on one side of the plane to handle 'diagonal' cases
6798 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6802 // segment crosses plane
6803 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6806 // if sides == 0 then the trace itself is bogus (Not A Number values),
6807 // in this case we simply pretend the trace hit nothing
6809 return; // ERROR: NAN bounding box!
6810 // take whichever side the segment box is on
6811 node = node->children[sides - 1];
6814 // abort if this part of the bsp tree can not be hit by this trace
6815 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6817 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6818 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6819 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6820 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6821 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6822 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6824 leaf = (mleaf_t *)node;
6826 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6829 for (i = 0;i < leaf->numleafbrushes;i++)
6831 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6832 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6834 brush->markframe = markframe;
6835 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6838 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6840 for (i = 0;i < leaf->numleafsurfaces;i++)
6842 surface = model->data_surfaces + leaf->firstleafsurface[i];
6843 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6845 surface->deprecatedq3collisionmarkframe = markframe;
6846 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);
6853 static int markframe = 0;
6855 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)
6859 memset(trace, 0, sizeof(*trace));
6860 trace->fraction = 1;
6861 trace->realfraction = 1;
6862 trace->hitsupercontentsmask = hitsupercontentsmask;
6863 if (mod_collision_bih.integer)
6864 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6865 else if (model->brush.submodel)
6867 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6868 if (brush->colbrushf)
6869 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6872 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6875 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)
6878 float segmentmins[3], segmentmaxs[3];
6879 msurface_t *surface;
6882 if (VectorCompare(start, end))
6884 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6888 memset(trace, 0, sizeof(*trace));
6889 trace->fraction = 1;
6890 trace->realfraction = 1;
6891 trace->hitsupercontentsmask = hitsupercontentsmask;
6892 segmentmins[0] = min(start[0], end[0]) - 1;
6893 segmentmins[1] = min(start[1], end[1]) - 1;
6894 segmentmins[2] = min(start[2], end[2]) - 1;
6895 segmentmaxs[0] = max(start[0], end[0]) + 1;
6896 segmentmaxs[1] = max(start[1], end[1]) + 1;
6897 segmentmaxs[2] = max(start[2], end[2]) + 1;
6898 if (mod_collision_bih.integer)
6899 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6900 else if (model->brush.submodel)
6902 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6903 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6904 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6905 if (mod_q3bsp_curves_collisions.integer)
6906 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6907 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6908 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);
6911 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6914 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)
6916 float segmentmins[3], segmentmaxs[3];
6918 msurface_t *surface;
6921 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6923 if (VectorCompare(start->mins, end->mins))
6924 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6926 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6930 // box trace, performed as brush trace
6931 memset(trace, 0, sizeof(*trace));
6932 trace->fraction = 1;
6933 trace->realfraction = 1;
6934 trace->hitsupercontentsmask = hitsupercontentsmask;
6935 segmentmins[0] = min(start->mins[0], end->mins[0]) - 1;
6936 segmentmins[1] = min(start->mins[1], end->mins[1]) - 1;
6937 segmentmins[2] = min(start->mins[2], end->mins[2]) - 1;
6938 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]) + 1;
6939 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]) + 1;
6940 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]) + 1;
6941 if (mod_collision_bih.integer)
6942 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6943 else if (model->brush.submodel)
6945 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6946 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6947 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6948 if (mod_q3bsp_curves_collisions.integer)
6949 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6950 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6951 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);
6954 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6957 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)
6959 colboxbrushf_t thisbrush_start, thisbrush_end;
6960 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6962 // box trace, performed as brush trace
6963 VectorAdd(start, boxmins, boxstartmins);
6964 VectorAdd(start, boxmaxs, boxstartmaxs);
6965 VectorAdd(end, boxmins, boxendmins);
6966 VectorAdd(end, boxmaxs, boxendmaxs);
6967 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6968 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6969 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6972 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6975 int supercontents = 0;
6977 if (mod_collision_bih.integer)
6979 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
6981 // test if the point is inside each brush
6982 else if (model->brush.submodel)
6984 // submodels are effectively one leaf
6985 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6986 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6987 supercontents |= brush->colbrushf->supercontents;
6991 mnode_t *node = model->brush.data_nodes;
6993 // find which leaf the point is in
6995 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6996 leaf = (mleaf_t *)node;
6997 // now check the brushes in the leaf
6998 for (i = 0;i < leaf->numleafbrushes;i++)
7000 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
7001 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
7002 supercontents |= brush->colbrushf->supercontents;
7005 return supercontents;
7008 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)
7010 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
7014 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
7022 int nummodelbrushes = model->nummodelbrushes;
7023 int nummodelsurfaces = model->nummodelsurfaces;
7025 const int *collisionelement3i;
7026 const float *collisionvertex3f;
7027 const int *renderelement3i;
7028 const float *rendervertex3f;
7029 bih_leaf_t *bihleafs;
7030 bih_node_t *bihnodes;
7032 int *temp_leafsortscratch;
7033 const msurface_t *surface;
7034 const q3mbrush_t *brush;
7036 // find out how many BIH leaf nodes we need
7038 if (userendersurfaces)
7040 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7041 bihnumleafs += surface->num_triangles;
7045 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7046 if (brush->colbrushf)
7048 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7050 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7051 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7053 bihnumleafs += surface->num_collisiontriangles;
7060 // allocate the memory for the BIH leaf nodes
7061 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7063 // now populate the BIH leaf nodes
7066 // add render surfaces
7067 renderelement3i = model->surfmesh.data_element3i;
7068 rendervertex3f = model->surfmesh.data_vertex3f;
7069 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7071 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7073 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7075 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7076 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7077 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7078 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7079 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7080 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7081 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7082 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7083 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7084 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7089 if (!userendersurfaces)
7091 // add collision brushes
7092 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7094 if (!brush->colbrushf)
7096 bihleafs[bihleafindex].type = BIH_BRUSH;
7097 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7098 bihleafs[bihleafindex].surfaceindex = -1;
7099 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7100 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7101 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7105 // add collision surfaces
7106 collisionelement3i = model->brush.data_collisionelement3i;
7107 collisionvertex3f = model->brush.data_collisionvertex3f;
7108 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7110 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7112 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7113 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7114 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7115 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7116 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7117 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7118 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7119 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7120 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7121 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7127 // allocate buffers for the produced and temporary data
7128 bihmaxnodes = bihnumleafs + 1;
7129 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7130 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7131 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7134 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7136 // we're done with the temporary data
7137 Mem_Free(temp_leafsort);
7139 // resize the BIH nodes array if it over-allocated
7140 if (out->maxnodes > out->numnodes)
7142 out->maxnodes = out->numnodes;
7143 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7149 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7151 int supercontents = 0;
7152 if (nativecontents & CONTENTSQ3_SOLID)
7153 supercontents |= SUPERCONTENTS_SOLID;
7154 if (nativecontents & CONTENTSQ3_WATER)
7155 supercontents |= SUPERCONTENTS_WATER;
7156 if (nativecontents & CONTENTSQ3_SLIME)
7157 supercontents |= SUPERCONTENTS_SLIME;
7158 if (nativecontents & CONTENTSQ3_LAVA)
7159 supercontents |= SUPERCONTENTS_LAVA;
7160 if (nativecontents & CONTENTSQ3_BODY)
7161 supercontents |= SUPERCONTENTS_BODY;
7162 if (nativecontents & CONTENTSQ3_CORPSE)
7163 supercontents |= SUPERCONTENTS_CORPSE;
7164 if (nativecontents & CONTENTSQ3_NODROP)
7165 supercontents |= SUPERCONTENTS_NODROP;
7166 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7167 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7168 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7169 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7170 if (nativecontents & CONTENTSQ3_DONOTENTER)
7171 supercontents |= SUPERCONTENTS_DONOTENTER;
7172 if (nativecontents & CONTENTSQ3_BOTCLIP)
7173 supercontents |= SUPERCONTENTS_BOTCLIP;
7174 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7175 supercontents |= SUPERCONTENTS_OPAQUE;
7176 return supercontents;
7179 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7181 int nativecontents = 0;
7182 if (supercontents & SUPERCONTENTS_SOLID)
7183 nativecontents |= CONTENTSQ3_SOLID;
7184 if (supercontents & SUPERCONTENTS_WATER)
7185 nativecontents |= CONTENTSQ3_WATER;
7186 if (supercontents & SUPERCONTENTS_SLIME)
7187 nativecontents |= CONTENTSQ3_SLIME;
7188 if (supercontents & SUPERCONTENTS_LAVA)
7189 nativecontents |= CONTENTSQ3_LAVA;
7190 if (supercontents & SUPERCONTENTS_BODY)
7191 nativecontents |= CONTENTSQ3_BODY;
7192 if (supercontents & SUPERCONTENTS_CORPSE)
7193 nativecontents |= CONTENTSQ3_CORPSE;
7194 if (supercontents & SUPERCONTENTS_NODROP)
7195 nativecontents |= CONTENTSQ3_NODROP;
7196 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7197 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7198 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7199 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7200 if (supercontents & SUPERCONTENTS_DONOTENTER)
7201 nativecontents |= CONTENTSQ3_DONOTENTER;
7202 if (supercontents & SUPERCONTENTS_BOTCLIP)
7203 nativecontents |= CONTENTSQ3_BOTCLIP;
7204 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7205 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7206 return nativecontents;
7209 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7214 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7215 node = node->children[1];
7217 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7218 if (loadmodel->brush.num_leafs < numleafs)
7219 loadmodel->brush.num_leafs = numleafs;
7222 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7225 q3dheader_t *header;
7226 float corner[3], yawradius, modelradius;
7228 mod->modeldatatypestring = "Q3BSP";
7230 mod->type = mod_brushq3;
7231 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7234 header = (q3dheader_t *)buffer;
7235 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7236 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7238 i = LittleLong(header->version);
7239 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7240 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7242 mod->soundfromcenter = true;
7243 mod->TraceBox = Mod_Q3BSP_TraceBox;
7244 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7245 mod->TraceLine = Mod_Q3BSP_TraceLine;
7246 mod->TracePoint = Mod_Q3BSP_TracePoint;
7247 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7248 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7249 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7250 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7251 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7252 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7253 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7254 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7255 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7256 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7257 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7258 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7259 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7260 mod->brush.AmbientSoundLevelsForPoint = NULL;
7261 mod->brush.RoundUpToHullSize = NULL;
7262 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7263 mod->Draw = R_Q1BSP_Draw;
7264 mod->DrawDepth = R_Q1BSP_DrawDepth;
7265 mod->DrawDebug = R_Q1BSP_DrawDebug;
7266 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7267 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7268 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7269 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7270 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7271 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7272 mod->DrawLight = R_Q1BSP_DrawLight;
7274 mod_base = (unsigned char *)header;
7276 // swap all the lumps
7277 header->ident = LittleLong(header->ident);
7278 header->version = LittleLong(header->version);
7279 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7280 for (i = 0;i < lumps;i++)
7282 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7283 if((char *) bufferend < (char *) buffer + j)
7284 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7285 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7286 if((char *) bufferend < (char *) buffer + j)
7287 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7290 * NO, do NOT clear them!
7291 * they contain actual data referenced by other stuff.
7292 * Instead, before using the advertisements lump, check header->versio
7294 * Sorry, but otherwise it breaks memory of the first lump.
7295 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7297 header->lumps[i].fileofs = 0;
7298 header->lumps[i].filelen = 0;
7302 mod->brush.qw_md4sum = 0;
7303 mod->brush.qw_md4sum2 = 0;
7304 for (i = 0;i < lumps;i++)
7306 if (i == Q3LUMP_ENTITIES)
7308 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7309 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7311 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7313 // all this checksumming can take a while, so let's send keepalives here too
7314 CL_KeepaliveMessage(false);
7317 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7318 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7319 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7320 if (header->version == Q3BSPVERSION_IG)
7321 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7323 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7324 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7325 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7326 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7327 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7328 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7329 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7330 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7331 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7332 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7333 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7334 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7335 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7336 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7337 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7339 // the MakePortals code works fine on the q3bsp data as well
7340 if (mod_bsp_portalize.integer)
7341 Mod_Q1BSP_MakePortals();
7343 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7344 loadmodel->brush.supportwateralpha = true;
7346 // make a single combined shadow mesh to allow optimized shadow volume creation
7347 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7349 loadmodel->brush.num_leafs = 0;
7350 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7352 if (loadmodel->brush.numsubmodels)
7353 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7356 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7361 // duplicate the basic information
7362 dpsnprintf(name, sizeof(name), "*%i", i);
7363 mod = Mod_FindName(name, loadmodel->name);
7364 // copy the base model to this one
7366 // rename the clone back to its proper name
7367 strlcpy(mod->name, name, sizeof(mod->name));
7368 mod->brush.parentmodel = loadmodel;
7369 // textures and memory belong to the main model
7370 mod->texturepool = NULL;
7371 mod->mempool = NULL;
7372 mod->brush.GetPVS = NULL;
7373 mod->brush.FatPVS = NULL;
7374 mod->brush.BoxTouchingPVS = NULL;
7375 mod->brush.BoxTouchingLeafPVS = NULL;
7376 mod->brush.BoxTouchingVisibleLeafs = NULL;
7377 mod->brush.FindBoxClusters = NULL;
7378 mod->brush.LightPoint = NULL;
7379 mod->brush.AmbientSoundLevelsForPoint = NULL;
7381 mod->brush.submodel = i;
7382 if (loadmodel->brush.submodels)
7383 loadmodel->brush.submodels[i] = mod;
7385 // make the model surface list (used by shadowing/lighting)
7386 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7387 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7388 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7389 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7390 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7391 Mod_MakeSortedSurfaces(mod);
7393 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7394 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7395 // enlarge the bounding box to enclose all geometry of this model,
7396 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7397 // which can in turn mess up the farclip (as well as culling when
7398 // outside the level - an unimportant concern)
7400 //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]);
7401 for (j = 0;j < mod->nummodelsurfaces;j++)
7403 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7404 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7406 if (!surface->num_vertices)
7408 for (k = 0;k < surface->num_vertices;k++, v += 3)
7410 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7411 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7412 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7413 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7414 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7415 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7418 //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]);
7419 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7420 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7421 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7422 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7423 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7424 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7425 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7426 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7427 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7428 mod->yawmins[2] = mod->normalmins[2];
7429 mod->yawmaxs[2] = mod->normalmaxs[2];
7430 mod->radius = modelradius;
7431 mod->radius2 = modelradius * modelradius;
7433 // this gets altered below if sky or water is used
7434 mod->DrawSky = NULL;
7435 mod->DrawAddWaterPlanes = NULL;
7437 for (j = 0;j < mod->nummodelsurfaces;j++)
7438 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7440 if (j < mod->nummodelsurfaces)
7441 mod->DrawSky = R_Q1BSP_DrawSky;
7443 for (j = 0;j < mod->nummodelsurfaces;j++)
7444 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7446 if (j < mod->nummodelsurfaces)
7447 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7449 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7450 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7452 // generate VBOs and other shared data before cloning submodels
7457 if (mod_q3bsp_sRGBlightmaps.integer)
7459 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7461 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7462 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7463 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7464 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7465 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7467 else // if this is NOT set, regular rendering looks right by this requirement anyway
7470 // we want color 1 to do the same as without sRGB
7471 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7472 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7475 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7476 // we need to undo that
7477 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7481 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);
7484 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7486 int i = LittleLong(((int *)buffer)[1]);
7487 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7488 Mod_Q3BSP_Load(mod,buffer, bufferend);
7489 else if (i == Q2BSPVERSION)
7490 Mod_Q2BSP_Load(mod,buffer, bufferend);
7492 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7495 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7497 Host_Error("Mod_MAP_Load: not yet implemented");
7500 typedef struct objvertex_s
7511 static unsigned char nobsp_pvs[1] = {1};
7513 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7515 const char *textbase = (char *)buffer, *text = textbase;
7519 char materialname[MAX_QPATH];
7520 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7521 int index1, index2, index3;
7522 objvertex_t vfirst, vprev, vcurrent;
7525 int numtriangles = 0;
7526 int maxtriangles = 0;
7527 objvertex_t *vertices = NULL;
7529 int maxtextures = 0, numtextures = 0, textureindex = 0;
7530 int maxv = 0, numv = 1;
7531 int maxvt = 0, numvt = 1;
7532 int maxvn = 0, numvn = 1;
7533 char *texturenames = NULL;
7534 float dist, modelradius, modelyawradius, yawradius;
7541 objvertex_t *thisvertex = NULL;
7542 int vertexhashindex;
7543 int *vertexhashtable = NULL;
7544 objvertex_t *vertexhashdata = NULL;
7545 objvertex_t *vdata = NULL;
7546 int vertexhashsize = 0;
7547 int vertexhashcount = 0;
7548 skinfile_t *skinfiles = NULL;
7549 unsigned char *data = NULL;
7550 int *submodelfirstsurface;
7551 msurface_t *surface;
7552 msurface_t *tempsurfaces;
7554 memset(&vfirst, 0, sizeof(vfirst));
7555 memset(&vprev, 0, sizeof(vprev));
7556 memset(&vcurrent, 0, sizeof(vcurrent));
7558 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7560 loadmodel->modeldatatypestring = "OBJ";
7562 loadmodel->type = mod_obj;
7563 loadmodel->soundfromcenter = true;
7564 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7565 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7566 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7567 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7568 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7569 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7570 loadmodel->brush.TraceLineOfSight = NULL;
7571 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7572 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7573 loadmodel->brush.GetPVS = NULL;
7574 loadmodel->brush.FatPVS = NULL;
7575 loadmodel->brush.BoxTouchingPVS = NULL;
7576 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7577 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7578 loadmodel->brush.FindBoxClusters = NULL;
7579 loadmodel->brush.LightPoint = NULL;
7580 loadmodel->brush.FindNonSolidLocation = NULL;
7581 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7582 loadmodel->brush.RoundUpToHullSize = NULL;
7583 loadmodel->brush.PointInLeaf = NULL;
7584 loadmodel->Draw = R_Q1BSP_Draw;
7585 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7586 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7587 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7588 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7589 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7590 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7591 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7592 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7593 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7595 skinfiles = Mod_LoadSkinFiles();
7596 if (loadmodel->numskins < 1)
7597 loadmodel->numskins = 1;
7599 // make skinscenes for the skins (no groups)
7600 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7601 for (i = 0;i < loadmodel->numskins;i++)
7603 loadmodel->skinscenes[i].firstframe = i;
7604 loadmodel->skinscenes[i].framecount = 1;
7605 loadmodel->skinscenes[i].loop = true;
7606 loadmodel->skinscenes[i].framerate = 10;
7612 // we always have model 0, i.e. the first "submodel"
7613 loadmodel->brush.numsubmodels = 1;
7615 // parse the OBJ text now
7618 static char emptyarg[1] = "";
7623 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7624 line[linelen] = text[linelen];
7626 for (argc = 0;argc < 4;argc++)
7627 argv[argc] = emptyarg;
7630 while (*s == ' ' || *s == '\t')
7640 while (*s == ' ' || *s == '\t')
7650 if (argv[0][0] == '#')
7652 if (!strcmp(argv[0], "v"))
7656 maxv = max(maxv * 2, 1024);
7657 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7659 if(mod_obj_orientation.integer)
7661 v[numv*3+0] = atof(argv[1]);
7662 v[numv*3+2] = atof(argv[2]);
7663 v[numv*3+1] = atof(argv[3]);
7667 v[numv*3+0] = atof(argv[1]);
7668 v[numv*3+1] = atof(argv[2]);
7669 v[numv*3+2] = atof(argv[3]);
7673 else if (!strcmp(argv[0], "vt"))
7677 maxvt = max(maxvt * 2, 1024);
7678 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7680 vt[numvt*2+0] = atof(argv[1]);
7681 vt[numvt*2+1] = 1-atof(argv[2]);
7684 else if (!strcmp(argv[0], "vn"))
7688 maxvn = max(maxvn * 2, 1024);
7689 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7691 if(mod_obj_orientation.integer)
7693 vn[numvn*3+0] = atof(argv[1]);
7694 vn[numvn*3+2] = atof(argv[2]);
7695 vn[numvn*3+1] = atof(argv[3]);
7699 vn[numvn*3+0] = atof(argv[1]);
7700 vn[numvn*3+1] = atof(argv[2]);
7701 vn[numvn*3+2] = atof(argv[3]);
7705 else if (!strcmp(argv[0], "f"))
7709 if (maxtextures <= numtextures)
7711 maxtextures = max(maxtextures * 2, 256);
7712 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7714 textureindex = numtextures++;
7715 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7717 for (j = 1;j < argc;j++)
7719 index1 = atoi(argv[j]);
7720 while(argv[j][0] && argv[j][0] != '/')
7724 index2 = atoi(argv[j]);
7725 while(argv[j][0] && argv[j][0] != '/')
7729 index3 = atoi(argv[j]);
7730 // negative refers to a recent vertex
7731 // zero means not specified
7732 // positive means an absolute vertex index
7734 index1 = numv - index1;
7736 index2 = numvt - index2;
7738 index3 = numvn - index3;
7739 vcurrent.nextindex = -1;
7740 vcurrent.textureindex = textureindex;
7741 vcurrent.submodelindex = submodelindex;
7742 if (v && index1 >= 0 && index1 < numv)
7743 VectorCopy(v + 3*index1, vcurrent.v);
7744 if (vt && index2 >= 0 && index2 < numvt)
7745 Vector2Copy(vt + 2*index2, vcurrent.vt);
7746 if (vn && index3 >= 0 && index3 < numvn)
7747 VectorCopy(vn + 3*index3, vcurrent.vn);
7748 if (numtriangles == 0)
7750 VectorCopy(vcurrent.v, mins);
7751 VectorCopy(vcurrent.v, maxs);
7755 mins[0] = min(mins[0], vcurrent.v[0]);
7756 mins[1] = min(mins[1], vcurrent.v[1]);
7757 mins[2] = min(mins[2], vcurrent.v[2]);
7758 maxs[0] = max(maxs[0], vcurrent.v[0]);
7759 maxs[1] = max(maxs[1], vcurrent.v[1]);
7760 maxs[2] = max(maxs[2], vcurrent.v[2]);
7766 if (maxtriangles <= numtriangles)
7768 maxtriangles = max(maxtriangles * 2, 32768);
7769 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7771 if(mod_obj_orientation.integer)
7773 vertices[numtriangles*3+0] = vfirst;
7774 vertices[numtriangles*3+1] = vprev;
7775 vertices[numtriangles*3+2] = vcurrent;
7779 vertices[numtriangles*3+0] = vfirst;
7780 vertices[numtriangles*3+2] = vprev;
7781 vertices[numtriangles*3+1] = vcurrent;
7788 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7790 submodelindex = atof(argv[1]);
7791 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7793 else if (!strcmp(argv[0], "usemtl"))
7795 for (i = 0;i < numtextures;i++)
7796 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7798 if (i < numtextures)
7802 if (maxtextures <= numtextures)
7804 maxtextures = max(maxtextures * 2, 256);
7805 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7807 textureindex = numtextures++;
7808 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7813 // now that we have the OBJ data loaded as-is, we can convert it
7815 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7816 VectorCopy(mins, loadmodel->normalmins);
7817 VectorCopy(maxs, loadmodel->normalmaxs);
7818 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7819 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7820 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7821 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7822 modelradius = modelyawradius + modelradius * modelradius;
7823 modelyawradius = sqrt(modelyawradius);
7824 modelradius = sqrt(modelradius);
7825 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7826 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7827 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7828 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7829 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7830 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7831 loadmodel->radius = modelradius;
7832 loadmodel->radius2 = modelradius * modelradius;
7834 // allocate storage for triangles
7835 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7836 // allocate vertex hash structures to build an optimal vertex subset
7837 vertexhashsize = numtriangles*2;
7838 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7839 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7840 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7841 vertexhashcount = 0;
7843 // gather surface stats for assigning vertex/triangle ranges
7847 loadmodel->num_surfaces = 0;
7848 // allocate storage for the worst case number of surfaces, later we resize
7849 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7850 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7851 surface = tempsurfaces;
7852 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7854 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7855 for (textureindex = 0;textureindex < numtextures;textureindex++)
7857 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7859 thisvertex = vertices + vertexindex;
7860 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7863 // skip the surface creation if there are no triangles for it
7864 if (vertexindex == numtriangles*3)
7866 // create a surface for these vertices
7867 surfacevertices = 0;
7868 surfaceelements = 0;
7869 // we hack in a texture index in the surface to be fixed up later...
7870 surface->texture = (texture_t *)((size_t)textureindex);
7871 // calculate bounds as we go
7872 VectorCopy(thisvertex->v, surface->mins);
7873 VectorCopy(thisvertex->v, surface->maxs);
7874 for (;vertexindex < numtriangles*3;vertexindex++)
7876 thisvertex = vertices + vertexindex;
7877 if (thisvertex->submodelindex != submodelindex)
7879 if (thisvertex->textureindex != textureindex)
7881 // add vertex to surface bounds
7882 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7883 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7884 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7885 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7886 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7887 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7888 // add the vertex if it is not found in the merged set, and
7889 // get its index (triangle element) for the surface
7890 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7891 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7893 vdata = vertexhashdata + i;
7894 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7899 i = vertexhashcount++;
7900 vdata = vertexhashdata + i;
7901 *vdata = *thisvertex;
7902 vdata->nextindex = vertexhashtable[vertexhashindex];
7903 vertexhashtable[vertexhashindex] = i;
7906 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7909 surfacetriangles = surfaceelements / 3;
7910 surface->num_vertices = surfacevertices;
7911 surface->num_triangles = surfacetriangles;
7912 surface->num_firstvertex = firstvertex;
7913 surface->num_firsttriangle = firsttriangle;
7914 firstvertex += surface->num_vertices;
7915 firsttriangle += surface->num_triangles;
7917 loadmodel->num_surfaces++;
7920 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7921 numvertices = firstvertex;
7922 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7923 tempsurfaces = NULL;
7925 // allocate storage for final mesh data
7926 loadmodel->num_textures = numtextures * loadmodel->numskins;
7927 loadmodel->num_texturesperskin = numtextures;
7928 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 *));
7929 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7930 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7931 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7932 loadmodel->surfmesh.num_vertices = numvertices;
7933 loadmodel->surfmesh.num_triangles = numtriangles;
7934 if (r_enableshadowvolumes.integer)
7935 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7936 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7937 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7938 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7939 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7940 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7941 if (loadmodel->surfmesh.num_vertices <= 65536)
7942 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7944 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7946 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7947 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7948 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7951 // load the textures
7952 for (textureindex = 0;textureindex < numtextures;textureindex++)
7953 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7954 Mod_FreeSkinFiles(skinfiles);
7956 // set the surface textures to their real values now that we loaded them...
7957 for (i = 0;i < loadmodel->num_surfaces;i++)
7958 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7962 Mem_Free(texturenames);
7966 Mem_Free(vertexhashtable);
7967 Mem_Free(vertexhashdata);
7969 // make a single combined shadow mesh to allow optimized shadow volume creation
7970 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7972 // compute all the mesh information that was not loaded from the file
7973 if (loadmodel->surfmesh.data_element3s)
7974 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7975 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7976 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7977 // generate normals if the file did not have them
7978 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7979 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);
7980 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);
7981 if (loadmodel->surfmesh.data_neighbor3i)
7982 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7984 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7985 loadmodel->brush.num_visleafs = 1;
7986 loadmodel->brush.num_leafs = 1;
7987 loadmodel->brush.num_nodes = 0;
7988 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7989 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7990 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7991 loadmodel->brush.num_pvsclusters = 1;
7992 loadmodel->brush.num_pvsclusterbytes = 1;
7993 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7994 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7995 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7996 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7997 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7998 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7999 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8000 loadmodel->brush.data_leafs->clusterindex = 0;
8001 loadmodel->brush.data_leafs->areaindex = 0;
8002 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8003 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8004 loadmodel->brush.data_leafs->numleafbrushes = 0;
8005 loadmodel->brush.data_leafs->firstleafbrush = NULL;
8006 loadmodel->brush.supportwateralpha = true;
8008 if (loadmodel->brush.numsubmodels)
8009 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
8012 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8017 // duplicate the basic information
8018 dpsnprintf(name, sizeof(name), "*%i", i);
8019 mod = Mod_FindName(name, loadmodel->name);
8020 // copy the base model to this one
8022 // rename the clone back to its proper name
8023 strlcpy(mod->name, name, sizeof(mod->name));
8024 mod->brush.parentmodel = loadmodel;
8025 // textures and memory belong to the main model
8026 mod->texturepool = NULL;
8027 mod->mempool = NULL;
8028 mod->brush.GetPVS = NULL;
8029 mod->brush.FatPVS = NULL;
8030 mod->brush.BoxTouchingPVS = NULL;
8031 mod->brush.BoxTouchingLeafPVS = NULL;
8032 mod->brush.BoxTouchingVisibleLeafs = NULL;
8033 mod->brush.FindBoxClusters = NULL;
8034 mod->brush.LightPoint = NULL;
8035 mod->brush.AmbientSoundLevelsForPoint = NULL;
8037 mod->brush.submodel = i;
8038 if (loadmodel->brush.submodels)
8039 loadmodel->brush.submodels[i] = mod;
8041 // make the model surface list (used by shadowing/lighting)
8042 mod->firstmodelsurface = submodelfirstsurface[i];
8043 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
8044 mod->firstmodelbrush = 0;
8045 mod->nummodelbrushes = 0;
8046 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8047 Mod_MakeSortedSurfaces(mod);
8049 VectorClear(mod->normalmins);
8050 VectorClear(mod->normalmaxs);
8052 for (j = 0;j < mod->nummodelsurfaces;j++)
8054 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8055 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8057 if (!surface->num_vertices)
8062 VectorCopy(v, mod->normalmins);
8063 VectorCopy(v, mod->normalmaxs);
8065 for (k = 0;k < surface->num_vertices;k++, v += 3)
8067 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
8068 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
8069 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
8070 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
8071 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
8072 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
8075 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8076 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8077 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8078 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8079 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8080 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8081 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8082 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8083 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8084 mod->yawmins[2] = mod->normalmins[2];
8085 mod->yawmaxs[2] = mod->normalmaxs[2];
8086 mod->radius = modelradius;
8087 mod->radius2 = modelradius * modelradius;
8089 // this gets altered below if sky or water is used
8090 mod->DrawSky = NULL;
8091 mod->DrawAddWaterPlanes = NULL;
8093 for (j = 0;j < mod->nummodelsurfaces;j++)
8094 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8096 if (j < mod->nummodelsurfaces)
8097 mod->DrawSky = R_Q1BSP_DrawSky;
8099 for (j = 0;j < mod->nummodelsurfaces;j++)
8100 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8102 if (j < mod->nummodelsurfaces)
8103 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8105 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8106 mod->render_bih = mod->collision_bih;
8108 // generate VBOs and other shared data before cloning submodels
8113 Mem_Free(submodelfirstsurface);
8115 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);