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 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"};
43 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)"};
44 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
45 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)"};
46 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)"};
47 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
48 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
49 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, ..."};
50 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)"};
51 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
52 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
53 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"};
54 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
55 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
56 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
57 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
58 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"};
59 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"};
61 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)"};
62 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"};
63 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"};
65 static texture_t mod_q1bsp_texture_solid;
66 static texture_t mod_q1bsp_texture_sky;
67 static texture_t mod_q1bsp_texture_lava;
68 static texture_t mod_q1bsp_texture_slime;
69 static texture_t mod_q1bsp_texture_water;
71 void Mod_BrushInit(void)
73 // Cvar_RegisterVariable(&r_subdivide_size);
74 Cvar_RegisterVariable(&mod_bsp_portalize);
75 Cvar_RegisterVariable(&r_novis);
76 Cvar_RegisterVariable(&r_nosurftextures);
77 Cvar_RegisterVariable(&r_subdivisions_tolerance);
78 Cvar_RegisterVariable(&r_subdivisions_mintess);
79 Cvar_RegisterVariable(&r_subdivisions_maxtess);
80 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
81 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
82 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
83 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
84 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
85 Cvar_RegisterVariable(&r_trippy);
86 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
87 Cvar_RegisterVariable(&mod_obj_orientation);
88 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
89 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
90 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
91 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
92 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
93 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
94 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
95 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
96 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
97 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
98 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
99 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
100 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
101 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
102 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
103 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
104 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
105 Cvar_RegisterVariable(&mod_collision_bih);
106 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
108 // these games were made for older DP engines and are no longer
109 // maintained; use this hack to show their textures properly
110 if(gamemode == GAME_NEXUIZ)
111 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
113 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
114 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
115 mod_q1bsp_texture_solid.surfaceflags = 0;
116 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
118 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
119 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
120 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
121 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
123 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
124 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
125 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
126 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
128 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
129 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
130 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
131 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
133 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
134 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
135 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
136 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
139 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
146 // LordHavoc: modified to start at first clip node,
147 // in other words: first node of the (sub)model
148 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
150 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
152 return (mleaf_t *)node;
155 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
159 leaf = Mod_Q1BSP_PointInLeaf(model, p);
162 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
165 memcpy(out, leaf->ambient_sound_level, i);
171 memset(out, 0, outsize);
174 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
177 int nodestackindex = 0;
178 mnode_t *node, *nodestack[1024];
179 if (!model->brush.num_pvsclusters)
181 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
187 // node - recurse down the BSP tree
188 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
192 return -1; // ERROR: NAN bounding box!
193 // box is on one side of plane, take that path
194 node = node->children[sides-1];
198 // box crosses plane, take one path and remember the other
199 if (nodestackindex < 1024)
200 nodestack[nodestackindex++] = node->children[0];
201 node = node->children[1];
207 // leaf - add clusterindex to list
208 if (numclusters < maxclusters)
209 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
213 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
217 if (nodestackindex < 1024)
218 nodestack[nodestackindex++] = node->children[0];
219 node = node->children[1];
224 // leaf - add clusterindex to list
225 if (numclusters < maxclusters)
226 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
231 // try another path we didn't take earlier
232 if (nodestackindex == 0)
234 node = nodestack[--nodestackindex];
236 // return number of clusters found (even if more than the maxclusters)
240 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
242 int nodestackindex = 0;
243 mnode_t *node, *nodestack[1024];
244 if (!model->brush.num_pvsclusters)
246 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
252 // node - recurse down the BSP tree
253 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
257 return -1; // ERROR: NAN bounding box!
258 // box is on one side of plane, take that path
259 node = node->children[sides-1];
263 // box crosses plane, take one path and remember the other
264 if (nodestackindex < 1024)
265 nodestack[nodestackindex++] = node->children[0];
266 node = node->children[1];
272 // leaf - check cluster bit
273 int clusterindex = ((mleaf_t *)node)->clusterindex;
274 if (CHECKPVSBIT(pvs, clusterindex))
276 // it is visible, return immediately with the news
281 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
285 if (nodestackindex < 1024)
286 nodestack[nodestackindex++] = node->children[0];
287 node = node->children[1];
292 // leaf - check cluster bit
293 int clusterindex = ((mleaf_t *)node)->clusterindex;
294 if (CHECKPVSBIT(pvs, clusterindex))
296 // it is visible, return immediately with the news
302 // nothing to see here, try another path we didn't take earlier
303 if (nodestackindex == 0)
305 node = nodestack[--nodestackindex];
311 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
313 int nodestackindex = 0;
314 mnode_t *node, *nodestack[1024];
315 if (!model->brush.num_leafs)
317 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
323 // node - recurse down the BSP tree
324 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
328 return -1; // ERROR: NAN bounding box!
329 // box is on one side of plane, take that path
330 node = node->children[sides-1];
334 // box crosses plane, take one path and remember the other
335 if (nodestackindex < 1024)
336 nodestack[nodestackindex++] = node->children[0];
337 node = node->children[1];
343 // leaf - check cluster bit
344 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
345 if (CHECKPVSBIT(pvs, clusterindex))
347 // it is visible, return immediately with the news
352 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
356 if (nodestackindex < 1024)
357 nodestack[nodestackindex++] = node->children[0];
358 node = node->children[1];
363 // leaf - check cluster bit
364 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
365 if (CHECKPVSBIT(pvs, clusterindex))
367 // it is visible, return immediately with the news
373 // nothing to see here, try another path we didn't take earlier
374 if (nodestackindex == 0)
376 node = nodestack[--nodestackindex];
382 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
384 int nodestackindex = 0;
385 mnode_t *node, *nodestack[1024];
386 if (!model->brush.num_leafs)
388 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
394 // node - recurse down the BSP tree
395 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
399 return -1; // ERROR: NAN bounding box!
400 // box is on one side of plane, take that path
401 node = node->children[sides-1];
405 // box crosses plane, take one path and remember the other
406 if (nodestackindex < 1024)
407 nodestack[nodestackindex++] = node->children[0];
408 node = node->children[1];
414 // leaf - check if it is visible
415 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
417 // it is visible, return immediately with the news
422 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
426 if (nodestackindex < 1024)
427 nodestack[nodestackindex++] = node->children[0];
428 node = node->children[1];
433 // leaf - check if it is visible
434 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
436 // it is visible, return immediately with the news
442 // nothing to see here, try another path we didn't take earlier
443 if (nodestackindex == 0)
445 node = nodestack[--nodestackindex];
451 typedef struct findnonsolidlocationinfo_s
454 vec3_t absmin, absmax;
460 findnonsolidlocationinfo_t;
462 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
465 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
467 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
468 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
469 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
470 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
471 VectorSubtract(vert[1], vert[0], edge[0]);
472 VectorSubtract(vert[2], vert[1], edge[1]);
473 CrossProduct(edge[1], edge[0], facenormal);
474 if (facenormal[0] || facenormal[1] || facenormal[2])
476 VectorNormalize(facenormal);
477 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
478 if (f <= info->bestdist && f >= -info->bestdist)
480 VectorSubtract(vert[0], vert[2], edge[2]);
481 VectorNormalize(edge[0]);
482 VectorNormalize(edge[1]);
483 VectorNormalize(edge[2]);
484 CrossProduct(facenormal, edge[0], edgenormal[0]);
485 CrossProduct(facenormal, edge[1], edgenormal[1]);
486 CrossProduct(facenormal, edge[2], edgenormal[2]);
488 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
489 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
490 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
492 // we got lucky, the center is within the face
493 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
497 if (info->bestdist > dist)
499 info->bestdist = dist;
500 VectorScale(facenormal, (info->radius - -dist), info->nudge);
505 if (info->bestdist > dist)
507 info->bestdist = dist;
508 VectorScale(facenormal, (info->radius - dist), info->nudge);
514 // check which edge or vertex the center is nearest
515 for (i = 0;i < 3;i++)
517 f = DotProduct(info->center, edge[i]);
518 if (f >= DotProduct(vert[0], edge[i])
519 && f <= DotProduct(vert[1], edge[i]))
522 VectorMA(info->center, -f, edge[i], point);
523 dist = sqrt(DotProduct(point, point));
524 if (info->bestdist > dist)
526 info->bestdist = dist;
527 VectorScale(point, (info->radius / dist), info->nudge);
529 // skip both vertex checks
530 // (both are further away than this edge)
535 // not on edge, check first vertex of edge
536 VectorSubtract(info->center, vert[i], point);
537 dist = sqrt(DotProduct(point, point));
538 if (info->bestdist > dist)
540 info->bestdist = dist;
541 VectorScale(point, (info->radius / dist), info->nudge);
550 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
552 int surfacenum, k, *mark;
554 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
556 surface = info->model->data_surfaces + *mark;
557 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
559 if(surface->deprecatedq3num_bboxstride > 0)
562 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
563 for(i = 0; i < cnt; ++i)
565 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
567 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
569 tri = i * surface->deprecatedq3num_bboxstride + k;
570 if(tri >= surface->num_triangles)
572 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
579 for (k = 0;k < surface->num_triangles;k++)
581 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
588 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
592 float f = PlaneDiff(info->center, node->plane);
593 if (f >= -info->bestdist)
594 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
595 if (f <= info->bestdist)
596 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
600 if (((mleaf_t *)node)->numleafsurfaces)
601 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
605 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
608 findnonsolidlocationinfo_t info;
614 VectorCopy(in, info.center);
615 info.radius = radius;
620 VectorClear(info.nudge);
621 info.bestdist = radius;
622 VectorCopy(info.center, info.absmin);
623 VectorCopy(info.center, info.absmax);
624 info.absmin[0] -= info.radius + 1;
625 info.absmin[1] -= info.radius + 1;
626 info.absmin[2] -= info.radius + 1;
627 info.absmax[0] += info.radius + 1;
628 info.absmax[1] += info.radius + 1;
629 info.absmax[2] += info.radius + 1;
630 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
631 VectorAdd(info.center, info.nudge, info.center);
633 while (info.bestdist < radius && ++i < 10);
634 VectorCopy(info.center, out);
637 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
639 switch(nativecontents)
644 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
646 return SUPERCONTENTS_WATER;
648 return SUPERCONTENTS_SLIME;
650 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
652 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
657 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
659 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
660 return CONTENTS_SOLID;
661 if (supercontents & SUPERCONTENTS_SKY)
663 if (supercontents & SUPERCONTENTS_LAVA)
664 return CONTENTS_LAVA;
665 if (supercontents & SUPERCONTENTS_SLIME)
666 return CONTENTS_SLIME;
667 if (supercontents & SUPERCONTENTS_WATER)
668 return CONTENTS_WATER;
669 return CONTENTS_EMPTY;
672 typedef struct RecursiveHullCheckTraceInfo_s
674 // the hull we're tracing through
677 // the trace structure to fill in
680 // start, end, and end - start (in model space)
685 RecursiveHullCheckTraceInfo_t;
687 // 1/32 epsilon to keep floating point happy
688 #define DIST_EPSILON (0.03125)
690 #define HULLCHECKSTATE_EMPTY 0
691 #define HULLCHECKSTATE_SOLID 1
692 #define HULLCHECKSTATE_DONE 2
694 extern cvar_t collision_prefernudgedfraction;
695 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
697 // status variables, these don't need to be saved on the stack when
698 // recursing... but are because this should be thread-safe
699 // (note: tracing against a bbox is not thread-safe, yet)
704 // variables that need to be stored on the stack when recursing
709 // LordHavoc: a goto! everyone flee in terror... :)
714 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
715 if (!t->trace->startfound)
717 t->trace->startfound = true;
718 t->trace->startsupercontents |= num;
720 if (num & SUPERCONTENTS_LIQUIDSMASK)
721 t->trace->inwater = true;
723 t->trace->inopen = true;
724 if (num & SUPERCONTENTS_SOLID)
725 t->trace->hittexture = &mod_q1bsp_texture_solid;
726 else if (num & SUPERCONTENTS_SKY)
727 t->trace->hittexture = &mod_q1bsp_texture_sky;
728 else if (num & SUPERCONTENTS_LAVA)
729 t->trace->hittexture = &mod_q1bsp_texture_lava;
730 else if (num & SUPERCONTENTS_SLIME)
731 t->trace->hittexture = &mod_q1bsp_texture_slime;
733 t->trace->hittexture = &mod_q1bsp_texture_water;
734 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
735 t->trace->hitsupercontents = num;
736 if (num & t->trace->hitsupercontentsmask)
738 // if the first leaf is solid, set startsolid
739 if (t->trace->allsolid)
740 t->trace->startsolid = true;
741 #if COLLISIONPARANOID >= 3
744 return HULLCHECKSTATE_SOLID;
748 t->trace->allsolid = false;
749 #if COLLISIONPARANOID >= 3
752 return HULLCHECKSTATE_EMPTY;
756 // find the point distances
757 node = t->hull->clipnodes + num;
759 plane = t->hull->planes + node->planenum;
762 t1 = p1[plane->type] - plane->dist;
763 t2 = p2[plane->type] - plane->dist;
767 t1 = DotProduct (plane->normal, p1) - plane->dist;
768 t2 = DotProduct (plane->normal, p2) - plane->dist;
775 #if COLLISIONPARANOID >= 3
778 num = node->children[1];
787 #if COLLISIONPARANOID >= 3
790 num = node->children[0];
796 // the line intersects, find intersection point
797 // LordHavoc: this uses the original trace for maximum accuracy
798 #if COLLISIONPARANOID >= 3
803 t1 = t->start[plane->type] - plane->dist;
804 t2 = t->end[plane->type] - plane->dist;
808 t1 = DotProduct (plane->normal, t->start) - plane->dist;
809 t2 = DotProduct (plane->normal, t->end) - plane->dist;
812 midf = t1 / (t1 - t2);
813 midf = bound(p1f, midf, p2f);
814 VectorMA(t->start, midf, t->dist, mid);
816 // recurse both sides, front side first
817 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
818 // if this side is not empty, return what it is (solid or done)
819 if (ret != HULLCHECKSTATE_EMPTY)
822 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
823 // if other side is not solid, return what it is (empty or done)
824 if (ret != HULLCHECKSTATE_SOLID)
827 // front is air and back is solid, this is the impact point...
830 t->trace->plane.dist = -plane->dist;
831 VectorNegate (plane->normal, t->trace->plane.normal);
835 t->trace->plane.dist = plane->dist;
836 VectorCopy (plane->normal, t->trace->plane.normal);
839 // calculate the true fraction
840 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
841 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
842 midf = t1 / (t1 - t2);
843 t->trace->realfraction = bound(0, midf, 1);
845 // calculate the return fraction which is nudged off the surface a bit
846 midf = (t1 - DIST_EPSILON) / (t1 - t2);
847 t->trace->fraction = bound(0, midf, 1);
849 if (collision_prefernudgedfraction.integer)
850 t->trace->realfraction = t->trace->fraction;
852 #if COLLISIONPARANOID >= 3
855 return HULLCHECKSTATE_DONE;
858 //#if COLLISIONPARANOID < 2
859 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
862 mclipnode_t *nodes = t->hull->clipnodes;
863 mplane_t *planes = t->hull->planes;
865 VectorCopy(t->start, point);
868 plane = planes + nodes[num].planenum;
869 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
871 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
872 t->trace->startsupercontents |= num;
873 if (num & SUPERCONTENTS_LIQUIDSMASK)
874 t->trace->inwater = true;
876 t->trace->inopen = true;
877 if (num & t->trace->hitsupercontentsmask)
879 t->trace->allsolid = t->trace->startsolid = true;
880 return HULLCHECKSTATE_SOLID;
884 t->trace->allsolid = t->trace->startsolid = false;
885 return HULLCHECKSTATE_EMPTY;
890 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
892 RecursiveHullCheckTraceInfo_t rhc;
894 memset(&rhc, 0, sizeof(rhc));
895 memset(trace, 0, sizeof(trace_t));
897 rhc.trace->fraction = 1;
898 rhc.trace->realfraction = 1;
899 rhc.trace->allsolid = true;
900 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
901 VectorCopy(start, rhc.start);
902 VectorCopy(start, rhc.end);
903 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
906 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)
908 RecursiveHullCheckTraceInfo_t rhc;
910 if (VectorCompare(start, end))
912 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
916 memset(&rhc, 0, sizeof(rhc));
917 memset(trace, 0, sizeof(trace_t));
919 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
920 rhc.trace->fraction = 1;
921 rhc.trace->realfraction = 1;
922 rhc.trace->allsolid = true;
923 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
924 VectorCopy(start, rhc.start);
925 VectorCopy(end, rhc.end);
926 VectorSubtract(rhc.end, rhc.start, rhc.dist);
927 #if COLLISIONPARANOID >= 2
928 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]);
929 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
934 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
935 memset(&testtrace, 0, sizeof(trace_t));
936 rhc.trace = &testtrace;
937 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
938 rhc.trace->fraction = 1;
939 rhc.trace->realfraction = 1;
940 rhc.trace->allsolid = true;
941 VectorCopy(test, rhc.start);
942 VectorCopy(test, rhc.end);
943 VectorClear(rhc.dist);
944 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
945 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
946 if (!trace->startsolid && testtrace.startsolid)
947 Con_Printf(" - ended in solid!\n");
951 if (VectorLength2(rhc.dist))
952 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
954 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
958 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)
960 // this function currently only supports same size start and end
962 RecursiveHullCheckTraceInfo_t rhc;
964 if (VectorCompare(boxmins, boxmaxs))
966 if (VectorCompare(start, end))
967 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
969 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
973 memset(&rhc, 0, sizeof(rhc));
974 memset(trace, 0, sizeof(trace_t));
976 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
977 rhc.trace->fraction = 1;
978 rhc.trace->realfraction = 1;
979 rhc.trace->allsolid = true;
980 VectorSubtract(boxmaxs, boxmins, boxsize);
982 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
983 else if (model->brush.ishlbsp)
985 // LordHavoc: this has to have a minor tolerance (the .1) because of
986 // minor float precision errors from the box being transformed around
987 if (boxsize[0] < 32.1)
989 if (boxsize[2] < 54) // pick the nearest of 36 or 72
990 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
992 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
995 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
999 // LordHavoc: this has to have a minor tolerance (the .1) because of
1000 // minor float precision errors from the box being transformed around
1001 if (boxsize[0] < 32.1)
1002 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1004 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1006 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1007 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1008 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1009 #if COLLISIONPARANOID >= 2
1010 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]);
1011 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1016 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1017 memset(&testtrace, 0, sizeof(trace_t));
1018 rhc.trace = &testtrace;
1019 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1020 rhc.trace->fraction = 1;
1021 rhc.trace->realfraction = 1;
1022 rhc.trace->allsolid = true;
1023 VectorCopy(test, rhc.start);
1024 VectorCopy(test, rhc.end);
1025 VectorClear(rhc.dist);
1026 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1027 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1028 if (!trace->startsolid && testtrace.startsolid)
1029 Con_Printf(" - ended in solid!\n");
1033 if (VectorLength2(rhc.dist))
1034 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1036 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1040 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1042 int num = model->brushq1.hulls[0].firstclipnode;
1044 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1045 mplane_t *planes = model->brushq1.hulls[0].planes;
1048 plane = planes + nodes[num].planenum;
1049 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1051 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1054 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)
1058 colplanef_t cbox_planes[6];
1060 cbox.hasaabbplanes = true;
1061 cbox.supercontents = boxsupercontents;
1064 cbox.numtriangles = 0;
1065 cbox.planes = cbox_planes;
1067 cbox.elements = NULL;
1075 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];
1076 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];
1077 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];
1078 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];
1079 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];
1080 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];
1081 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1082 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1083 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1084 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1085 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1086 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1087 memset(trace, 0, sizeof(trace_t));
1088 trace->hitsupercontentsmask = hitsupercontentsmask;
1089 trace->fraction = 1;
1090 trace->realfraction = 1;
1091 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1093 RecursiveHullCheckTraceInfo_t rhc;
1094 static hull_t box_hull;
1095 static mclipnode_t box_clipnodes[6];
1096 static mplane_t box_planes[6];
1097 // fill in a default trace
1098 memset(&rhc, 0, sizeof(rhc));
1099 memset(trace, 0, sizeof(trace_t));
1100 //To keep everything totally uniform, bounding boxes are turned into small
1101 //BSP trees instead of being compared directly.
1102 // create a temp hull from bounding box sizes
1103 box_planes[0].dist = cmaxs[0] - mins[0];
1104 box_planes[1].dist = cmins[0] - maxs[0];
1105 box_planes[2].dist = cmaxs[1] - mins[1];
1106 box_planes[3].dist = cmins[1] - maxs[1];
1107 box_planes[4].dist = cmaxs[2] - mins[2];
1108 box_planes[5].dist = cmins[2] - maxs[2];
1109 #if COLLISIONPARANOID >= 3
1110 Con_Printf("box_planes %f:%f %f:%f %f:%f\ncbox %f %f %f:%f %f %f\nbox %f %f %f:%f %f %f\n", box_planes[0].dist, box_planes[1].dist, box_planes[2].dist, box_planes[3].dist, box_planes[4].dist, box_planes[5].dist, cmins[0], cmins[1], cmins[2], cmaxs[0], cmaxs[1], cmaxs[2], mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
1113 if (box_hull.clipnodes == NULL)
1117 //Set up the planes and clipnodes so that the six floats of a bounding box
1118 //can just be stored out and get a proper hull_t structure.
1120 box_hull.clipnodes = box_clipnodes;
1121 box_hull.planes = box_planes;
1122 box_hull.firstclipnode = 0;
1123 box_hull.lastclipnode = 5;
1125 for (i = 0;i < 6;i++)
1127 box_clipnodes[i].planenum = i;
1131 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1133 box_clipnodes[i].children[side^1] = i + 1;
1135 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1137 box_planes[i].type = i>>1;
1138 box_planes[i].normal[i>>1] = 1;
1142 // trace a line through the generated clipping hull
1143 //rhc.boxsupercontents = boxsupercontents;
1144 rhc.hull = &box_hull;
1146 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1147 rhc.trace->fraction = 1;
1148 rhc.trace->realfraction = 1;
1149 rhc.trace->allsolid = true;
1150 VectorCopy(start, rhc.start);
1151 VectorCopy(end, rhc.end);
1152 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1153 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1154 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1155 if (rhc.trace->startsupercontents)
1156 rhc.trace->startsupercontents = boxsupercontents;
1160 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)
1162 memset(trace, 0, sizeof(trace_t));
1163 trace->fraction = 1;
1164 trace->realfraction = 1;
1165 if (BoxesOverlap(start, start, cmins, cmaxs))
1167 trace->startsupercontents |= boxsupercontents;
1168 if (hitsupercontentsmask & boxsupercontents)
1170 trace->startsolid = true;
1171 trace->allsolid = true;
1176 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1179 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1180 return trace.fraction == 1;
1183 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)
1187 float mid, distz = endz - startz;
1191 return false; // didn't hit anything
1193 switch (node->plane->type)
1196 node = node->children[x < node->plane->dist];
1199 node = node->children[y < node->plane->dist];
1202 side = startz < node->plane->dist;
1203 if ((endz < node->plane->dist) == side)
1205 node = node->children[side];
1208 // found an intersection
1209 mid = node->plane->dist;
1212 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1213 front += startz * node->plane->normal[2];
1214 back += endz * node->plane->normal[2];
1215 side = front < node->plane->dist;
1216 if ((back < node->plane->dist) == side)
1218 node = node->children[side];
1221 // found an intersection
1222 mid = startz + distz * (front - node->plane->dist) / (front - back);
1226 // go down front side
1227 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1228 return true; // hit something
1231 // check for impact on this node
1232 if (node->numsurfaces)
1234 int i, dsi, dti, lmwidth, lmheight;
1236 msurface_t *surface;
1237 unsigned char *lightmap;
1238 int maps, line3, size3;
1241 float scale, w, w00, w01, w10, w11;
1243 surface = model->data_surfaces + node->firstsurface;
1244 for (i = 0;i < node->numsurfaces;i++, surface++)
1246 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1247 continue; // no lightmaps
1249 // location we want to sample in the lightmap
1250 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;
1251 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;
1256 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1257 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1260 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1262 // calculate bilinear interpolation factors
1263 // and also multiply by fixedpoint conversion factors
1266 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1267 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1268 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1269 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1271 // values for pointer math
1272 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1273 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1275 // look up the pixel
1276 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1278 // bilinear filter each lightmap style, and sum them
1279 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1281 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1282 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1283 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1284 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1285 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1289 return true; // success
1294 // go down back side
1295 node = node->children[side ^ 1];
1297 distz = endz - startz;
1302 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1304 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1305 VectorSet(diffusenormal, 0, 0, 1);
1307 if (!model->brushq1.lightdata)
1309 VectorSet(ambientcolor, 1, 1, 1);
1310 VectorSet(diffusecolor, 0, 0, 0);
1314 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);
1317 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1322 const msurface_t *surface;
1327 float edgenormal[3];
1334 surface = model->data_surfaces + node->firstsurface;
1335 for (i = 0;i < node->numsurfaces;i++, surface++)
1337 // skip surfaces whose bounding box does not include the point
1338 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1340 // skip faces with contents we don't care about
1341 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1343 // get the surface normal - since it is flat we know any vertex normal will suffice
1344 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1346 if (DotProduct(t->dist, normal) > 0)
1348 // iterate edges and see if the point is outside one of them
1349 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1351 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1352 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1353 VectorSubtract(v0, v1, edgedir);
1354 CrossProduct(edgedir, normal, edgenormal);
1355 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1358 // if the point is outside one of the edges, it is not within the surface
1359 if (j < surface->num_vertices)
1362 // we hit a surface, this is the impact point...
1363 VectorCopy(normal, t->trace->plane.normal);
1364 t->trace->plane.dist = DotProduct(normal, p);
1366 // calculate the true fraction
1367 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1368 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1369 midf = t1 / (t1 - t2);
1370 t->trace->realfraction = midf;
1372 // calculate the return fraction which is nudged off the surface a bit
1373 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1374 t->trace->fraction = bound(0, midf, 1);
1376 if (collision_prefernudgedfraction.integer)
1377 t->trace->realfraction = t->trace->fraction;
1379 t->trace->hittexture = surface->texture->currentframe;
1380 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1381 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1382 return surface->texture->currentframe;
1387 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])
1389 const mplane_t *plane;
1392 double midf, mid[3];
1393 const mleaf_t *leaf;
1397 plane = node->plane;
1398 if (plane->type < 3)
1400 t1 = p1[plane->type] - plane->dist;
1401 t2 = p2[plane->type] - plane->dist;
1405 t1 = DotProduct (plane->normal, p1) - plane->dist;
1406 t2 = DotProduct (plane->normal, p2) - plane->dist;
1412 node = node->children[1];
1421 node = node->children[0];
1427 // the line intersects, find intersection point
1428 // LordHavoc: this uses the original trace for maximum accuracy
1429 if (plane->type < 3)
1431 t1 = t->start[plane->type] - plane->dist;
1432 t2 = t->end[plane->type] - plane->dist;
1436 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1437 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1440 midf = t1 / (t1 - t2);
1441 VectorMA(t->start, midf, t->dist, mid);
1443 // recurse both sides, front side first, return if we hit a surface
1444 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1445 return HULLCHECKSTATE_DONE;
1447 // test each surface on the node
1448 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1449 if (t->trace->hittexture)
1450 return HULLCHECKSTATE_DONE;
1452 // recurse back side
1453 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1455 leaf = (const mleaf_t *)node;
1456 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1457 if (!t->trace->startfound)
1459 t->trace->startfound = true;
1460 t->trace->startsupercontents |= side;
1462 if (side & SUPERCONTENTS_LIQUIDSMASK)
1463 t->trace->inwater = true;
1465 t->trace->inopen = true;
1466 if (side & t->trace->hitsupercontentsmask)
1468 // if the first leaf is solid, set startsolid
1469 if (t->trace->allsolid)
1470 t->trace->startsolid = true;
1471 return HULLCHECKSTATE_SOLID;
1475 t->trace->allsolid = false;
1476 return HULLCHECKSTATE_EMPTY;
1480 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)
1482 RecursiveHullCheckTraceInfo_t rhc;
1484 memset(&rhc, 0, sizeof(rhc));
1485 memset(trace, 0, sizeof(trace_t));
1487 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1488 rhc.trace->fraction = 1;
1489 rhc.trace->realfraction = 1;
1490 rhc.trace->allsolid = true;
1491 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1492 VectorCopy(start, rhc.start);
1493 VectorCopy(end, rhc.end);
1494 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1495 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1496 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1499 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1502 unsigned char *outstart = out;
1503 while (out < outend)
1507 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));
1517 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));
1520 for (c = *in++;c > 0;c--)
1524 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));
1535 R_Q1BSP_LoadSplitSky
1537 A sky texture is 256*128, with the right side being a masked overlay
1540 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1545 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1546 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1548 // allocate a texture pool if we need it
1549 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1550 loadmodel->texturepool = R_AllocTexturePool();
1552 if (bytesperpixel == 4)
1554 for (y = 0;y < h;y++)
1556 for (x = 0;x < w;x++)
1558 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1559 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1565 // make an average value for the back to avoid
1566 // a fringe on the top level
1575 for (y = 0;y < h;y++)
1577 for (x = 0;x < w;x++)
1579 p = src[x*width+y+w];
1580 r += palette_rgb[p][0];
1581 g += palette_rgb[p][1];
1582 b += palette_rgb[p][2];
1585 bgra.b[2] = r/(w*h);
1586 bgra.b[1] = g/(w*h);
1587 bgra.b[0] = b/(w*h);
1589 for (y = 0;y < h;y++)
1591 for (x = 0;x < w;x++)
1593 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1595 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1600 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1601 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1602 Mem_Free(solidpixels);
1603 Mem_Free(alphapixels);
1606 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1608 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1609 skinframe_t *skinframe;
1610 texture_t *tx, *tx2, *anims[10], *altanims[10];
1611 texture_t backuptex;
1612 unsigned char *data, *mtdata;
1614 char mapname[MAX_QPATH], name[MAX_QPATH];
1615 unsigned char zeroopaque[4], zerotrans[4];
1618 Vector4Set(zeroopaque, 0, 0, 0, 255);
1619 Vector4Set(zerotrans, 0, 0, 0, 128);
1621 loadmodel->data_textures = NULL;
1623 // add two slots for notexture walls and notexture liquids
1626 nummiptex = MSG_ReadLittleLong(sb);
1627 loadmodel->num_textures = nummiptex + 2;
1628 loadmodel->num_texturesperskin = loadmodel->num_textures;
1632 loadmodel->num_textures = 2;
1633 loadmodel->num_texturesperskin = loadmodel->num_textures;
1636 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1638 // fill out all slots with notexture
1639 if (cls.state != ca_dedicated)
1640 skinframe = R_SkinFrame_LoadMissing();
1643 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1645 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1648 if (cls.state != ca_dedicated)
1650 tx->numskinframes = 1;
1651 tx->skinframerate = 1;
1652 tx->skinframes[0] = skinframe;
1653 tx->currentskinframe = tx->skinframes[0];
1655 tx->basematerialflags = MATERIALFLAG_WALL;
1656 if (i == loadmodel->num_textures - 1)
1658 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1659 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1660 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1664 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1665 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1667 tx->currentframe = tx;
1669 // clear water settings
1672 tx->refractfactor = 1;
1673 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1674 tx->reflectfactor = 1;
1675 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1676 tx->r_water_wateralpha = 1;
1677 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1678 tx->offsetscale = 1;
1680 tx->specularscalemod = 1;
1681 tx->specularpowermod = 1;
1686 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1690 s = loadmodel->name;
1691 if (!strncasecmp(s, "maps/", 5))
1693 FS_StripExtension(s, mapname, sizeof(mapname));
1695 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1696 // LordHavoc: mostly rewritten map texture loader
1697 for (i = 0;i < nummiptex;i++)
1699 doffset = MSG_ReadLittleLong(sb);
1700 if (r_nosurftextures.integer)
1704 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1708 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1710 // copy name, but only up to 16 characters
1711 // (the output buffer can hold more than this, but the input buffer is
1713 for (j = 0;j < 16;j++)
1714 name[j] = MSG_ReadByte(&miptexsb);
1716 // pretty up the buffer (replacing any trailing garbage with 0)
1717 for (j = strlen(name);j < 16;j++)
1722 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1723 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1726 mtwidth = MSG_ReadLittleLong(&miptexsb);
1727 mtheight = MSG_ReadLittleLong(&miptexsb);
1729 j = MSG_ReadLittleLong(&miptexsb);
1733 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1735 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1738 mtdata = miptexsb.data + j;
1741 if ((mtwidth & 15) || (mtheight & 15))
1742 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1744 // LordHavoc: force all names to lowercase
1745 for (j = 0;name[j];j++)
1746 if (name[j] >= 'A' && name[j] <= 'Z')
1747 name[j] += 'a' - 'A';
1749 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1750 backuptex = loadmodel->data_textures[i];
1751 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1753 loadmodel->data_textures[i] = backuptex;
1755 tx = loadmodel->data_textures + i;
1756 strlcpy(tx->name, name, sizeof(tx->name));
1757 tx->width = mtwidth;
1758 tx->height = mtheight;
1760 if (tx->name[0] == '*')
1762 if (!strncmp(tx->name, "*lava", 5))
1764 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1765 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1767 else if (!strncmp(tx->name, "*slime", 6))
1769 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1770 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1774 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1775 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1778 else if (!strncmp(tx->name, "sky", 3))
1780 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1781 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1782 tx->supercontents |= SUPERCONTENTS_SOLID; // for the surface traceline we need to hit this surface as a solid...
1786 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1787 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1790 if (cls.state != ca_dedicated)
1792 // LordHavoc: HL sky textures are entirely different than quake
1793 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1795 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1797 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1798 if (data && image_width == image_height * 2)
1800 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1803 else if (mtdata != NULL)
1804 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1808 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);
1810 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);
1812 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1815 // did not find external texture, load it from the bsp or wad3
1816 if (loadmodel->brush.ishlbsp)
1818 // internal texture overrides wad
1819 unsigned char *pixels, *freepixels;
1820 pixels = freepixels = NULL;
1822 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1824 pixels = freepixels = W_GetTextureBGRA(tx->name);
1827 tx->width = image_width;
1828 tx->height = image_height;
1829 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1832 Mem_Free(freepixels);
1834 else if (mtdata) // texture included
1835 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1837 // if skinframe is still NULL the "missing" texture will be used
1839 tx->skinframes[0] = skinframe;
1841 // LordHavoc: some Tenebrae textures get replaced by black
1842 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1843 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1844 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1845 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1848 tx->basematerialflags = MATERIALFLAG_WALL;
1849 if (tx->name[0] == '*')
1851 // LordHavoc: some turbulent textures should not be affected by wateralpha
1852 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1853 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1854 else if (!strncmp(tx->name,"*lava",5)
1855 || !strncmp(tx->name,"*teleport",9)
1856 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1857 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1859 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1860 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1861 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1863 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1865 // replace the texture with black
1866 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1868 else if (!strncmp(tx->name, "sky", 3))
1869 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1870 else if (!strcmp(tx->name, "caulk"))
1871 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1872 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1873 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1875 // start out with no animation
1876 tx->currentframe = tx;
1877 tx->currentskinframe = tx->skinframes[0];
1878 tx->currentmaterialflags = tx->basematerialflags;
1881 // sequence the animations
1882 for (i = 0;i < nummiptex;i++)
1884 tx = loadmodel->data_textures + i;
1885 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1887 if (tx->anim_total[0] || tx->anim_total[1])
1888 continue; // already sequenced
1890 // find the number of frames in the animation
1891 memset(anims, 0, sizeof(anims));
1892 memset(altanims, 0, sizeof(altanims));
1894 for (j = i;j < nummiptex;j++)
1896 tx2 = loadmodel->data_textures + j;
1897 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1901 if (num >= '0' && num <= '9')
1902 anims[num - '0'] = tx2;
1903 else if (num >= 'a' && num <= 'j')
1904 altanims[num - 'a'] = tx2;
1906 Con_Printf("Bad animating texture %s\n", tx->name);
1910 for (j = 0;j < 10;j++)
1917 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1920 for (j = 0;j < max;j++)
1924 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1928 for (j = 0;j < altmax;j++)
1932 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1941 // if there is no alternate animation, duplicate the primary
1942 // animation into the alternate
1944 for (k = 0;k < 10;k++)
1945 altanims[k] = anims[k];
1948 // link together the primary animation
1949 for (j = 0;j < max;j++)
1952 tx2->animated = true;
1953 tx2->anim_total[0] = max;
1954 tx2->anim_total[1] = altmax;
1955 for (k = 0;k < 10;k++)
1957 tx2->anim_frames[0][k] = anims[k];
1958 tx2->anim_frames[1][k] = altanims[k];
1962 // if there really is an alternate anim...
1963 if (anims[0] != altanims[0])
1965 // link together the alternate animation
1966 for (j = 0;j < altmax;j++)
1969 tx2->animated = true;
1970 // the primary/alternate are reversed here
1971 tx2->anim_total[0] = altmax;
1972 tx2->anim_total[1] = max;
1973 for (k = 0;k < 10;k++)
1975 tx2->anim_frames[0][k] = altanims[k];
1976 tx2->anim_frames[1][k] = anims[k];
1983 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
1986 unsigned char *in, *out, *data, d;
1987 char litfilename[MAX_QPATH];
1988 char dlitfilename[MAX_QPATH];
1989 fs_offset_t filesize;
1990 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1992 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
1993 for (i = 0;i < sb->cursize;i++)
1994 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
1996 else // LordHavoc: bsp version 29 (normal white lighting)
1998 // LordHavoc: hope is not lost yet, check for a .lit file to load
1999 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2000 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2001 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2002 strlcat (litfilename, ".lit", sizeof (litfilename));
2003 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2004 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2007 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2009 i = LittleLong(((int *)data)[1]);
2012 if (developer_loading.integer)
2013 Con_Printf("loaded %s\n", litfilename);
2014 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2015 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2017 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2020 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2022 i = LittleLong(((int *)data)[1]);
2025 if (developer_loading.integer)
2026 Con_Printf("loaded %s\n", dlitfilename);
2027 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2028 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2029 loadmodel->brushq3.deluxemapping_modelspace = false;
2030 loadmodel->brushq3.deluxemapping = true;
2039 Con_Printf("Unknown .lit file version (%d)\n", i);
2041 else if (filesize == 8)
2042 Con_Print("Empty .lit file, ignoring\n");
2044 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2051 // LordHavoc: oh well, expand the white lighting data
2054 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2056 out = loadmodel->brushq1.lightdata;
2057 for (i = 0;i < sb->cursize;i++)
2067 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2069 loadmodel->brushq1.num_compressedpvs = 0;
2070 loadmodel->brushq1.data_compressedpvs = NULL;
2073 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2074 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2075 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2078 // used only for HalfLife maps
2079 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2081 char key[128], value[4096];
2085 if (!COM_ParseToken_Simple(&data, false, false, true))
2087 if (com_token[0] != '{')
2091 if (!COM_ParseToken_Simple(&data, false, false, true))
2093 if (com_token[0] == '}')
2094 break; // end of worldspawn
2095 if (com_token[0] == '_')
2096 strlcpy(key, com_token + 1, sizeof(key));
2098 strlcpy(key, com_token, sizeof(key));
2099 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2100 key[strlen(key)-1] = 0;
2101 if (!COM_ParseToken_Simple(&data, false, false, true))
2103 dpsnprintf(value, sizeof(value), "%s", com_token);
2104 if (!strcmp("wad", key)) // for HalfLife maps
2106 if (loadmodel->brush.ishlbsp)
2109 for (i = 0;i < (int)sizeof(value);i++)
2110 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2114 for (;i < (int)sizeof(value);i++)
2116 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2117 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2119 else if (value[i] == ';' || value[i] == 0)
2123 W_LoadTextureWadFile(&value[j], false);
2135 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2137 loadmodel->brush.entities = NULL;
2140 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2141 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2142 loadmodel->brush.entities[sb->cursize] = 0;
2143 if (loadmodel->brush.ishlbsp)
2144 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2148 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2152 size_t structsize = 12;
2154 if (sb->cursize % structsize)
2155 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2156 count = sb->cursize / structsize;
2157 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2159 loadmodel->brushq1.vertexes = out;
2160 loadmodel->brushq1.numvertexes = count;
2162 for ( i=0 ; i<count ; i++, out++)
2164 out->position[0] = MSG_ReadLittleFloat(sb);
2165 out->position[1] = MSG_ReadLittleFloat(sb);
2166 out->position[2] = MSG_ReadLittleFloat(sb);
2170 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2174 size_t structsize = (48+4*hullinfo->filehulls);
2176 if (sb->cursize % structsize)
2177 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2179 count = sb->cursize / structsize;
2180 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2182 loadmodel->brushq1.submodels = out;
2183 loadmodel->brush.numsubmodels = count;
2185 for (i = 0; i < count; i++, out++)
2187 // spread out the mins / maxs by a pixel
2188 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2189 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2190 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2191 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2192 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2193 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2194 out->origin[0] = MSG_ReadLittleFloat(sb);
2195 out->origin[1] = MSG_ReadLittleFloat(sb);
2196 out->origin[2] = MSG_ReadLittleFloat(sb);
2197 for (j = 0; j < hullinfo->filehulls; j++)
2198 out->headnode[j] = MSG_ReadLittleLong(sb);
2199 out->visleafs = MSG_ReadLittleLong(sb);
2200 out->firstface = MSG_ReadLittleLong(sb);
2201 out->numfaces = MSG_ReadLittleLong(sb);
2205 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2209 size_t structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2211 if (sb->cursize % structsize)
2212 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2213 count = sb->cursize / structsize;
2214 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2216 loadmodel->brushq1.edges = out;
2217 loadmodel->brushq1.numedges = count;
2219 for ( i=0 ; i<count ; i++, out++)
2221 if (loadmodel->brush.isbsp2)
2223 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2224 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2228 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2229 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2231 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2233 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);
2234 if(!loadmodel->brushq1.numvertexes)
2235 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2243 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2246 int i, j, k, count, miptex;
2247 size_t structsize = 40;
2249 if (sb->cursize % structsize)
2250 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2251 count = sb->cursize / structsize;
2252 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2254 loadmodel->brushq1.texinfo = out;
2255 loadmodel->brushq1.numtexinfo = count;
2257 for (i = 0;i < count;i++, out++)
2259 for (k = 0;k < 2;k++)
2260 for (j = 0;j < 4;j++)
2261 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2263 miptex = MSG_ReadLittleLong(sb);
2264 out->flags = MSG_ReadLittleLong(sb);
2266 out->texture = NULL;
2267 if (loadmodel->data_textures)
2269 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2270 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2272 out->texture = loadmodel->data_textures + miptex;
2274 if (out->flags & TEX_SPECIAL)
2276 // if texture chosen is NULL or the shader needs a lightmap,
2277 // force to notexture water shader
2278 if (out->texture == NULL)
2279 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2283 // if texture chosen is NULL, force to notexture
2284 if (out->texture == NULL)
2285 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2291 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2296 mins[0] = mins[1] = mins[2] = 9999;
2297 maxs[0] = maxs[1] = maxs[2] = -9999;
2299 for (i = 0;i < numverts;i++)
2301 for (j = 0;j < 3;j++, v++)
2311 #define MAX_SUBDIVPOLYTRIANGLES 4096
2312 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2314 static int subdivpolyverts, subdivpolytriangles;
2315 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2316 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2318 static int subdivpolylookupvert(vec3_t v)
2321 for (i = 0;i < subdivpolyverts;i++)
2322 if (subdivpolyvert[i][0] == v[0]
2323 && subdivpolyvert[i][1] == v[1]
2324 && subdivpolyvert[i][2] == v[2])
2326 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2327 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2328 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2329 return subdivpolyverts++;
2332 static void SubdividePolygon(int numverts, float *verts)
2334 int i, i1, i2, i3, f, b, c, p;
2335 vec3_t mins, maxs, front[256], back[256];
2336 float m, *pv, *cv, dist[256], frac;
2339 Host_Error("SubdividePolygon: ran out of verts in buffer");
2341 BoundPoly(numverts, verts, mins, maxs);
2343 for (i = 0;i < 3;i++)
2345 m = (mins[i] + maxs[i]) * 0.5;
2346 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2347 if (maxs[i] - m < 8)
2349 if (m - mins[i] < 8)
2353 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2354 dist[c] = cv[i] - m;
2357 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2361 VectorCopy(pv, front[f]);
2366 VectorCopy(pv, back[b]);
2369 if (dist[p] == 0 || dist[c] == 0)
2371 if ((dist[p] > 0) != (dist[c] > 0) )
2374 frac = dist[p] / (dist[p] - dist[c]);
2375 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2376 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2377 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2383 SubdividePolygon(f, front[0]);
2384 SubdividePolygon(b, back[0]);
2388 i1 = subdivpolylookupvert(verts);
2389 i2 = subdivpolylookupvert(verts + 3);
2390 for (i = 2;i < numverts;i++)
2392 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2394 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2398 i3 = subdivpolylookupvert(verts + i * 3);
2399 subdivpolyindex[subdivpolytriangles][0] = i1;
2400 subdivpolyindex[subdivpolytriangles][1] = i2;
2401 subdivpolyindex[subdivpolytriangles][2] = i3;
2403 subdivpolytriangles++;
2407 //Breaks a polygon up along axial 64 unit
2408 //boundaries so that turbulent and sky warps
2409 //can be done reasonably.
2410 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2416 subdivpolytriangles = 0;
2417 subdivpolyverts = 0;
2418 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2419 if (subdivpolytriangles < 1)
2420 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2422 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2423 mesh->num_vertices = subdivpolyverts;
2424 mesh->num_triangles = subdivpolytriangles;
2425 mesh->vertex = (surfvertex_t *)(mesh + 1);
2426 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2427 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2429 for (i = 0;i < mesh->num_triangles;i++)
2430 for (j = 0;j < 3;j++)
2431 mesh->index[i*3+j] = subdivpolyindex[i][j];
2433 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2435 VectorCopy(subdivpolyvert[i], v->v);
2436 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2437 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2442 extern cvar_t gl_max_lightmapsize;
2443 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2445 msurface_t *surface;
2446 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2447 float texmins[2], texmaxs[2], val;
2448 rtexture_t *lightmaptexture, *deluxemaptexture;
2450 size_t structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2452 if (sb->cursize % structsize)
2453 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2454 count = sb->cursize / structsize;
2455 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2456 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2458 loadmodel->num_surfaces = count;
2460 loadmodel->brushq1.firstrender = true;
2461 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2465 for (surfacenum = 0;surfacenum < count;surfacenum++)
2467 if (loadmodel->brush.isbsp2)
2468 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2470 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2471 totalverts += numedges;
2472 totaltris += numedges - 2;
2475 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2477 lightmaptexture = NULL;
2478 deluxemaptexture = r_texture_blanknormalmap;
2480 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2481 totallightmapsamples = 0;
2485 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2487 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2488 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2489 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2490 firstedge = MSG_ReadLittleLong(sb);
2491 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2492 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2493 for (i = 0;i < MAXLIGHTMAPS;i++)
2494 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2495 lightmapoffset = MSG_ReadLittleLong(sb);
2497 // FIXME: validate edges, texinfo, etc?
2498 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)
2499 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2500 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2501 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2502 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2503 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2505 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2506 surface->texture = surface->lightmapinfo->texinfo->texture;
2508 //surface->flags = surface->texture->flags;
2509 //if (LittleShort(in->side))
2510 // surface->flags |= SURF_PLANEBACK;
2511 //surface->plane = loadmodel->brush.data_planes + planenum;
2513 surface->num_firstvertex = totalverts;
2514 surface->num_vertices = numedges;
2515 surface->num_firsttriangle = totaltris;
2516 surface->num_triangles = numedges - 2;
2517 totalverts += numedges;
2518 totaltris += numedges - 2;
2520 // convert edges back to a normal polygon
2521 for (i = 0;i < surface->num_vertices;i++)
2523 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2525 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2527 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2529 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2530 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2531 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2532 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2533 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2534 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2535 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2536 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2539 for (i = 0;i < surface->num_triangles;i++)
2541 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2542 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2543 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2546 // compile additional data about the surface geometry
2547 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);
2548 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);
2549 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2551 // generate surface extents information
2552 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2553 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2554 for (i = 1;i < surface->num_vertices;i++)
2556 for (j = 0;j < 2;j++)
2558 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2559 texmins[j] = min(texmins[j], val);
2560 texmaxs[j] = max(texmaxs[j], val);
2563 for (i = 0;i < 2;i++)
2565 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2566 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2569 smax = surface->lightmapinfo->extents[0] >> 4;
2570 tmax = surface->lightmapinfo->extents[1] >> 4;
2571 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2572 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2575 surface->lightmaptexture = NULL;
2576 surface->deluxemaptexture = r_texture_blanknormalmap;
2577 if (lightmapoffset == -1)
2579 surface->lightmapinfo->samples = NULL;
2581 // give non-lightmapped water a 1x white lightmap
2582 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2584 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2585 surface->lightmapinfo->styles[0] = 0;
2586 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2590 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2591 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2592 else // LordHavoc: white lighting (bsp version 29)
2594 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2595 if (loadmodel->brushq1.nmaplightdata)
2596 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2599 // check if we should apply a lightmap to this
2600 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2602 if (ssize > 256 || tsize > 256)
2603 Host_Error("Bad surface extents");
2605 if (lightmapsize < ssize)
2606 lightmapsize = ssize;
2607 if (lightmapsize < tsize)
2608 lightmapsize = tsize;
2610 totallightmapsamples += ssize*tsize;
2612 // force lightmap upload on first time seeing the surface
2614 // additionally this is used by the later code to see if a
2615 // lightmap is needed on this surface (rather than duplicating the
2617 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2618 loadmodel->lit = true;
2622 // small maps (such as ammo boxes especially) don't need big lightmap
2623 // textures, so this code tries to guess a good size based on
2624 // totallightmapsamples (size of the lightmaps lump basically), as well as
2625 // trying to max out the size if there is a lot of lightmap data to store
2626 // additionally, never choose a lightmapsize that is smaller than the
2627 // largest surface encountered (as it would fail)
2629 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2632 // now that we've decided the lightmap texture size, we can do the rest
2633 if (cls.state != ca_dedicated)
2635 int stainmapsize = 0;
2636 mod_alloclightmap_state_t allocState;
2638 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2639 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2641 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2642 float u, v, ubase, vbase, uscale, vscale;
2644 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2647 smax = surface->lightmapinfo->extents[0] >> 4;
2648 tmax = surface->lightmapinfo->extents[1] >> 4;
2649 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2650 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2651 stainmapsize += ssize * tsize * 3;
2653 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2655 // allocate a texture pool if we need it
2656 if (loadmodel->texturepool == NULL)
2657 loadmodel->texturepool = R_AllocTexturePool();
2658 // could not find room, make a new lightmap
2659 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2660 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2661 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2662 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);
2663 if (loadmodel->brushq1.nmaplightdata)
2664 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);
2666 Mod_AllocLightmap_Reset(&allocState);
2667 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2669 surface->lightmaptexture = lightmaptexture;
2670 surface->deluxemaptexture = deluxemaptexture;
2671 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2672 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2674 uscale = 1.0f / (float)lightmapsize;
2675 vscale = 1.0f / (float)lightmapsize;
2676 ubase = lightmapx * uscale;
2677 vbase = lightmapy * vscale;
2679 for (i = 0;i < surface->num_vertices;i++)
2681 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);
2682 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);
2683 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2684 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2685 // LordHavoc: calc lightmap data offset for vertex lighting to use
2688 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2692 if (cl_stainmaps.integer)
2694 // allocate stainmaps for permanent marks on walls and clear white
2695 unsigned char *stainsamples = NULL;
2696 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2697 memset(stainsamples, 255, stainmapsize);
2699 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2701 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2703 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2704 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2705 surface->lightmapinfo->stainsamples = stainsamples;
2706 stainsamples += ssize * tsize * 3;
2711 // generate ushort elements array if possible
2712 if (loadmodel->surfmesh.data_element3s)
2713 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2714 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2717 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2720 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2721 node->parent = parent;
2724 // this is a node, recurse to children
2725 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2726 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2727 // combine supercontents of children
2728 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2733 mleaf_t *leaf = (mleaf_t *)node;
2734 // if this is a leaf, calculate supercontents mask from all collidable
2735 // primitives in the leaf (brushes and collision surfaces)
2736 // also flag if the leaf contains any collision surfaces
2737 leaf->combinedsupercontents = 0;
2738 // combine the supercontents values of all brushes in this leaf
2739 for (j = 0;j < leaf->numleafbrushes;j++)
2740 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2741 // check if this leaf contains any collision surfaces (q3 patches)
2742 for (j = 0;j < leaf->numleafsurfaces;j++)
2744 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2745 if (surface->num_collisiontriangles)
2747 leaf->containscollisionsurfaces = true;
2748 leaf->combinedsupercontents |= surface->texture->supercontents;
2754 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2756 int i, j, count, p, child[2];
2758 size_t structsize = loadmodel->brush.isbsp2 ? 44 : 24;
2760 if (sb->cursize % structsize)
2761 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2762 count = sb->cursize / structsize;
2764 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2765 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2767 loadmodel->brush.data_nodes = out;
2768 loadmodel->brush.num_nodes = count;
2770 for ( i=0 ; i<count ; i++, out++)
2772 p = MSG_ReadLittleLong(sb);
2773 out->plane = loadmodel->brush.data_planes + p;
2775 if (loadmodel->brush.isbsp2)
2777 child[0] = MSG_ReadLittleLong(sb);
2778 child[1] = MSG_ReadLittleLong(sb);
2779 out->mins[0] = MSG_ReadLittleFloat(sb);
2780 out->mins[1] = MSG_ReadLittleFloat(sb);
2781 out->mins[2] = MSG_ReadLittleFloat(sb);
2782 out->maxs[0] = MSG_ReadLittleFloat(sb);
2783 out->maxs[1] = MSG_ReadLittleFloat(sb);
2784 out->maxs[2] = MSG_ReadLittleFloat(sb);
2785 out->firstsurface = MSG_ReadLittleLong(sb);
2786 out->numsurfaces = MSG_ReadLittleLong(sb);
2790 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2791 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2792 if (child[0] >= count)
2794 if (child[1] >= count)
2797 out->mins[0] = MSG_ReadLittleShort(sb);
2798 out->mins[1] = MSG_ReadLittleShort(sb);
2799 out->mins[2] = MSG_ReadLittleShort(sb);
2800 out->maxs[0] = MSG_ReadLittleShort(sb);
2801 out->maxs[1] = MSG_ReadLittleShort(sb);
2802 out->maxs[2] = MSG_ReadLittleShort(sb);
2804 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2805 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2808 for (j=0 ; j<2 ; j++)
2810 // LordHavoc: this code supports broken bsp files produced by
2811 // arguire qbsp which can produce more than 32768 nodes, any value
2812 // below count is assumed to be a node number, any other value is
2813 // assumed to be a leaf number
2817 if (p < loadmodel->brush.num_nodes)
2818 out->children[j] = loadmodel->brush.data_nodes + p;
2821 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2822 // map it to the solid leaf
2823 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2828 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2830 if (p < loadmodel->brush.num_leafs)
2831 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2834 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2835 // map it to the solid leaf
2836 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2842 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2845 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2848 int i, j, count, p, firstmarksurface, nummarksurfaces;
2849 size_t structsize = loadmodel->brush.isbsp2 ? 44 : 28;
2851 if (sb->cursize % structsize)
2852 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2853 count = sb->cursize / structsize;
2854 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2856 loadmodel->brush.data_leafs = out;
2857 loadmodel->brush.num_leafs = count;
2858 // get visleafs from the submodel data
2859 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2860 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2861 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2862 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2864 // FIXME: this function could really benefit from some error checking
2865 for ( i=0 ; i<count ; i++, out++)
2867 out->contents = MSG_ReadLittleLong(sb);
2869 out->clusterindex = i - 1;
2870 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2871 out->clusterindex = -1;
2873 p = MSG_ReadLittleLong(sb);
2874 // ignore visofs errors on leaf 0 (solid)
2875 if (p >= 0 && out->clusterindex >= 0)
2877 if (p >= loadmodel->brushq1.num_compressedpvs)
2878 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2880 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);
2883 if (loadmodel->brush.isbsp2)
2885 out->mins[0] = MSG_ReadLittleFloat(sb);
2886 out->mins[1] = MSG_ReadLittleFloat(sb);
2887 out->mins[2] = MSG_ReadLittleFloat(sb);
2888 out->maxs[0] = MSG_ReadLittleFloat(sb);
2889 out->maxs[1] = MSG_ReadLittleFloat(sb);
2890 out->maxs[2] = MSG_ReadLittleFloat(sb);
2892 firstmarksurface = MSG_ReadLittleLong(sb);
2893 nummarksurfaces = MSG_ReadLittleLong(sb);
2897 out->mins[0] = MSG_ReadLittleShort(sb);
2898 out->mins[1] = MSG_ReadLittleShort(sb);
2899 out->mins[2] = MSG_ReadLittleShort(sb);
2900 out->maxs[0] = MSG_ReadLittleShort(sb);
2901 out->maxs[1] = MSG_ReadLittleShort(sb);
2902 out->maxs[2] = MSG_ReadLittleShort(sb);
2904 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2905 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2908 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2910 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2911 out->numleafsurfaces = nummarksurfaces;
2915 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2916 out->firstleafsurface = NULL;
2917 out->numleafsurfaces = 0;
2920 for (j = 0;j < 4;j++)
2921 out->ambient_sound_level[j] = MSG_ReadByte(sb);
2925 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2929 const unsigned char *pvs;
2930 // if there's no vis data, assume supported (because everything is visible all the time)
2931 if (!loadmodel->brush.data_pvsclusters)
2933 // check all liquid leafs to see if they can see into empty leafs, if any
2934 // can we can assume this map supports r_wateralpha
2935 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2937 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2939 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2940 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2941 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2948 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
2953 size_t structsize = loadmodel->brush.isbsp2 ? 12 : 8;
2955 if (sb->cursize % structsize)
2956 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2957 count = sb->cursize / structsize;
2958 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2960 loadmodel->brushq1.clipnodes = out;
2961 loadmodel->brushq1.numclipnodes = count;
2963 for (i = 1; i < MAX_MAP_HULLS; i++)
2965 hull = &loadmodel->brushq1.hulls[i];
2966 hull->clipnodes = out;
2967 hull->firstclipnode = 0;
2968 hull->lastclipnode = count-1;
2969 hull->planes = loadmodel->brush.data_planes;
2970 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2971 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2972 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2973 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2974 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2975 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2976 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2979 for (i=0 ; i<count ; i++, out++)
2981 out->planenum = MSG_ReadLittleLong(sb);
2982 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2983 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
2984 if (loadmodel->brush.isbsp2)
2986 out->children[0] = MSG_ReadLittleLong(sb);
2987 out->children[1] = MSG_ReadLittleLong(sb);
2988 if (out->children[0] >= count)
2989 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
2990 if (out->children[1] >= count)
2991 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
2995 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2996 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
2997 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
2998 if (out->children[0] >= count)
2999 out->children[0] -= 65536;
3000 if (out->children[1] >= count)
3001 out->children[1] -= 65536;
3006 //Duplicate the drawing hull structure as a clipping hull
3007 static void Mod_Q1BSP_MakeHull0(void)
3014 hull = &loadmodel->brushq1.hulls[0];
3016 in = loadmodel->brush.data_nodes;
3017 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3019 hull->clipnodes = out;
3020 hull->firstclipnode = 0;
3021 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3022 hull->planes = loadmodel->brush.data_planes;
3024 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3026 out->planenum = in->plane - loadmodel->brush.data_planes;
3027 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3028 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3032 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3035 size_t structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3037 if (sb->cursize % structsize)
3038 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3039 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3040 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3042 if (loadmodel->brush.isbsp2)
3044 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3046 j = MSG_ReadLittleLong(sb);
3047 if (j < 0 || j >= loadmodel->num_surfaces)
3048 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3049 loadmodel->brush.data_leafsurfaces[i] = j;
3054 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3056 j = (unsigned short) MSG_ReadLittleShort(sb);
3057 if (j >= loadmodel->num_surfaces)
3058 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3059 loadmodel->brush.data_leafsurfaces[i] = j;
3064 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3067 size_t structsize = 4;
3069 if (sb->cursize % structsize)
3070 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3071 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3072 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3074 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3075 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3079 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3083 size_t structsize = 20;
3085 if (sb->cursize % structsize)
3086 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3087 loadmodel->brush.num_planes = sb->cursize / structsize;
3088 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3090 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3092 out->normal[0] = MSG_ReadLittleFloat(sb);
3093 out->normal[1] = MSG_ReadLittleFloat(sb);
3094 out->normal[2] = MSG_ReadLittleFloat(sb);
3095 out->dist = MSG_ReadLittleFloat(sb);
3096 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3101 static void Mod_Q1BSP_LoadMapBrushes(void)
3105 int submodel, numbrushes;
3106 qboolean firstbrush;
3107 char *text, *maptext;
3108 char mapfilename[MAX_QPATH];
3109 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3110 strlcat (mapfilename, ".map", sizeof (mapfilename));
3111 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3115 if (!COM_ParseToken_Simple(&data, false, false, true))
3120 if (!COM_ParseToken_Simple(&data, false, false, true))
3122 if (com_token[0] != '{')
3128 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3131 if (!COM_ParseToken_Simple(&data, false, false, true))
3133 if (com_token[0] == '}')
3134 break; // end of entity
3135 if (com_token[0] == '{')
3142 if (submodel > loadmodel->brush.numsubmodels)
3144 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3148 model = loadmodel->brush.submodels[submodel];
3155 if (!COM_ParseToken_Simple(&data, false, false, true))
3157 if (com_token[0] == '}')
3158 break; // end of brush
3159 // each brush face should be this format:
3160 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3161 // FIXME: support hl .map format
3162 for (pointnum = 0;pointnum < 3;pointnum++)
3164 COM_ParseToken_Simple(&data, false, false, true);
3165 for (componentnum = 0;componentnum < 3;componentnum++)
3167 COM_ParseToken_Simple(&data, false, false, true);
3168 point[pointnum][componentnum] = atof(com_token);
3170 COM_ParseToken_Simple(&data, false, false, true);
3172 COM_ParseToken_Simple(&data, false, false, true);
3173 strlcpy(facetexture, com_token, sizeof(facetexture));
3174 COM_ParseToken_Simple(&data, false, false, true);
3175 //scroll_s = atof(com_token);
3176 COM_ParseToken_Simple(&data, false, false, true);
3177 //scroll_t = atof(com_token);
3178 COM_ParseToken_Simple(&data, false, false, true);
3179 //rotate = atof(com_token);
3180 COM_ParseToken_Simple(&data, false, false, true);
3181 //scale_s = atof(com_token);
3182 COM_ParseToken_Simple(&data, false, false, true);
3183 //scale_t = atof(com_token);
3184 TriangleNormal(point[0], point[1], point[2], planenormal);
3185 VectorNormalizeDouble(planenormal);
3186 planedist = DotProduct(point[0], planenormal);
3187 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3197 #define MAX_PORTALPOINTS 64
3199 typedef struct portal_s
3202 mnode_t *nodes[2]; // [0] = front side of plane
3203 struct portal_s *next[2];
3205 double points[3*MAX_PORTALPOINTS];
3206 struct portal_s *chain; // all portals are linked into a list
3210 static memexpandablearray_t portalarray;
3212 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3214 // process only nodes (leafs already had their box calculated)
3218 // calculate children first
3219 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3220 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3222 // make combined bounding box from children
3223 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3224 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3225 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3226 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3227 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3228 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3231 static void Mod_Q1BSP_FinalizePortals(void)
3233 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3237 mleaf_t *leaf, *endleaf;
3239 // tally up portal and point counts and recalculate bounding boxes for all
3240 // leafs (because qbsp is very sloppy)
3241 leaf = loadmodel->brush.data_leafs;
3242 endleaf = leaf + loadmodel->brush.num_leafs;
3243 if (mod_recalculatenodeboxes.integer)
3245 for (;leaf < endleaf;leaf++)
3247 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3248 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3253 for (portalindex = 0;portalindex < portalrange;portalindex++)
3255 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3258 // note: this check must match the one below or it will usually corrupt memory
3259 // 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
3260 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3263 numpoints += p->numpoints * 2;
3266 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3267 loadmodel->brush.num_portals = numportals;
3268 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3269 loadmodel->brush.num_portalpoints = numpoints;
3270 // clear all leaf portal chains
3271 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3272 loadmodel->brush.data_leafs[i].portals = NULL;
3273 // process all portals in the global portal chain, while freeing them
3274 portal = loadmodel->brush.data_portals;
3275 point = loadmodel->brush.data_portalpoints;
3276 for (portalindex = 0;portalindex < portalrange;portalindex++)
3278 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3281 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3283 // note: this check must match the one above or it will usually corrupt memory
3284 // 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
3285 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3287 // first make the back to front portal(forward portal)
3288 portal->points = point;
3289 portal->numpoints = p->numpoints;
3290 portal->plane.dist = p->plane.dist;
3291 VectorCopy(p->plane.normal, portal->plane.normal);
3292 portal->here = (mleaf_t *)p->nodes[1];
3293 portal->past = (mleaf_t *)p->nodes[0];
3295 for (j = 0;j < portal->numpoints;j++)
3297 VectorCopy(p->points + j*3, point->position);
3300 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3301 PlaneClassify(&portal->plane);
3303 // link into leaf's portal chain
3304 portal->next = portal->here->portals;
3305 portal->here->portals = portal;
3307 // advance to next portal
3310 // then make the front to back portal(backward portal)
3311 portal->points = point;
3312 portal->numpoints = p->numpoints;
3313 portal->plane.dist = -p->plane.dist;
3314 VectorNegate(p->plane.normal, portal->plane.normal);
3315 portal->here = (mleaf_t *)p->nodes[0];
3316 portal->past = (mleaf_t *)p->nodes[1];
3318 for (j = portal->numpoints - 1;j >= 0;j--)
3320 VectorCopy(p->points + j*3, point->position);
3323 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3324 PlaneClassify(&portal->plane);
3326 // link into leaf's portal chain
3327 portal->next = portal->here->portals;
3328 portal->here->portals = portal;
3330 // advance to next portal
3333 // add the portal's polygon points to the leaf bounding boxes
3334 if (mod_recalculatenodeboxes.integer)
3336 for (i = 0;i < 2;i++)
3338 leaf = (mleaf_t *)p->nodes[i];
3339 for (j = 0;j < p->numpoints;j++)
3341 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3342 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3343 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3344 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3345 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3346 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3352 // now recalculate the node bounding boxes from the leafs
3353 if (mod_recalculatenodeboxes.integer)
3354 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3362 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3365 Host_Error("AddPortalToNodes: NULL front node");
3367 Host_Error("AddPortalToNodes: NULL back node");
3368 if (p->nodes[0] || p->nodes[1])
3369 Host_Error("AddPortalToNodes: already included");
3370 // 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
3372 p->nodes[0] = front;
3373 p->next[0] = (portal_t *)front->portals;
3374 front->portals = (mportal_t *)p;
3377 p->next[1] = (portal_t *)back->portals;
3378 back->portals = (mportal_t *)p;
3383 RemovePortalFromNode
3386 static void RemovePortalFromNodes(portal_t *portal)
3390 void **portalpointer;
3392 for (i = 0;i < 2;i++)
3394 node = portal->nodes[i];
3396 portalpointer = (void **) &node->portals;
3399 t = (portal_t *)*portalpointer;
3401 Host_Error("RemovePortalFromNodes: portal not in leaf");
3405 if (portal->nodes[0] == node)
3407 *portalpointer = portal->next[0];
3408 portal->nodes[0] = NULL;
3410 else if (portal->nodes[1] == node)
3412 *portalpointer = portal->next[1];
3413 portal->nodes[1] = NULL;
3416 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3420 if (t->nodes[0] == node)
3421 portalpointer = (void **) &t->next[0];
3422 else if (t->nodes[1] == node)
3423 portalpointer = (void **) &t->next[1];
3425 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3430 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3431 static double *portalpointsbuffer;
3432 static int portalpointsbufferoffset;
3433 static int portalpointsbuffersize;
3434 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3437 mnode_t *front, *back, *other_node;
3438 mplane_t clipplane, *plane;
3439 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3440 int numfrontpoints, numbackpoints;
3441 double *frontpoints, *backpoints;
3443 // if a leaf, we're done
3447 // get some space for our clipping operations to use
3448 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3450 portalpointsbuffersize = portalpointsbufferoffset * 2;
3451 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3453 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3454 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3455 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3456 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3458 plane = node->plane;
3460 front = node->children[0];
3461 back = node->children[1];
3463 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3465 // create the new portal by generating a polygon for the node plane,
3466 // and clipping it by all of the other portals(which came from nodes above this one)
3467 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3468 nodeportal->plane = *plane;
3470 // 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)
3471 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);
3472 nodeportal->numpoints = 4;
3473 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3474 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3476 clipplane = portal->plane;
3477 if (portal->nodes[0] == portal->nodes[1])
3478 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3479 if (portal->nodes[0] == node)
3481 else if (portal->nodes[1] == node)
3483 clipplane.dist = -clipplane.dist;
3484 VectorNegate(clipplane.normal, clipplane.normal);
3489 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3490 side = 0; // hush warning
3493 for (i = 0;i < nodeportal->numpoints*3;i++)
3494 frontpoints[i] = nodeportal->points[i];
3495 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);
3496 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3500 if (nodeportal->numpoints < 3)
3502 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3503 nodeportal->numpoints = 0;
3505 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3507 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3508 nodeportal->numpoints = 0;
3511 AddPortalToNodes(nodeportal, front, back);
3513 // split the portals of this node along this node's plane and assign them to the children of this node
3514 // (migrating the portals downward through the tree)
3515 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3517 if (portal->nodes[0] == portal->nodes[1])
3518 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3519 if (portal->nodes[0] == node)
3521 else if (portal->nodes[1] == node)
3525 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3526 side = 0; // hush warning
3528 nextportal = portal->next[side];
3529 if (!portal->numpoints)
3532 other_node = portal->nodes[!side];
3533 RemovePortalFromNodes(portal);
3535 // cut the portal into two portals, one on each side of the node plane
3536 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);
3538 if (!numfrontpoints)
3541 AddPortalToNodes(portal, back, other_node);
3543 AddPortalToNodes(portal, other_node, back);
3549 AddPortalToNodes(portal, front, other_node);
3551 AddPortalToNodes(portal, other_node, front);
3555 // the portal is split
3556 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3557 temp = splitportal->chain;
3558 *splitportal = *portal;
3559 splitportal->chain = temp;
3560 for (i = 0;i < numbackpoints*3;i++)
3561 splitportal->points[i] = backpoints[i];
3562 splitportal->numpoints = numbackpoints;
3563 for (i = 0;i < numfrontpoints*3;i++)
3564 portal->points[i] = frontpoints[i];
3565 portal->numpoints = numfrontpoints;
3569 AddPortalToNodes(portal, front, other_node);
3570 AddPortalToNodes(splitportal, back, other_node);
3574 AddPortalToNodes(portal, other_node, front);
3575 AddPortalToNodes(splitportal, other_node, back);
3579 Mod_Q1BSP_RecursiveNodePortals(front);
3580 Mod_Q1BSP_RecursiveNodePortals(back);
3582 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3585 static void Mod_Q1BSP_MakePortals(void)
3587 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3588 portalpointsbufferoffset = 0;
3589 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3590 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3591 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3592 Mem_Free(portalpointsbuffer);
3593 portalpointsbuffer = NULL;
3594 portalpointsbufferoffset = 0;
3595 portalpointsbuffersize = 0;
3596 Mod_Q1BSP_FinalizePortals();
3597 Mem_ExpandableArray_FreeArray(&portalarray);
3600 //Returns PVS data for a given point
3601 //(note: can return NULL)
3602 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3605 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3607 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3608 if (((mleaf_t *)node)->clusterindex >= 0)
3609 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3614 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)
3618 float d = PlaneDiff(org, node->plane);
3620 node = node->children[0];
3621 else if (d < -radius)
3622 node = node->children[1];
3625 // go down both sides
3626 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3627 node = node->children[1];
3630 // if this leaf is in a cluster, accumulate the pvs bits
3631 if (((mleaf_t *)node)->clusterindex >= 0)
3634 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3635 for (i = 0;i < pvsbytes;i++)
3636 pvsbuffer[i] |= pvs[i];
3640 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3641 //of the given point.
3642 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3644 int bytes = model->brush.num_pvsclusterbytes;
3645 bytes = min(bytes, pvsbufferlength);
3646 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3648 memset(pvsbuffer, 0xFF, bytes);
3652 memset(pvsbuffer, 0, bytes);
3653 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3657 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3662 VectorSubtract(inmaxs, inmins, size);
3663 if (cmodel->brush.ishlbsp)
3666 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3667 else if (size[0] <= 32)
3669 if (size[2] < 54) // pick the nearest of 36 or 72
3670 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3672 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3675 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3680 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3681 else if (size[0] <= 32)
3682 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3684 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3686 VectorCopy(inmins, outmins);
3687 VectorAdd(inmins, hull->clip_size, outmaxs);
3690 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3693 int numshadowmeshtriangles = 0;
3694 msurface_t *surface;
3695 if (cls.state == ca_dedicated)
3697 // make a single combined shadow mesh to allow optimized shadow volume creation
3699 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3701 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3702 numshadowmeshtriangles += surface->num_triangles;
3704 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3705 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3706 if (surface->num_triangles > 0)
3707 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));
3708 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3709 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3710 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3712 return numshadowmeshtriangles;
3715 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);
3717 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3720 sizebuf_t lumpsb[HEADER_LUMPS];
3722 float dist, modelyawradius, modelradius;
3723 msurface_t *surface;
3724 hullinfo_t hullinfo;
3725 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3726 model_brush_lightstyleinfo_t styleinfo[256];
3727 unsigned char *datapointer;
3730 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3732 mod->type = mod_brushq1;
3734 mod->brush.isbsp2 = false;
3735 mod->brush.ishlbsp = false;
3736 i = MSG_ReadLittleLong(&sb);
3740 mod->modeldatatypestring = "Q1BSP";
3743 mod->brush.ishlbsp = true;
3744 mod->modeldatatypestring = "HLBSP";
3746 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3747 mod->brush.isbsp2 = true;
3748 mod->modeldatatypestring = "Q1BSP2";
3751 mod->modeldatatypestring = "Unknown BSP";
3752 Host_Error("Mod_Q1BSP_Load: %s has wrong version number %i: supported versions are 29 (Quake), 30 (Half-Life), \"BSP2\"", mod->name, i);
3756 // fill in hull info
3757 VectorClear (hullinfo.hullsizes[0][0]);
3758 VectorClear (hullinfo.hullsizes[0][1]);
3759 if (mod->brush.ishlbsp)
3761 hullinfo.filehulls = 4;
3762 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3763 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3764 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3765 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3766 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3767 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3771 hullinfo.filehulls = 4;
3772 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3773 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3774 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3775 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3779 for (i = 0; i < HEADER_LUMPS; i++)
3781 int offset = MSG_ReadLittleLong(&sb);
3782 int size = MSG_ReadLittleLong(&sb);
3783 if (offset < 0 || offset + size > sb.cursize)
3784 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);
3785 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3788 mod->soundfromcenter = true;
3789 mod->TraceBox = Mod_Q1BSP_TraceBox;
3790 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
3791 mod->TraceLine = Mod_Q1BSP_TraceLineAgainstSurfaces; // LordHavoc: use the surface-hitting version of TraceLine in all cases
3793 mod->TraceLine = Mod_Q1BSP_TraceLine;
3794 mod->TracePoint = Mod_Q1BSP_TracePoint;
3795 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3796 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3797 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3798 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3799 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3800 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3801 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3802 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3803 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3804 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3805 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3806 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3807 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3808 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3809 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3810 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3811 mod->Draw = R_Q1BSP_Draw;
3812 mod->DrawDepth = R_Q1BSP_DrawDepth;
3813 mod->DrawDebug = R_Q1BSP_DrawDebug;
3814 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3815 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3816 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3817 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3818 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3819 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3820 mod->DrawLight = R_Q1BSP_DrawLight;
3824 mod->brush.qw_md4sum = 0;
3825 mod->brush.qw_md4sum2 = 0;
3826 for (i = 0;i < HEADER_LUMPS;i++)
3829 if (i == LUMP_ENTITIES)
3831 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3832 mod->brush.qw_md4sum ^= LittleLong(temp);
3833 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3835 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3838 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3839 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3840 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3841 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3842 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3843 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3844 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3845 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3846 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3847 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3848 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3849 // load submodels before leafs because they contain the number of vis leafs
3850 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3851 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3852 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3853 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3855 for (i = 0; i < HEADER_LUMPS; i++)
3856 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3857 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3859 // check if the map supports transparent water rendering
3860 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3862 if (mod->brushq1.data_compressedpvs)
3863 Mem_Free(mod->brushq1.data_compressedpvs);
3864 mod->brushq1.data_compressedpvs = NULL;
3865 mod->brushq1.num_compressedpvs = 0;
3867 Mod_Q1BSP_MakeHull0();
3868 if (mod_bsp_portalize.integer)
3869 Mod_Q1BSP_MakePortals();
3871 mod->numframes = 2; // regular and alternate animation
3874 // make a single combined shadow mesh to allow optimized shadow volume creation
3875 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3877 if (loadmodel->brush.numsubmodels)
3878 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3880 // LordHavoc: to clear the fog around the original quake submodel code, I
3882 // first of all, some background info on the submodels:
3883 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3884 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3885 // now the weird for loop itself:
3886 // the loop functions in an odd way, on each iteration it sets up the
3887 // current 'mod' model (which despite the confusing code IS the model of
3888 // the number i), at the end of the loop it duplicates the model to become
3889 // the next submodel, and loops back to set up the new submodel.
3891 // LordHavoc: now the explanation of my sane way (which works identically):
3892 // set up the world model, then on each submodel copy from the world model
3893 // and set up the submodel with the respective model info.
3894 totalstylesurfaces = 0;
3896 for (i = 0;i < mod->brush.numsubmodels;i++)
3898 memset(stylecounts, 0, sizeof(stylecounts));
3899 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3901 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3902 for (j = 0;j < MAXLIGHTMAPS;j++)
3903 stylecounts[surface->lightmapinfo->styles[j]]++;
3905 for (k = 0;k < 255;k++)
3909 totalstylesurfaces += stylecounts[k];
3912 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3913 for (i = 0;i < mod->brush.numsubmodels;i++)
3915 // LordHavoc: this code was originally at the end of this loop, but
3916 // has been transformed to something more readable at the start here.
3921 // duplicate the basic information
3922 dpsnprintf(name, sizeof(name), "*%i", i);
3923 mod = Mod_FindName(name, loadmodel->name);
3924 // copy the base model to this one
3926 // rename the clone back to its proper name
3927 strlcpy(mod->name, name, sizeof(mod->name));
3928 mod->brush.parentmodel = loadmodel;
3929 // textures and memory belong to the main model
3930 mod->texturepool = NULL;
3931 mod->mempool = NULL;
3932 mod->brush.GetPVS = NULL;
3933 mod->brush.FatPVS = NULL;
3934 mod->brush.BoxTouchingPVS = NULL;
3935 mod->brush.BoxTouchingLeafPVS = NULL;
3936 mod->brush.BoxTouchingVisibleLeafs = NULL;
3937 mod->brush.FindBoxClusters = NULL;
3938 mod->brush.LightPoint = NULL;
3939 mod->brush.AmbientSoundLevelsForPoint = NULL;
3942 mod->brush.submodel = i;
3944 if (loadmodel->brush.submodels)
3945 loadmodel->brush.submodels[i] = mod;
3947 bm = &mod->brushq1.submodels[i];
3949 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3950 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3952 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3953 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3956 mod->firstmodelsurface = bm->firstface;
3957 mod->nummodelsurfaces = bm->numfaces;
3959 // set node/leaf parents for this submodel
3960 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3962 // make the model surface list (used by shadowing/lighting)
3963 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3964 Mod_MakeSortedSurfaces(mod);
3966 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3967 // (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)
3968 VectorCopy(bm->mins, mod->normalmins);
3969 VectorCopy(bm->maxs, mod->normalmaxs);
3970 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3971 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3972 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3973 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3974 modelradius = modelyawradius + modelradius * modelradius;
3975 modelyawradius = sqrt(modelyawradius);
3976 modelradius = sqrt(modelradius);
3977 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3978 mod->yawmins[2] = mod->normalmins[2];
3979 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3980 mod->yawmaxs[2] = mod->normalmaxs[2];
3981 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3982 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3983 mod->radius = modelradius;
3984 mod->radius2 = modelradius * modelradius;
3986 // this gets altered below if sky or water is used
3987 mod->DrawSky = NULL;
3988 mod->DrawAddWaterPlanes = NULL;
3990 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3991 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3992 if (mod->nummodelsurfaces)
3994 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3995 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3997 if (j < mod->nummodelsurfaces)
3998 mod->DrawSky = R_Q1BSP_DrawSky;
4000 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4001 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4003 if (j < mod->nummodelsurfaces)
4004 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4006 // build lightstyle update chains
4007 // (used to rapidly mark lightmapupdateflags on many surfaces
4008 // when d_lightstylevalue changes)
4009 memset(stylecounts, 0, sizeof(stylecounts));
4010 for (k = 0;k < mod->nummodelsurfaces;k++)
4012 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4013 for (j = 0;j < MAXLIGHTMAPS;j++)
4014 stylecounts[surface->lightmapinfo->styles[j]]++;
4016 mod->brushq1.num_lightstyles = 0;
4017 for (k = 0;k < 255;k++)
4021 styleinfo[mod->brushq1.num_lightstyles].style = k;
4022 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4023 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4024 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4025 remapstyles[k] = mod->brushq1.num_lightstyles;
4026 mod->brushq1.num_lightstyles++;
4029 for (k = 0;k < mod->nummodelsurfaces;k++)
4031 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4032 for (j = 0;j < MAXLIGHTMAPS;j++)
4034 if (surface->lightmapinfo->styles[j] != 255)
4036 int r = remapstyles[surface->lightmapinfo->styles[j]];
4037 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4041 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4042 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4046 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4047 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4049 //mod->brushq1.num_visleafs = bm->visleafs;
4051 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4052 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4054 if (mod_q1bsp_polygoncollisions.integer)
4056 mod->collision_bih = mod->render_bih;
4057 // point traces and contents checks still use the bsp tree
4058 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4059 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4060 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4061 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4064 // generate VBOs and other shared data before cloning submodels
4068 Mod_Q1BSP_LoadMapBrushes();
4069 //Mod_Q1BSP_ProcessLightList();
4073 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);
4076 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4080 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4087 in = (void *)(mod_base + l->fileofs);
4088 if (l->filelen % sizeof(*in))
4089 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4090 count = l->filelen / sizeof(*in);
4091 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4094 loadmodel->num = count;
4096 for (i = 0;i < count;i++, in++, out++)
4102 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4109 in = (void *)(mod_base + l->fileofs);
4110 if (l->filelen % sizeof(*in))
4111 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4112 count = l->filelen / sizeof(*in);
4113 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4116 loadmodel->num = count;
4118 for (i = 0;i < count;i++, in++, out++)
4124 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4131 in = (void *)(mod_base + l->fileofs);
4132 if (l->filelen % sizeof(*in))
4133 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4134 count = l->filelen / sizeof(*in);
4135 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4138 loadmodel->num = count;
4140 for (i = 0;i < count;i++, in++, out++)
4146 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4153 in = (void *)(mod_base + l->fileofs);
4154 if (l->filelen % sizeof(*in))
4155 Host_Error("Mod_Q2BSP_LoadNodes: 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_LoadTexInfo(lump_t *l)
4175 in = (void *)(mod_base + l->fileofs);
4176 if (l->filelen % sizeof(*in))
4177 Host_Error("Mod_Q2BSP_LoadTexInfo: 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_LoadFaces(lump_t *l)
4197 in = (void *)(mod_base + l->fileofs);
4198 if (l->filelen % sizeof(*in))
4199 Host_Error("Mod_Q2BSP_LoadFaces: 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_LoadLighting(lump_t *l)
4219 in = (void *)(mod_base + l->fileofs);
4220 if (l->filelen % sizeof(*in))
4221 Host_Error("Mod_Q2BSP_LoadLighting: 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_LoadLeafs(lump_t *l)
4241 in = (void *)(mod_base + l->fileofs);
4242 if (l->filelen % sizeof(*in))
4243 Host_Error("Mod_Q2BSP_LoadLeafs: 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_LoadLeafFaces(lump_t *l)
4263 in = (void *)(mod_base + l->fileofs);
4264 if (l->filelen % sizeof(*in))
4265 Host_Error("Mod_Q2BSP_LoadLeafFaces: 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_LoadLeafBrushes(lump_t *l)
4285 in = (void *)(mod_base + l->fileofs);
4286 if (l->filelen % sizeof(*in))
4287 Host_Error("Mod_Q2BSP_LoadLeafBrushes: 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_LoadEdges(lump_t *l)
4307 in = (void *)(mod_base + l->fileofs);
4308 if (l->filelen % sizeof(*in))
4309 Host_Error("Mod_Q2BSP_LoadEdges: 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_LoadSurfEdges(lump_t *l)
4329 in = (void *)(mod_base + l->fileofs);
4330 if (l->filelen % sizeof(*in))
4331 Host_Error("Mod_Q2BSP_LoadSurfEdges: 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_LoadBrushes(lump_t *l)
4351 in = (void *)(mod_base + l->fileofs);
4352 if (l->filelen % sizeof(*in))
4353 Host_Error("Mod_Q2BSP_LoadBrushes: 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_LoadBrushSides(lump_t *l)
4373 in = (void *)(mod_base + l->fileofs);
4374 if (l->filelen % sizeof(*in))
4375 Host_Error("Mod_Q2BSP_LoadBrushSides: 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_LoadAreas(lump_t *l)
4395 in = (void *)(mod_base + l->fileofs);
4396 if (l->filelen % sizeof(*in))
4397 Host_Error("Mod_Q2BSP_LoadAreas: 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_LoadAreaPortals(lump_t *l)
4417 in = (void *)(mod_base + l->fileofs);
4418 if (l->filelen % sizeof(*in))
4419 Host_Error("Mod_Q2BSP_LoadAreaPortals: 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_LoadModels(lump_t *l)
4439 in = (void *)(mod_base + l->fileofs);
4440 if (l->filelen % sizeof(*in))
4441 Host_Error("Mod_Q2BSP_LoadModels: 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_Load(dp_model_t *mod, void *buffer, void *bufferend)
4457 q2dheader_t *header;
4459 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4461 mod->modeldatatypestring = "Q2BSP";
4463 mod->type = mod_brushq2;
4465 header = (q2dheader_t *)buffer;
4467 i = LittleLong(header->version);
4468 if (i != Q2BSPVERSION)
4469 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4471 mod_base = (unsigned char *)header;
4473 // swap all the lumps
4474 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4475 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4477 mod->brush.qw_md4sum = 0;
4478 mod->brush.qw_md4sum2 = 0;
4479 for (i = 0;i < Q2HEADER_LUMPS;i++)
4481 if (i == Q2LUMP_ENTITIES)
4483 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4484 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4486 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4489 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4490 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4491 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4492 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4493 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4494 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4495 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4496 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4497 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4498 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4499 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4500 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4501 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4502 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4503 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4504 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4505 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4506 // LordHavoc: must go last because this makes the submodels
4507 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4510 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4511 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4513 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4516 char key[128], value[MAX_INPUTLINE];
4518 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4519 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4520 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4523 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4524 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4525 loadmodel->brush.entities[l->filelen] = 0;
4526 data = loadmodel->brush.entities;
4527 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4528 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4529 loadmodel->brushq3.deluxemapping = false;
4530 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4534 if (!COM_ParseToken_Simple(&data, false, false, true))
4536 if (com_token[0] == '}')
4537 break; // end of worldspawn
4538 if (com_token[0] == '_')
4539 strlcpy(key, com_token + 1, sizeof(key));
4541 strlcpy(key, com_token, sizeof(key));
4542 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4543 key[strlen(key)-1] = 0;
4544 if (!COM_ParseToken_Simple(&data, false, false, true))
4546 strlcpy(value, com_token, sizeof(value));
4547 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4549 #if _MSC_VER >= 1400
4550 #define sscanf sscanf_s
4553 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4554 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4556 VectorSet(v, 64, 64, 128);
4557 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4558 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]);
4559 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4560 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4563 else if (!strcmp("deluxeMaps", key))
4565 if (!strcmp(com_token, "1"))
4567 loadmodel->brushq3.deluxemapping = true;
4568 loadmodel->brushq3.deluxemapping_modelspace = true;
4570 else if (!strcmp(com_token, "2"))
4572 loadmodel->brushq3.deluxemapping = true;
4573 loadmodel->brushq3.deluxemapping_modelspace = false;
4580 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4586 in = (q3dtexture_t *)(mod_base + l->fileofs);
4587 if (l->filelen % sizeof(*in))
4588 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4589 count = l->filelen / sizeof(*in);
4590 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4592 loadmodel->data_textures = out;
4593 loadmodel->num_textures = count;
4594 loadmodel->num_texturesperskin = loadmodel->num_textures;
4596 for (i = 0;i < count;i++)
4598 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4599 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4600 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4601 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4602 // restore the surfaceflags and supercontents
4603 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4604 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4608 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4614 in = (q3dplane_t *)(mod_base + l->fileofs);
4615 if (l->filelen % sizeof(*in))
4616 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4617 count = l->filelen / sizeof(*in);
4618 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4620 loadmodel->brush.data_planes = out;
4621 loadmodel->brush.num_planes = count;
4623 for (i = 0;i < count;i++, in++, out++)
4625 out->normal[0] = LittleFloat(in->normal[0]);
4626 out->normal[1] = LittleFloat(in->normal[1]);
4627 out->normal[2] = LittleFloat(in->normal[2]);
4628 out->dist = LittleFloat(in->dist);
4633 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4636 q3mbrushside_t *out;
4639 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4640 if (l->filelen % sizeof(*in))
4641 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4642 count = l->filelen / sizeof(*in);
4643 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4645 loadmodel->brush.data_brushsides = out;
4646 loadmodel->brush.num_brushsides = count;
4648 for (i = 0;i < count;i++, in++, out++)
4650 n = LittleLong(in->planeindex);
4651 if (n < 0 || n >= loadmodel->brush.num_planes)
4652 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4653 out->plane = loadmodel->brush.data_planes + n;
4654 n = LittleLong(in->textureindex);
4655 if (n < 0 || n >= loadmodel->num_textures)
4656 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4657 out->texture = loadmodel->data_textures + n;
4661 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4663 q3dbrushside_ig_t *in;
4664 q3mbrushside_t *out;
4667 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4668 if (l->filelen % sizeof(*in))
4669 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4670 count = l->filelen / sizeof(*in);
4671 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4673 loadmodel->brush.data_brushsides = out;
4674 loadmodel->brush.num_brushsides = count;
4676 for (i = 0;i < count;i++, in++, out++)
4678 n = LittleLong(in->planeindex);
4679 if (n < 0 || n >= loadmodel->brush.num_planes)
4680 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4681 out->plane = loadmodel->brush.data_planes + n;
4682 n = LittleLong(in->textureindex);
4683 if (n < 0 || n >= loadmodel->num_textures)
4684 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4685 out->texture = loadmodel->data_textures + n;
4689 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4693 int i, j, n, c, count, maxplanes, q3surfaceflags;
4694 colplanef_t *planes;
4696 in = (q3dbrush_t *)(mod_base + l->fileofs);
4697 if (l->filelen % sizeof(*in))
4698 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4699 count = l->filelen / sizeof(*in);
4700 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4702 loadmodel->brush.data_brushes = out;
4703 loadmodel->brush.num_brushes = count;
4708 for (i = 0;i < count;i++, in++, out++)
4710 n = LittleLong(in->firstbrushside);
4711 c = LittleLong(in->numbrushsides);
4712 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4713 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4714 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4715 out->numbrushsides = c;
4716 n = LittleLong(in->textureindex);
4717 if (n < 0 || n >= loadmodel->num_textures)
4718 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4719 out->texture = loadmodel->data_textures + n;
4721 // make a list of mplane_t structs to construct a colbrush from
4722 if (maxplanes < out->numbrushsides)
4724 maxplanes = out->numbrushsides;
4727 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4730 for (j = 0;j < out->numbrushsides;j++)
4732 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4733 planes[j].dist = out->firstbrushside[j].plane->dist;
4734 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4735 planes[j].texture = out->firstbrushside[j].texture;
4736 q3surfaceflags |= planes[j].q3surfaceflags;
4738 // make the colbrush from the planes
4739 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4741 // this whole loop can take a while (e.g. on redstarrepublic4)
4742 CL_KeepaliveMessage(false);
4748 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4754 in = (q3deffect_t *)(mod_base + l->fileofs);
4755 if (l->filelen % sizeof(*in))
4756 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4757 count = l->filelen / sizeof(*in);
4758 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4760 loadmodel->brushq3.data_effects = out;
4761 loadmodel->brushq3.num_effects = count;
4763 for (i = 0;i < count;i++, in++, out++)
4765 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4766 n = LittleLong(in->brushindex);
4767 if (n >= loadmodel->brush.num_brushes)
4769 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4772 out->brushindex = n;
4773 out->unknown = LittleLong(in->unknown);
4777 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4782 in = (q3dvertex_t *)(mod_base + l->fileofs);
4783 if (l->filelen % sizeof(*in))
4784 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4785 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4786 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4787 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4788 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4789 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4790 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4792 for (i = 0;i < count;i++, in++)
4794 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4795 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4796 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4797 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4798 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4799 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4800 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4801 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4802 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4803 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4804 // svector/tvector are calculated later in face loading
4805 if(mod_q3bsp_sRGBlightmaps.integer)
4807 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
4808 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
4809 // working like this may be odd, but matches q3map2 -gamma 2.2
4810 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4812 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4813 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4814 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4815 // we fix the brightness consistently via lightmapscale
4819 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
4820 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
4821 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
4826 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4828 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4829 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4830 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4834 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4835 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4836 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4839 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4840 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4841 loadmodel->lit = true;
4845 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4851 in = (int *)(mod_base + l->fileofs);
4852 if (l->filelen % sizeof(int[3]))
4853 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4854 count = l->filelen / sizeof(*in);
4856 if(!loadmodel->brushq3.num_vertices)
4859 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4860 loadmodel->brushq3.num_triangles = 0;
4864 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4865 loadmodel->brushq3.num_triangles = count / 3;
4866 loadmodel->brushq3.data_element3i = out;
4868 for (i = 0;i < count;i++, in++, out++)
4870 *out = LittleLong(*in);
4871 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4873 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4879 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4881 q3dlightmap_t *input_pointer;
4899 int mergedrowsxcolumns;
4904 unsigned char *mergedpixels;
4905 unsigned char *mergeddeluxepixels;
4906 unsigned char *mergebuf;
4907 char mapname[MAX_QPATH];
4909 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4912 // defaults for q3bsp
4919 loadmodel->brushq3.lightmapsize = 128;
4921 if (cls.state == ca_dedicated)
4924 if(mod_q3bsp_nolightmaps.integer)
4930 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4931 if (developer_loading.integer)
4932 Con_Printf("Using internal lightmaps\n");
4933 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4934 if (l->filelen % sizeof(*input_pointer))
4935 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4936 count = l->filelen / sizeof(*input_pointer);
4937 for(i = 0; i < count; ++i)
4938 inpixels[i] = input_pointer[i].rgb;
4942 // no internal lightmaps
4943 // try external lightmaps
4944 if (developer_loading.integer)
4945 Con_Printf("Using external lightmaps\n");
4946 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4947 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
4951 // using EXTERNAL lightmaps instead
4952 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4954 Mem_Free(inpixels[0]);
4955 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4965 for(count = 1; ; ++count)
4967 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
4968 if(!inpixels[count])
4969 break; // we got all of them
4970 if(image_width != size || image_height != size)
4972 Mem_Free(inpixels[count]);
4973 inpixels[count] = NULL;
4974 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);
4980 loadmodel->brushq3.lightmapsize = size;
4981 loadmodel->brushq3.num_originallightmaps = count;
4983 // now check the surfaces to see if any of them index an odd numbered
4984 // lightmap, if so this is not a deluxemapped bsp file
4986 // also check what lightmaps are actually used, because q3map2 sometimes
4987 // (always?) makes an unused one at the end, which
4988 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4989 // reason when only one lightmap is used, which can throw off the
4990 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4991 // to see if the second lightmap is blank, if so it is not deluxemapped.
4992 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4993 // in Mod_Q3BSP_LoadEntities was failed
4994 if (!loadmodel->brushq3.deluxemapping)
4996 loadmodel->brushq3.deluxemapping = !(count & 1);
4997 loadmodel->brushq3.deluxemapping_modelspace = true;
4999 if (loadmodel->brushq3.deluxemapping)
5001 int facecount = faceslump->filelen / sizeof(q3dface_t);
5002 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5003 for (i = 0;i < facecount;i++)
5005 j = LittleLong(faces[i].lightmapindex);
5008 endlightmap = max(endlightmap, j + 1);
5009 if ((j & 1) || j + 1 >= count)
5011 loadmodel->brushq3.deluxemapping = false;
5018 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5019 // reason when only one lightmap is used, which can throw off the
5020 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5021 // to see if the second lightmap is blank, if so it is not deluxemapped.
5023 // further research has shown q3map2 sometimes creates a deluxemap and two
5024 // blank lightmaps, which must be handled properly as well
5025 if (endlightmap == 1 && count > 1)
5028 for (i = 0;i < size*size;i++)
5030 if (c[bytesperpixel*i + rgbmap[0]])
5032 if (c[bytesperpixel*i + rgbmap[1]])
5034 if (c[bytesperpixel*i + rgbmap[2]])
5039 // all pixels in the unused lightmap were black...
5040 loadmodel->brushq3.deluxemapping = false;
5045 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5047 // figure out what the most reasonable merge power is within limits
5049 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5050 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5052 // figure out how big the merged texture has to be
5053 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5054 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5055 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5057 mergedwidth = mergegoal;
5058 mergedheight = mergegoal;
5059 // choose non-square size (2x1 aspect) if only half the space is used;
5060 // this really only happens when the entire set fits in one texture, if
5061 // there are multiple textures, we don't worry about shrinking the last
5062 // one to fit, because the driver prefers the same texture size on
5063 // consecutive draw calls...
5064 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5067 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5068 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5069 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5070 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5071 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5072 loadmodel->brushq3.num_lightmapmergedheightpower++;
5073 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5075 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5076 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5077 powerxy = powerx+powery;
5078 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5080 mergedcolumns = 1 << powerx;
5081 mergedrows = 1 << powery;
5082 mergedrowsxcolumns = 1 << powerxy;
5084 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5085 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5086 if (loadmodel->brushq3.deluxemapping)
5087 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5089 // allocate a texture pool if we need it
5090 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5091 loadmodel->texturepool = R_AllocTexturePool();
5093 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5094 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5095 for (i = 0;i < count;i++)
5097 // figure out which merged lightmap texture this fits into
5098 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5099 lightmapindex = i >> powerdxy;
5101 // choose the destination address
5102 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5103 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5104 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5105 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);
5107 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5108 for (j = 0;j < size;j++)
5109 for (k = 0;k < size;k++)
5111 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5112 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5113 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5114 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5117 // upload texture if this was the last tile being written to the texture
5118 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5120 if (loadmodel->brushq3.deluxemapping && (i & 1))
5121 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);
5124 if(mod_q3bsp_sRGBlightmaps.integer)
5127 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5129 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5130 // we fix the brightness consistently via lightmapscale
5133 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5134 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);
5138 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5139 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5140 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);
5146 if (mergeddeluxepixels)
5147 Mem_Free(mergeddeluxepixels);
5148 Mem_Free(mergedpixels);
5151 for(i = 0; i < count; ++i)
5152 Mem_Free(inpixels[i]);
5156 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5161 *collisionstride = stride;
5164 cnt = (num_triangles + stride - 1) / stride;
5165 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5166 for(j = 0; j < cnt; ++j)
5168 mins = &((*collisionbbox6f)[6 * j + 0]);
5169 maxs = &((*collisionbbox6f)[6 * j + 3]);
5170 for(k = 0; k < stride; ++k)
5172 tri = j * stride + k;
5173 if(tri >= num_triangles)
5175 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5176 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5177 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5178 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5179 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5180 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5181 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5182 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5183 if(vert[0] < mins[0]) mins[0] = vert[0];
5184 if(vert[1] < mins[1]) mins[1] = vert[1];
5185 if(vert[2] < mins[2]) mins[2] = vert[2];
5186 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5187 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5188 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5189 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5190 if(vert[0] < mins[0]) mins[0] = vert[0];
5191 if(vert[1] < mins[1]) mins[1] = vert[1];
5192 if(vert[2] < mins[2]) mins[2] = vert[2];
5193 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5194 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5195 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5200 *collisionbbox6f = NULL;
5203 typedef struct patchtess_s
5207 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5210 float *originalvertex3f;
5213 #define PATCHTESS_SAME_LODGROUP(a,b) \
5215 (a).lodgroup[0] == (b).lodgroup[0] && \
5216 (a).lodgroup[1] == (b).lodgroup[1] && \
5217 (a).lodgroup[2] == (b).lodgroup[2] && \
5218 (a).lodgroup[3] == (b).lodgroup[3] && \
5219 (a).lodgroup[4] == (b).lodgroup[4] && \
5220 (a).lodgroup[5] == (b).lodgroup[5] \
5223 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5225 q3dface_t *in, *oldin;
5226 msurface_t *out, *oldout;
5227 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;
5228 float lightmaptcbase[2], lightmaptcscale[2];
5229 //int *originalelement3i;
5230 //int *originalneighbor3i;
5231 float *originalvertex3f;
5232 //float *originalsvector3f;
5233 //float *originaltvector3f;
5234 float *originalnormal3f;
5235 float *originalcolor4f;
5236 float *originaltexcoordtexture2f;
5237 float *originaltexcoordlightmap2f;
5238 float *surfacecollisionvertex3f;
5239 int *surfacecollisionelement3i;
5241 patchtess_t *patchtess = NULL;
5242 int patchtesscount = 0;
5245 in = (q3dface_t *)(mod_base + l->fileofs);
5246 if (l->filelen % sizeof(*in))
5247 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5248 count = l->filelen / sizeof(*in);
5249 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5251 loadmodel->data_surfaces = out;
5252 loadmodel->num_surfaces = count;
5255 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5263 for (;i < count;i++, in++, out++)
5265 // check face type first
5266 type = LittleLong(in->type);
5267 if (type != Q3FACETYPE_FLAT
5268 && type != Q3FACETYPE_PATCH
5269 && type != Q3FACETYPE_MESH
5270 && type != Q3FACETYPE_FLARE)
5272 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5276 n = LittleLong(in->textureindex);
5277 if (n < 0 || n >= loadmodel->num_textures)
5279 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5282 out->texture = loadmodel->data_textures + n;
5283 n = LittleLong(in->effectindex);
5284 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5286 if (developer_extra.integer)
5287 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5293 out->effect = loadmodel->brushq3.data_effects + n;
5295 if (cls.state != ca_dedicated)
5297 out->lightmaptexture = NULL;
5298 out->deluxemaptexture = r_texture_blanknormalmap;
5299 n = LittleLong(in->lightmapindex);
5302 else if (n >= loadmodel->brushq3.num_originallightmaps)
5304 if(loadmodel->brushq3.num_originallightmaps != 0)
5305 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5310 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5311 if (loadmodel->brushq3.deluxemapping)
5312 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5313 loadmodel->lit = true;
5317 firstvertex = LittleLong(in->firstvertex);
5318 numvertices = LittleLong(in->numvertices);
5319 firstelement = LittleLong(in->firstelement);
5320 numtriangles = LittleLong(in->numelements) / 3;
5321 if (numtriangles * 3 != LittleLong(in->numelements))
5323 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));
5326 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5328 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);
5331 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5333 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);
5338 case Q3FACETYPE_FLAT:
5339 case Q3FACETYPE_MESH:
5340 // no processing necessary
5342 case Q3FACETYPE_PATCH:
5343 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5344 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5345 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))
5347 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5350 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5352 // convert patch to Q3FACETYPE_MESH
5353 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5354 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5355 // bound to user settings
5356 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5357 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5358 // bound to sanity settings
5359 xtess = bound(0, xtess, 1024);
5360 ytess = bound(0, ytess, 1024);
5362 // lower quality collision patches! Same procedure as before, but different cvars
5363 // convert patch to Q3FACETYPE_MESH
5364 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5365 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5366 // bound to user settings
5367 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5368 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5369 // bound to sanity settings
5370 cxtess = bound(0, cxtess, 1024);
5371 cytess = bound(0, cytess, 1024);
5373 // store it for the LOD grouping step
5374 patchtess[patchtesscount].info.xsize = patchsize[0];
5375 patchtess[patchtesscount].info.ysize = patchsize[1];
5376 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5377 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5378 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5379 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5381 patchtess[patchtesscount].surface_id = i;
5382 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5383 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5384 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5385 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5386 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5387 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5388 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5391 case Q3FACETYPE_FLARE:
5392 if (developer_extra.integer)
5393 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5397 out->num_vertices = numvertices;
5398 out->num_triangles = numtriangles;
5399 meshvertices += out->num_vertices;
5400 meshtriangles += out->num_triangles;
5403 // Fix patches tesselations so that they make no seams
5407 for(i = 0; i < patchtesscount; ++i)
5409 for(j = i+1; j < patchtesscount; ++j)
5411 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5414 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5421 // Calculate resulting number of triangles
5422 collisionvertices = 0;
5423 collisiontriangles = 0;
5424 for(i = 0; i < patchtesscount; ++i)
5426 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5427 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5428 numvertices = finalwidth * finalheight;
5429 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5431 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5432 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5433 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5434 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5436 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5437 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5438 numvertices = finalwidth * finalheight;
5439 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5441 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5442 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5443 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5444 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5450 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5451 if (collisiontriangles)
5453 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5454 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5458 collisionvertices = 0;
5459 collisiontriangles = 0;
5460 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5462 if (out->num_vertices < 3 || out->num_triangles < 1)
5465 type = LittleLong(in->type);
5466 firstvertex = LittleLong(in->firstvertex);
5467 firstelement = LittleLong(in->firstelement);
5468 out->num_firstvertex = meshvertices;
5469 out->num_firsttriangle = meshtriangles;
5470 out->num_firstcollisiontriangle = collisiontriangles;
5473 case Q3FACETYPE_FLAT:
5474 case Q3FACETYPE_MESH:
5475 // no processing necessary, except for lightmap merging
5476 for (j = 0;j < out->num_vertices;j++)
5478 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5479 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5480 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5481 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5482 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5483 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5484 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5485 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5486 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5487 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5488 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5489 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5490 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5491 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5493 for (j = 0;j < out->num_triangles*3;j++)
5494 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5496 case Q3FACETYPE_PATCH:
5497 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5498 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5499 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5500 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5501 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5502 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5503 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5505 xtess = ytess = cxtess = cytess = -1;
5506 for(j = 0; j < patchtesscount; ++j)
5507 if(patchtess[j].surface_id == i)
5509 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5510 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5511 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5512 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5517 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5518 xtess = ytess = cxtess = cytess = 0;
5521 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5522 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5523 finalvertices = finalwidth * finalheight;
5524 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5525 type = Q3FACETYPE_MESH;
5526 // generate geometry
5527 // (note: normals are skipped because they get recalculated)
5528 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5529 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5530 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5531 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5532 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5533 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5535 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);
5537 if (developer_extra.integer)
5539 if (out->num_triangles < finaltriangles)
5540 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);
5542 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);
5544 // q3map does not put in collision brushes for curves... ugh
5545 // build the lower quality collision geometry
5546 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5547 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5548 finalvertices = finalwidth * finalheight;
5549 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5551 // legacy collision geometry implementation
5552 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5553 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5554 out->num_collisionvertices = finalvertices;
5555 out->num_collisiontriangles = finaltriangles;
5556 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5557 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5559 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5560 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5562 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5564 // now optimize the collision mesh by finding triangle bboxes...
5565 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5566 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);
5568 // store collision geometry for BIH collision tree
5569 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5570 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5571 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5572 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5573 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5575 // remove this once the legacy code is removed
5577 int nc = out->num_collisiontriangles;
5579 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5581 if(nc != out->num_collisiontriangles)
5583 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5588 if (developer_extra.integer)
5589 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);
5591 collisionvertices += finalvertices;
5592 collisiontriangles += out->num_collisiontriangles;
5597 meshvertices += out->num_vertices;
5598 meshtriangles += out->num_triangles;
5599 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5600 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)
5602 if (invalidelements)
5604 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);
5605 for (j = 0;j < out->num_triangles * 3;j++)
5607 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5608 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)
5609 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5613 // calculate a bounding box
5614 VectorClear(out->mins);
5615 VectorClear(out->maxs);
5616 if (out->num_vertices)
5618 if (cls.state != ca_dedicated && out->lightmaptexture)
5620 // figure out which part of the merged lightmap this fits into
5621 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5622 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5623 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5624 lightmapindex &= mergewidth * mergeheight - 1;
5625 lightmaptcscale[0] = 1.0f / mergewidth;
5626 lightmaptcscale[1] = 1.0f / mergeheight;
5627 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5628 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5629 // modify the lightmap texcoords to match this region of the merged lightmap
5630 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5632 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5633 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5636 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5637 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5638 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5640 out->mins[0] = min(out->mins[0], v[0]);
5641 out->maxs[0] = max(out->maxs[0], v[0]);
5642 out->mins[1] = min(out->mins[1], v[1]);
5643 out->maxs[1] = max(out->maxs[1], v[1]);
5644 out->mins[2] = min(out->mins[2], v[2]);
5645 out->maxs[2] = max(out->maxs[2], v[2]);
5647 out->mins[0] -= 1.0f;
5648 out->mins[1] -= 1.0f;
5649 out->mins[2] -= 1.0f;
5650 out->maxs[0] += 1.0f;
5651 out->maxs[1] += 1.0f;
5652 out->maxs[2] += 1.0f;
5654 // set lightmap styles for consistency with q1bsp
5655 //out->lightmapinfo->styles[0] = 0;
5656 //out->lightmapinfo->styles[1] = 255;
5657 //out->lightmapinfo->styles[2] = 255;
5658 //out->lightmapinfo->styles[3] = 255;
5663 for (;i < count;i++, out++)
5665 if(out->num_vertices && out->num_triangles)
5667 if(out->num_vertices == 0)
5669 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5670 if(out->num_triangles == 0)
5671 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5673 else if(out->num_triangles == 0)
5674 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)",
5675 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5676 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5677 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5680 // for per pixel lighting
5681 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);
5683 // generate ushort elements array if possible
5684 if (loadmodel->surfmesh.data_element3s)
5685 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5686 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5688 // free the no longer needed vertex data
5689 loadmodel->brushq3.num_vertices = 0;
5690 if (loadmodel->brushq3.data_vertex3f)
5691 Mem_Free(loadmodel->brushq3.data_vertex3f);
5692 loadmodel->brushq3.data_vertex3f = NULL;
5693 loadmodel->brushq3.data_normal3f = NULL;
5694 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5695 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5696 loadmodel->brushq3.data_color4f = NULL;
5697 // free the no longer needed triangle data
5698 loadmodel->brushq3.num_triangles = 0;
5699 if (loadmodel->brushq3.data_element3i)
5700 Mem_Free(loadmodel->brushq3.data_element3i);
5701 loadmodel->brushq3.data_element3i = NULL;
5704 Mem_Free(patchtess);
5707 static void Mod_Q3BSP_LoadModels(lump_t *l)
5711 int i, j, n, c, count;
5713 in = (q3dmodel_t *)(mod_base + l->fileofs);
5714 if (l->filelen % sizeof(*in))
5715 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5716 count = l->filelen / sizeof(*in);
5717 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5719 loadmodel->brushq3.data_models = out;
5720 loadmodel->brushq3.num_models = count;
5722 for (i = 0;i < count;i++, in++, out++)
5724 for (j = 0;j < 3;j++)
5726 out->mins[j] = LittleFloat(in->mins[j]);
5727 out->maxs[j] = LittleFloat(in->maxs[j]);
5729 n = LittleLong(in->firstface);
5730 c = LittleLong(in->numfaces);
5731 if (n < 0 || n + c > loadmodel->num_surfaces)
5732 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5735 n = LittleLong(in->firstbrush);
5736 c = LittleLong(in->numbrushes);
5737 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5738 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5739 out->firstbrush = n;
5740 out->numbrushes = c;
5744 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5750 in = (int *)(mod_base + l->fileofs);
5751 if (l->filelen % sizeof(*in))
5752 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5753 count = l->filelen / sizeof(*in);
5754 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5756 loadmodel->brush.data_leafbrushes = out;
5757 loadmodel->brush.num_leafbrushes = count;
5759 for (i = 0;i < count;i++, in++, out++)
5761 n = LittleLong(*in);
5762 if (n < 0 || n >= loadmodel->brush.num_brushes)
5763 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5768 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5774 in = (int *)(mod_base + l->fileofs);
5775 if (l->filelen % sizeof(*in))
5776 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5777 count = l->filelen / sizeof(*in);
5778 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5780 loadmodel->brush.data_leafsurfaces = out;
5781 loadmodel->brush.num_leafsurfaces = count;
5783 for (i = 0;i < count;i++, in++, out++)
5785 n = LittleLong(*in);
5786 if (n < 0 || n >= loadmodel->num_surfaces)
5787 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5792 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5796 int i, j, n, c, count;
5798 in = (q3dleaf_t *)(mod_base + l->fileofs);
5799 if (l->filelen % sizeof(*in))
5800 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5801 count = l->filelen / sizeof(*in);
5802 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5804 loadmodel->brush.data_leafs = out;
5805 loadmodel->brush.num_leafs = count;
5807 for (i = 0;i < count;i++, in++, out++)
5811 out->clusterindex = LittleLong(in->clusterindex);
5812 out->areaindex = LittleLong(in->areaindex);
5813 for (j = 0;j < 3;j++)
5815 // yes the mins/maxs are ints
5816 out->mins[j] = LittleLong(in->mins[j]) - 1;
5817 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5819 n = LittleLong(in->firstleafface);
5820 c = LittleLong(in->numleaffaces);
5821 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5822 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5823 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5824 out->numleafsurfaces = c;
5825 n = LittleLong(in->firstleafbrush);
5826 c = LittleLong(in->numleafbrushes);
5827 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5828 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5829 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5830 out->numleafbrushes = c;
5834 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5840 in = (q3dnode_t *)(mod_base + l->fileofs);
5841 if (l->filelen % sizeof(*in))
5842 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5843 count = l->filelen / sizeof(*in);
5845 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5846 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5848 loadmodel->brush.data_nodes = out;
5849 loadmodel->brush.num_nodes = count;
5851 for (i = 0;i < count;i++, in++, out++)
5854 n = LittleLong(in->planeindex);
5855 if (n < 0 || n >= loadmodel->brush.num_planes)
5856 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5857 out->plane = loadmodel->brush.data_planes + n;
5858 for (j = 0;j < 2;j++)
5860 n = LittleLong(in->childrenindex[j]);
5863 if (n >= loadmodel->brush.num_nodes)
5864 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5865 out->children[j] = loadmodel->brush.data_nodes + n;
5870 if (n >= loadmodel->brush.num_leafs)
5871 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5872 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5875 for (j = 0;j < 3;j++)
5877 // yes the mins/maxs are ints
5878 out->mins[j] = LittleLong(in->mins[j]) - 1;
5879 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5883 // set the parent pointers
5884 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5887 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5890 q3dlightgrid_t *out;
5894 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5895 if (l->filelen % sizeof(*in))
5896 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5897 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5898 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5899 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5900 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5901 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5902 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5903 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5904 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5905 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5906 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5907 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5908 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5909 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5910 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]);
5911 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]);
5913 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5916 if (l->filelen < count * (int)sizeof(*in))
5918 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]);
5919 return; // ignore the grid if we cannot understand it
5921 if (l->filelen != count * (int)sizeof(*in))
5922 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5923 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5924 loadmodel->brushq3.data_lightgrid = out;
5925 loadmodel->brushq3.num_lightgrid = count;
5926 // no swapping or validation necessary
5927 memcpy(out, in, count * (int)sizeof(*out));
5929 if(mod_q3bsp_sRGBlightmaps.integer)
5931 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5933 // we fix the brightness consistently via lightmapscale
5937 for(i = 0; i < count; ++i)
5939 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5940 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5941 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5942 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
5943 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
5944 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
5950 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5952 for(i = 0; i < count; ++i)
5954 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5955 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5956 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5957 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
5958 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
5959 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
5970 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5975 if (l->filelen == 0)
5978 // unvised maps often have cluster indices even without pvs, so check
5979 // leafs to find real number of clusters
5980 loadmodel->brush.num_pvsclusters = 1;
5981 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5982 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5985 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5986 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5987 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5988 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5992 in = (q3dpvs_t *)(mod_base + l->fileofs);
5994 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5996 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5997 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5998 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5999 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6000 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6001 if (l->filelen < totalchains + (int)sizeof(*in))
6002 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);
6004 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6005 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6008 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6010 int i, j, k, index[3];
6011 float transformed[3], blend1, blend2, blend, stylescale = 1;
6012 q3dlightgrid_t *a, *s;
6014 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6015 switch(vid.renderpath)
6017 case RENDERPATH_GL20:
6018 case RENDERPATH_D3D9:
6019 case RENDERPATH_D3D10:
6020 case RENDERPATH_D3D11:
6021 case RENDERPATH_SOFT:
6022 case RENDERPATH_GLES2:
6023 // LordHavoc: FIXME: is this true?
6024 stylescale = 1; // added while render
6026 case RENDERPATH_GL11:
6027 case RENDERPATH_GL13:
6028 case RENDERPATH_GLES1:
6029 stylescale = r_refdef.scene.rtlightstylevalue[0];
6033 if (!model->brushq3.num_lightgrid)
6035 ambientcolor[0] = stylescale;
6036 ambientcolor[1] = stylescale;
6037 ambientcolor[2] = stylescale;
6041 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6042 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6043 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6044 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6045 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6046 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6047 index[0] = (int)floor(transformed[0]);
6048 index[1] = (int)floor(transformed[1]);
6049 index[2] = (int)floor(transformed[2]);
6050 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6052 // now lerp the values
6053 VectorClear(diffusenormal);
6054 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6055 for (k = 0;k < 2;k++)
6057 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6058 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6060 for (j = 0;j < 2;j++)
6062 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6063 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6065 for (i = 0;i < 2;i++)
6067 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6068 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6070 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6071 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6072 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6073 // this uses the mod_md3_sin table because the values are
6074 // already in the 0-255 range, the 64+ bias fetches a cosine
6075 // instead of a sine value
6076 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6077 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6078 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6079 //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)));
6084 // normalize the light direction before turning
6085 VectorNormalize(diffusenormal);
6086 //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]);
6089 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6092 double midf, mid[3];
6098 // find the point distances
6099 mplane_t *plane = node->plane;
6100 if (plane->type < 3)
6102 t1 = p1[plane->type] - plane->dist;
6103 t2 = p2[plane->type] - plane->dist;
6107 t1 = DotProduct (plane->normal, p1) - plane->dist;
6108 t2 = DotProduct (plane->normal, p2) - plane->dist;
6115 node = node->children[1];
6124 node = node->children[0];
6130 midf = t1 / (t1 - t2);
6131 VectorLerp(p1, midf, p2, mid);
6133 // recurse both sides, front side first
6134 // return 2 if empty is followed by solid (hit something)
6135 // do not return 2 if both are solid or both empty,
6136 // or if start is solid and end is empty
6137 // as these degenerate cases usually indicate the eye is in solid and
6138 // should see the target point anyway
6139 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6142 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6147 return ((mleaf_t *)node)->clusterindex < 0;
6150 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6152 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6155 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6156 return trace.fraction == 1;
6160 double tracestart[3], traceend[3];
6161 VectorCopy(start, tracestart);
6162 VectorCopy(end, traceend);
6163 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6167 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)
6170 const bih_leaf_t *leaf;
6171 const bih_node_t *node;
6172 const colbrushf_t *brush;
6175 int nodestackpos = 0;
6176 int nodestack[1024];
6178 memset(trace, 0, sizeof(*trace));
6179 trace->fraction = 1;
6180 trace->realfraction = 1;
6181 trace->hitsupercontentsmask = hitsupercontentsmask;
6183 bih = &model->collision_bih;
6187 nodenum = bih->rootnode;
6188 nodestack[nodestackpos++] = nodenum;
6189 while (nodestackpos)
6191 nodenum = nodestack[--nodestackpos];
6192 node = bih->nodes + nodenum;
6194 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6197 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6199 axis = node->type - BIH_SPLITX;
6200 if (start[axis] >= node->frontmin)
6201 nodestack[nodestackpos++] = node->front;
6202 if (start[axis] <= node->backmax)
6203 nodestack[nodestackpos++] = node->back;
6205 else if (node->type == BIH_UNORDERED)
6207 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6209 leaf = bih->leafs + node->children[axis];
6211 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6217 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6218 Collision_TracePointBrushFloat(trace, start, brush);
6220 case BIH_COLLISIONTRIANGLE:
6221 // collision triangle - skipped because they have no volume
6223 case BIH_RENDERTRIANGLE:
6224 // render triangle - skipped because they have no volume
6232 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)
6234 const bih_leaf_t *leaf;
6235 const bih_node_t *node;
6236 const colbrushf_t *brush;
6238 const texture_t *texture;
6239 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6240 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6241 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6246 if (VectorCompare(start, end))
6248 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6252 nodenum = bih->rootnode;
6254 memset(trace, 0, sizeof(*trace));
6255 trace->fraction = 1;
6256 trace->realfraction = 1;
6257 trace->hitsupercontentsmask = hitsupercontentsmask;
6260 nodestackline[nodestackpos][0] = start[0];
6261 nodestackline[nodestackpos][1] = start[1];
6262 nodestackline[nodestackpos][2] = start[2];
6263 nodestackline[nodestackpos][3] = end[0];
6264 nodestackline[nodestackpos][4] = end[1];
6265 nodestackline[nodestackpos][5] = end[2];
6266 nodestack[nodestackpos++] = nodenum;
6267 while (nodestackpos)
6269 nodenum = nodestack[--nodestackpos];
6270 node = bih->nodes + nodenum;
6271 VectorCopy(nodestackline[nodestackpos], nodestart);
6272 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6273 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6274 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6276 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6278 // recurse children of the split
6279 axis = node->type - BIH_SPLITX;
6280 d1 = node->backmax - nodestart[axis];
6281 d2 = node->backmax - nodeend[axis];
6282 d3 = nodestart[axis] - node->frontmin;
6283 d4 = nodeend[axis] - node->frontmin;
6284 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6286 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;
6287 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;
6288 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;
6289 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6290 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;
6291 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;
6292 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;
6293 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6294 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;
6295 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;
6296 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;
6297 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6298 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6299 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6300 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6301 case 15: /* <<<< */ break;
6304 else if (node->type == BIH_UNORDERED)
6306 // calculate sweep bounds for this node
6307 // copy node bounds into local variables
6308 VectorCopy(node->mins, nodebigmins);
6309 VectorCopy(node->maxs, nodebigmaxs);
6310 // clip line to this node bounds
6311 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); }
6312 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); }
6313 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); }
6314 // some of the line intersected the enlarged node box
6315 // calculate sweep bounds for this node
6316 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6317 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6319 leaf = bih->leafs + node->children[axis];
6320 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6325 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6326 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6328 case BIH_COLLISIONTRIANGLE:
6329 if (!mod_q3bsp_curves_collisions.integer)
6331 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6332 texture = model->data_textures + leaf->textureindex;
6333 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);
6335 case BIH_RENDERTRIANGLE:
6336 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6337 texture = model->data_textures + leaf->textureindex;
6338 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);
6346 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)
6348 if (VectorCompare(start, end))
6350 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6353 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6356 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)
6359 const bih_leaf_t *leaf;
6360 const bih_node_t *node;
6361 const colbrushf_t *brush;
6363 const texture_t *texture;
6364 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6365 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6366 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6367 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6369 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6371 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6372 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6374 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6378 bih = &model->collision_bih;
6381 nodenum = bih->rootnode;
6383 // box trace, performed as brush trace
6384 memset(trace, 0, sizeof(*trace));
6385 trace->fraction = 1;
6386 trace->realfraction = 1;
6387 trace->hitsupercontentsmask = hitsupercontentsmask;
6389 // calculate tracebox-like parameters for efficient culling
6390 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6391 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6392 VectorSubtract(thisbrush_start->mins, start, startmins);
6393 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6394 VectorSubtract(thisbrush_end->mins, end, endmins);
6395 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6396 mins[0] = min(startmins[0], endmins[0]);
6397 mins[1] = min(startmins[1], endmins[1]);
6398 mins[2] = min(startmins[2], endmins[2]);
6399 maxs[0] = max(startmaxs[0], endmaxs[0]);
6400 maxs[1] = max(startmaxs[1], endmaxs[1]);
6401 maxs[2] = max(startmaxs[2], endmaxs[2]);
6404 nodestackline[nodestackpos][0] = start[0];
6405 nodestackline[nodestackpos][1] = start[1];
6406 nodestackline[nodestackpos][2] = start[2];
6407 nodestackline[nodestackpos][3] = end[0];
6408 nodestackline[nodestackpos][4] = end[1];
6409 nodestackline[nodestackpos][5] = end[2];
6410 nodestack[nodestackpos++] = nodenum;
6411 while (nodestackpos)
6413 nodenum = nodestack[--nodestackpos];
6414 node = bih->nodes + nodenum;
6415 VectorCopy(nodestackline[nodestackpos], nodestart);
6416 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6417 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6418 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6420 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6422 // recurse children of the split
6423 axis = node->type - BIH_SPLITX;
6424 d1 = node->backmax - nodestart[axis] - mins[axis];
6425 d2 = node->backmax - nodeend[axis] - mins[axis];
6426 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6427 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6428 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6430 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;
6431 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;
6432 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;
6433 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6434 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;
6435 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;
6436 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;
6437 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6438 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;
6439 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;
6440 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;
6441 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6442 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6443 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6444 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6445 case 15: /* <<<< */ break;
6448 else if (node->type == BIH_UNORDERED)
6450 // calculate sweep bounds for this node
6451 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6452 VectorSubtract(node->mins, maxs, nodebigmins);
6453 VectorSubtract(node->maxs, mins, nodebigmaxs);
6454 // clip line to this node bounds
6455 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); }
6456 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); }
6457 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); }
6458 // some of the line intersected the enlarged node box
6459 // calculate sweep bounds for this node
6460 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6461 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6463 leaf = bih->leafs + node->children[axis];
6464 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6469 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6470 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6472 case BIH_COLLISIONTRIANGLE:
6473 if (!mod_q3bsp_curves_collisions.integer)
6475 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6476 texture = model->data_textures + leaf->textureindex;
6477 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);
6479 case BIH_RENDERTRIANGLE:
6480 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6481 texture = model->data_textures + leaf->textureindex;
6482 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);
6490 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)
6492 colboxbrushf_t thisbrush_start, thisbrush_end;
6493 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6495 // box trace, performed as brush trace
6496 VectorAdd(start, boxmins, boxstartmins);
6497 VectorAdd(start, boxmaxs, boxstartmaxs);
6498 VectorAdd(end, boxmins, boxendmins);
6499 VectorAdd(end, boxmaxs, boxendmaxs);
6500 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6501 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6502 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6506 static int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6509 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6510 return trace.startsupercontents;
6513 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)
6516 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6518 int hitsupercontents;
6519 VectorSet(end, start[0], start[1], model->normalmins[2]);
6521 memset(trace, 0, sizeof(*trace));
6522 trace->fraction = 1;
6523 trace->realfraction = 1;
6524 trace->hitsupercontentsmask = hitsupercontentsmask;
6526 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6527 hitsupercontents = trace->hitsupercontents;
6528 memset(trace, 0, sizeof(*trace));
6529 trace->fraction = 1;
6530 trace->realfraction = 1;
6531 trace->hitsupercontentsmask = hitsupercontentsmask;
6532 trace->startsupercontents = hitsupercontents;
6536 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6539 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6542 VectorSet(end, start[0], start[1], model->normalmins[2]);
6543 memset(&trace, 0, sizeof(trace));
6545 trace.realfraction = 1;
6546 trace.hitsupercontentsmask = 0;
6547 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6548 return trace.hitsupercontents;
6554 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6559 // find which leaf the point is in
6561 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6562 // point trace the brushes
6563 leaf = (mleaf_t *)node;
6564 for (i = 0;i < leaf->numleafbrushes;i++)
6566 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6567 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6569 brush->markframe = markframe;
6570 Collision_TracePointBrushFloat(trace, point, brush);
6573 // can't do point traces on curves (they have no thickness)
6576 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)
6578 int i, startside, endside;
6579 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6581 msurface_t *surface;
6584 // walk the tree until we hit a leaf, recursing for any split cases
6588 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6590 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6591 node = node->children[1];
6593 // abort if this part of the bsp tree can not be hit by this trace
6594 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6596 plane = node->plane;
6597 // axial planes are much more common than non-axial, so an optimized
6598 // axial case pays off here
6599 if (plane->type < 3)
6601 dist1 = start[plane->type] - plane->dist;
6602 dist2 = end[plane->type] - plane->dist;
6606 dist1 = DotProduct(start, plane->normal) - plane->dist;
6607 dist2 = DotProduct(end, plane->normal) - plane->dist;
6609 startside = dist1 < 0;
6610 endside = dist2 < 0;
6611 if (startside == endside)
6613 // most of the time the line fragment is on one side of the plane
6614 node = node->children[startside];
6618 // line crosses node plane, split the line
6619 dist1 = PlaneDiff(linestart, plane);
6620 dist2 = PlaneDiff(lineend, plane);
6621 midfrac = dist1 / (dist1 - dist2);
6622 VectorLerp(linestart, midfrac, lineend, mid);
6623 // take the near side first
6624 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6625 // if we found an impact on the front side, don't waste time
6626 // exploring the far side
6627 if (midfrac <= trace->realfraction)
6628 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6633 // abort if this part of the bsp tree can not be hit by this trace
6634 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6637 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6638 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6639 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6640 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6641 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6642 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6643 // line trace the brushes
6644 leaf = (mleaf_t *)node;
6646 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6649 for (i = 0;i < leaf->numleafbrushes;i++)
6651 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6652 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6654 brush->markframe = markframe;
6655 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6658 // can't do point traces on curves (they have no thickness)
6659 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6661 // line trace the curves
6662 for (i = 0;i < leaf->numleafsurfaces;i++)
6664 surface = model->data_surfaces + leaf->firstleafsurface[i];
6665 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6667 surface->deprecatedq3collisionmarkframe = markframe;
6668 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);
6674 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)
6680 msurface_t *surface;
6682 float nodesegmentmins[3], nodesegmentmaxs[3];
6683 // walk the tree until we hit a leaf, recursing for any split cases
6687 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6689 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6690 node = node->children[1];
6692 // abort if this part of the bsp tree can not be hit by this trace
6693 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6695 plane = node->plane;
6696 // axial planes are much more common than non-axial, so an optimized
6697 // axial case pays off here
6698 if (plane->type < 3)
6700 // this is an axial plane, compare bounding box directly to it and
6701 // recurse sides accordingly
6702 // recurse down node sides
6703 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6704 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6705 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6706 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6710 // this is a non-axial plane, so check if the start and end boxes
6711 // are both on one side of the plane to handle 'diagonal' cases
6712 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6716 // segment crosses plane
6717 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6720 // if sides == 0 then the trace itself is bogus (Not A Number values),
6721 // in this case we simply pretend the trace hit nothing
6723 return; // ERROR: NAN bounding box!
6724 // take whichever side the segment box is on
6725 node = node->children[sides - 1];
6728 // abort if this part of the bsp tree can not be hit by this trace
6729 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6731 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6732 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6733 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6734 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6735 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6736 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6738 leaf = (mleaf_t *)node;
6740 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6743 for (i = 0;i < leaf->numleafbrushes;i++)
6745 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6746 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6748 brush->markframe = markframe;
6749 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6752 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6754 for (i = 0;i < leaf->numleafsurfaces;i++)
6756 surface = model->data_surfaces + leaf->firstleafsurface[i];
6757 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6759 surface->deprecatedq3collisionmarkframe = markframe;
6760 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);
6767 static int markframe = 0;
6769 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)
6773 memset(trace, 0, sizeof(*trace));
6774 trace->fraction = 1;
6775 trace->realfraction = 1;
6776 trace->hitsupercontentsmask = hitsupercontentsmask;
6777 if (mod_collision_bih.integer)
6778 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6779 else if (model->brush.submodel)
6781 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6782 if (brush->colbrushf)
6783 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6786 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6789 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)
6792 float segmentmins[3], segmentmaxs[3];
6793 msurface_t *surface;
6796 if (VectorCompare(start, end))
6798 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6802 memset(trace, 0, sizeof(*trace));
6803 trace->fraction = 1;
6804 trace->realfraction = 1;
6805 trace->hitsupercontentsmask = hitsupercontentsmask;
6806 segmentmins[0] = min(start[0], end[0]) - 1;
6807 segmentmins[1] = min(start[1], end[1]) - 1;
6808 segmentmins[2] = min(start[2], end[2]) - 1;
6809 segmentmaxs[0] = max(start[0], end[0]) + 1;
6810 segmentmaxs[1] = max(start[1], end[1]) + 1;
6811 segmentmaxs[2] = max(start[2], end[2]) + 1;
6812 if (mod_collision_bih.integer)
6813 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6814 else if (model->brush.submodel)
6816 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6817 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6818 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6819 if (mod_q3bsp_curves_collisions.integer)
6820 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6821 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6822 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);
6825 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6828 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)
6830 float segmentmins[3], segmentmaxs[3];
6832 msurface_t *surface;
6835 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6837 if (VectorCompare(start->mins, end->mins))
6838 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6840 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6844 // box trace, performed as brush trace
6845 memset(trace, 0, sizeof(*trace));
6846 trace->fraction = 1;
6847 trace->realfraction = 1;
6848 trace->hitsupercontentsmask = hitsupercontentsmask;
6849 segmentmins[0] = min(start->mins[0], end->mins[0]);
6850 segmentmins[1] = min(start->mins[1], end->mins[1]);
6851 segmentmins[2] = min(start->mins[2], end->mins[2]);
6852 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6853 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6854 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6855 if (mod_collision_bih.integer)
6856 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6857 else if (model->brush.submodel)
6859 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6860 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6861 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6862 if (mod_q3bsp_curves_collisions.integer)
6863 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6864 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6865 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);
6868 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6871 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)
6873 colboxbrushf_t thisbrush_start, thisbrush_end;
6874 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6876 // box trace, performed as brush trace
6877 VectorAdd(start, boxmins, boxstartmins);
6878 VectorAdd(start, boxmaxs, boxstartmaxs);
6879 VectorAdd(end, boxmins, boxendmins);
6880 VectorAdd(end, boxmaxs, boxendmaxs);
6881 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6882 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6883 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6886 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6889 int supercontents = 0;
6891 if (mod_collision_bih.integer)
6893 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
6895 // test if the point is inside each brush
6896 else if (model->brush.submodel)
6898 // submodels are effectively one leaf
6899 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6900 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6901 supercontents |= brush->colbrushf->supercontents;
6905 mnode_t *node = model->brush.data_nodes;
6907 // find which leaf the point is in
6909 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6910 leaf = (mleaf_t *)node;
6911 // now check the brushes in the leaf
6912 for (i = 0;i < leaf->numleafbrushes;i++)
6914 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6915 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6916 supercontents |= brush->colbrushf->supercontents;
6919 return supercontents;
6922 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)
6924 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6928 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6936 int nummodelbrushes = model->nummodelbrushes;
6937 int nummodelsurfaces = model->nummodelsurfaces;
6939 const int *collisionelement3i;
6940 const float *collisionvertex3f;
6941 const int *renderelement3i;
6942 const float *rendervertex3f;
6943 bih_leaf_t *bihleafs;
6944 bih_node_t *bihnodes;
6946 int *temp_leafsortscratch;
6947 const msurface_t *surface;
6948 const q3mbrush_t *brush;
6950 // find out how many BIH leaf nodes we need
6952 if (userendersurfaces)
6954 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6955 bihnumleafs += surface->num_triangles;
6959 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6960 if (brush->colbrushf)
6962 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6964 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6965 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6967 bihnumleafs += surface->num_collisiontriangles;
6974 // allocate the memory for the BIH leaf nodes
6975 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6977 // now populate the BIH leaf nodes
6980 // add render surfaces
6981 renderelement3i = model->surfmesh.data_element3i;
6982 rendervertex3f = model->surfmesh.data_vertex3f;
6983 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6985 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6987 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6989 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6990 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6991 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6992 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6993 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6994 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6995 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6996 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6997 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6998 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7003 if (!userendersurfaces)
7005 // add collision brushes
7006 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7008 if (!brush->colbrushf)
7010 bihleafs[bihleafindex].type = BIH_BRUSH;
7011 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7012 bihleafs[bihleafindex].surfaceindex = -1;
7013 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7014 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7015 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7019 // add collision surfaces
7020 collisionelement3i = model->brush.data_collisionelement3i;
7021 collisionvertex3f = model->brush.data_collisionvertex3f;
7022 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7024 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7026 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7027 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7028 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7029 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7030 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7031 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7032 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7033 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7034 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7035 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7041 // allocate buffers for the produced and temporary data
7042 bihmaxnodes = bihnumleafs + 1;
7043 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7044 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7045 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7048 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7050 // we're done with the temporary data
7051 Mem_Free(temp_leafsort);
7053 // resize the BIH nodes array if it over-allocated
7054 if (out->maxnodes > out->numnodes)
7056 out->maxnodes = out->numnodes;
7057 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7063 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7065 int supercontents = 0;
7066 if (nativecontents & CONTENTSQ3_SOLID)
7067 supercontents |= SUPERCONTENTS_SOLID;
7068 if (nativecontents & CONTENTSQ3_WATER)
7069 supercontents |= SUPERCONTENTS_WATER;
7070 if (nativecontents & CONTENTSQ3_SLIME)
7071 supercontents |= SUPERCONTENTS_SLIME;
7072 if (nativecontents & CONTENTSQ3_LAVA)
7073 supercontents |= SUPERCONTENTS_LAVA;
7074 if (nativecontents & CONTENTSQ3_BODY)
7075 supercontents |= SUPERCONTENTS_BODY;
7076 if (nativecontents & CONTENTSQ3_CORPSE)
7077 supercontents |= SUPERCONTENTS_CORPSE;
7078 if (nativecontents & CONTENTSQ3_NODROP)
7079 supercontents |= SUPERCONTENTS_NODROP;
7080 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7081 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7082 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7083 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7084 if (nativecontents & CONTENTSQ3_DONOTENTER)
7085 supercontents |= SUPERCONTENTS_DONOTENTER;
7086 if (nativecontents & CONTENTSQ3_BOTCLIP)
7087 supercontents |= SUPERCONTENTS_BOTCLIP;
7088 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7089 supercontents |= SUPERCONTENTS_OPAQUE;
7090 return supercontents;
7093 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7095 int nativecontents = 0;
7096 if (supercontents & SUPERCONTENTS_SOLID)
7097 nativecontents |= CONTENTSQ3_SOLID;
7098 if (supercontents & SUPERCONTENTS_WATER)
7099 nativecontents |= CONTENTSQ3_WATER;
7100 if (supercontents & SUPERCONTENTS_SLIME)
7101 nativecontents |= CONTENTSQ3_SLIME;
7102 if (supercontents & SUPERCONTENTS_LAVA)
7103 nativecontents |= CONTENTSQ3_LAVA;
7104 if (supercontents & SUPERCONTENTS_BODY)
7105 nativecontents |= CONTENTSQ3_BODY;
7106 if (supercontents & SUPERCONTENTS_CORPSE)
7107 nativecontents |= CONTENTSQ3_CORPSE;
7108 if (supercontents & SUPERCONTENTS_NODROP)
7109 nativecontents |= CONTENTSQ3_NODROP;
7110 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7111 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7112 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7113 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7114 if (supercontents & SUPERCONTENTS_DONOTENTER)
7115 nativecontents |= CONTENTSQ3_DONOTENTER;
7116 if (supercontents & SUPERCONTENTS_BOTCLIP)
7117 nativecontents |= CONTENTSQ3_BOTCLIP;
7118 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7119 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7120 return nativecontents;
7123 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7128 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7129 node = node->children[1];
7131 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7132 if (loadmodel->brush.num_leafs < numleafs)
7133 loadmodel->brush.num_leafs = numleafs;
7136 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7139 q3dheader_t *header;
7140 float corner[3], yawradius, modelradius;
7142 mod->modeldatatypestring = "Q3BSP";
7144 mod->type = mod_brushq3;
7145 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7148 header = (q3dheader_t *)buffer;
7149 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7150 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7152 i = LittleLong(header->version);
7153 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7154 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7156 mod->soundfromcenter = true;
7157 mod->TraceBox = Mod_Q3BSP_TraceBox;
7158 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7159 mod->TraceLine = Mod_Q3BSP_TraceLine;
7160 mod->TracePoint = Mod_Q3BSP_TracePoint;
7161 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7162 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7163 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7164 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7165 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7166 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7167 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7168 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7169 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7170 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7171 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7172 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7173 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7174 mod->brush.AmbientSoundLevelsForPoint = NULL;
7175 mod->brush.RoundUpToHullSize = NULL;
7176 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7177 mod->Draw = R_Q1BSP_Draw;
7178 mod->DrawDepth = R_Q1BSP_DrawDepth;
7179 mod->DrawDebug = R_Q1BSP_DrawDebug;
7180 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7181 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7182 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7183 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7184 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7185 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7186 mod->DrawLight = R_Q1BSP_DrawLight;
7188 mod_base = (unsigned char *)header;
7190 // swap all the lumps
7191 header->ident = LittleLong(header->ident);
7192 header->version = LittleLong(header->version);
7193 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7194 for (i = 0;i < lumps;i++)
7196 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7197 if((char *) bufferend < (char *) buffer + j)
7198 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7199 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7200 if((char *) bufferend < (char *) buffer + j)
7201 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7204 * NO, do NOT clear them!
7205 * they contain actual data referenced by other stuff.
7206 * Instead, before using the advertisements lump, check header->versio
7208 * Sorry, but otherwise it breaks memory of the first lump.
7209 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7211 header->lumps[i].fileofs = 0;
7212 header->lumps[i].filelen = 0;
7216 mod->brush.qw_md4sum = 0;
7217 mod->brush.qw_md4sum2 = 0;
7218 for (i = 0;i < lumps;i++)
7220 if (i == Q3LUMP_ENTITIES)
7222 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7223 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7225 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7227 // all this checksumming can take a while, so let's send keepalives here too
7228 CL_KeepaliveMessage(false);
7231 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7232 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7233 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7234 if (header->version == Q3BSPVERSION_IG)
7235 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7237 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7238 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7239 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7240 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7241 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7242 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7243 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7244 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7245 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7246 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7247 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7248 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7249 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7250 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7251 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7253 // the MakePortals code works fine on the q3bsp data as well
7254 if (mod_bsp_portalize.integer)
7255 Mod_Q1BSP_MakePortals();
7257 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7258 loadmodel->brush.supportwateralpha = true;
7260 // make a single combined shadow mesh to allow optimized shadow volume creation
7261 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7263 loadmodel->brush.num_leafs = 0;
7264 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7266 if (loadmodel->brush.numsubmodels)
7267 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7270 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7275 // duplicate the basic information
7276 dpsnprintf(name, sizeof(name), "*%i", i);
7277 mod = Mod_FindName(name, loadmodel->name);
7278 // copy the base model to this one
7280 // rename the clone back to its proper name
7281 strlcpy(mod->name, name, sizeof(mod->name));
7282 mod->brush.parentmodel = loadmodel;
7283 // textures and memory belong to the main model
7284 mod->texturepool = NULL;
7285 mod->mempool = NULL;
7286 mod->brush.GetPVS = NULL;
7287 mod->brush.FatPVS = NULL;
7288 mod->brush.BoxTouchingPVS = NULL;
7289 mod->brush.BoxTouchingLeafPVS = NULL;
7290 mod->brush.BoxTouchingVisibleLeafs = NULL;
7291 mod->brush.FindBoxClusters = NULL;
7292 mod->brush.LightPoint = NULL;
7293 mod->brush.AmbientSoundLevelsForPoint = NULL;
7295 mod->brush.submodel = i;
7296 if (loadmodel->brush.submodels)
7297 loadmodel->brush.submodels[i] = mod;
7299 // make the model surface list (used by shadowing/lighting)
7300 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7301 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7302 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7303 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7304 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7305 Mod_MakeSortedSurfaces(mod);
7307 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7308 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7309 // enlarge the bounding box to enclose all geometry of this model,
7310 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7311 // which can in turn mess up the farclip (as well as culling when
7312 // outside the level - an unimportant concern)
7314 //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]);
7315 for (j = 0;j < mod->nummodelsurfaces;j++)
7317 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7318 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7320 if (!surface->num_vertices)
7322 for (k = 0;k < surface->num_vertices;k++, v += 3)
7324 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7325 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7326 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7327 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7328 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7329 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7332 //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]);
7333 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7334 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7335 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7336 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7337 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7338 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7339 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7340 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7341 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7342 mod->yawmins[2] = mod->normalmins[2];
7343 mod->yawmaxs[2] = mod->normalmaxs[2];
7344 mod->radius = modelradius;
7345 mod->radius2 = modelradius * modelradius;
7347 // this gets altered below if sky or water is used
7348 mod->DrawSky = NULL;
7349 mod->DrawAddWaterPlanes = NULL;
7351 for (j = 0;j < mod->nummodelsurfaces;j++)
7352 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7354 if (j < mod->nummodelsurfaces)
7355 mod->DrawSky = R_Q1BSP_DrawSky;
7357 for (j = 0;j < mod->nummodelsurfaces;j++)
7358 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7360 if (j < mod->nummodelsurfaces)
7361 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7363 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7364 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7366 // generate VBOs and other shared data before cloning submodels
7371 if (mod_q3bsp_sRGBlightmaps.integer)
7373 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7375 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7376 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7377 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7378 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7379 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7381 else // if this is NOT set, regular rendering looks right by this requirement anyway
7384 // we want color 1 to do the same as without sRGB
7385 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7386 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7389 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7390 // we need to undo that
7391 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7395 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);
7398 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7400 int i = LittleLong(((int *)buffer)[1]);
7401 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7402 Mod_Q3BSP_Load(mod,buffer, bufferend);
7403 else if (i == Q2BSPVERSION)
7404 Mod_Q2BSP_Load(mod,buffer, bufferend);
7406 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7409 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7411 Host_Error("Mod_MAP_Load: not yet implemented");
7414 typedef struct objvertex_s
7425 static unsigned char nobsp_pvs[1] = {1};
7427 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7429 const char *textbase = (char *)buffer, *text = textbase;
7433 char materialname[MAX_QPATH];
7434 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7435 int index1, index2, index3;
7436 objvertex_t vfirst, vprev, vcurrent;
7439 int numtriangles = 0;
7440 int maxtriangles = 0;
7441 objvertex_t *vertices = NULL;
7443 int maxtextures = 0, numtextures = 0, textureindex = 0;
7444 int maxv = 0, numv = 1;
7445 int maxvt = 0, numvt = 1;
7446 int maxvn = 0, numvn = 1;
7447 char *texturenames = NULL;
7448 float dist, modelradius, modelyawradius, yawradius;
7455 objvertex_t *thisvertex = NULL;
7456 int vertexhashindex;
7457 int *vertexhashtable = NULL;
7458 objvertex_t *vertexhashdata = NULL;
7459 objvertex_t *vdata = NULL;
7460 int vertexhashsize = 0;
7461 int vertexhashcount = 0;
7462 skinfile_t *skinfiles = NULL;
7463 unsigned char *data = NULL;
7464 int *submodelfirstsurface;
7465 msurface_t *surface;
7466 msurface_t *tempsurfaces;
7468 memset(&vfirst, 0, sizeof(vfirst));
7469 memset(&vprev, 0, sizeof(vprev));
7470 memset(&vcurrent, 0, sizeof(vcurrent));
7472 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7474 loadmodel->modeldatatypestring = "OBJ";
7476 loadmodel->type = mod_obj;
7477 loadmodel->soundfromcenter = true;
7478 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7479 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7480 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7481 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7482 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7483 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7484 loadmodel->brush.TraceLineOfSight = NULL;
7485 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7486 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7487 loadmodel->brush.GetPVS = NULL;
7488 loadmodel->brush.FatPVS = NULL;
7489 loadmodel->brush.BoxTouchingPVS = NULL;
7490 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7491 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7492 loadmodel->brush.FindBoxClusters = NULL;
7493 loadmodel->brush.LightPoint = NULL;
7494 loadmodel->brush.FindNonSolidLocation = NULL;
7495 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7496 loadmodel->brush.RoundUpToHullSize = NULL;
7497 loadmodel->brush.PointInLeaf = NULL;
7498 loadmodel->Draw = R_Q1BSP_Draw;
7499 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7500 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7501 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7502 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7503 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7504 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7505 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7506 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7507 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7509 skinfiles = Mod_LoadSkinFiles();
7510 if (loadmodel->numskins < 1)
7511 loadmodel->numskins = 1;
7513 // make skinscenes for the skins (no groups)
7514 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7515 for (i = 0;i < loadmodel->numskins;i++)
7517 loadmodel->skinscenes[i].firstframe = i;
7518 loadmodel->skinscenes[i].framecount = 1;
7519 loadmodel->skinscenes[i].loop = true;
7520 loadmodel->skinscenes[i].framerate = 10;
7526 // we always have model 0, i.e. the first "submodel"
7527 loadmodel->brush.numsubmodels = 1;
7529 // parse the OBJ text now
7532 static char emptyarg[1] = "";
7537 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7538 line[linelen] = text[linelen];
7540 for (argc = 0;argc < 4;argc++)
7541 argv[argc] = emptyarg;
7544 while (*s == ' ' || *s == '\t')
7554 while (*s == ' ' || *s == '\t')
7564 if (argv[0][0] == '#')
7566 if (!strcmp(argv[0], "v"))
7570 maxv = max(maxv * 2, 1024);
7571 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7573 if(mod_obj_orientation.integer)
7575 v[numv*3+0] = atof(argv[1]);
7576 v[numv*3+2] = atof(argv[2]);
7577 v[numv*3+1] = atof(argv[3]);
7581 v[numv*3+0] = atof(argv[1]);
7582 v[numv*3+1] = atof(argv[2]);
7583 v[numv*3+2] = atof(argv[3]);
7587 else if (!strcmp(argv[0], "vt"))
7591 maxvt = max(maxvt * 2, 1024);
7592 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7594 vt[numvt*2+0] = atof(argv[1]);
7595 vt[numvt*2+1] = 1-atof(argv[2]);
7598 else if (!strcmp(argv[0], "vn"))
7602 maxvn = max(maxvn * 2, 1024);
7603 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7605 if(mod_obj_orientation.integer)
7607 vn[numvn*3+0] = atof(argv[1]);
7608 vn[numvn*3+2] = atof(argv[2]);
7609 vn[numvn*3+1] = atof(argv[3]);
7613 vn[numvn*3+0] = atof(argv[1]);
7614 vn[numvn*3+1] = atof(argv[2]);
7615 vn[numvn*3+2] = atof(argv[3]);
7619 else if (!strcmp(argv[0], "f"))
7623 if (maxtextures <= numtextures)
7625 maxtextures = max(maxtextures * 2, 256);
7626 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7628 textureindex = numtextures++;
7629 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7631 for (j = 1;j < argc;j++)
7633 index1 = atoi(argv[j]);
7634 while(argv[j][0] && argv[j][0] != '/')
7638 index2 = atoi(argv[j]);
7639 while(argv[j][0] && argv[j][0] != '/')
7643 index3 = atoi(argv[j]);
7644 // negative refers to a recent vertex
7645 // zero means not specified
7646 // positive means an absolute vertex index
7648 index1 = numv - index1;
7650 index2 = numvt - index2;
7652 index3 = numvn - index3;
7653 vcurrent.nextindex = -1;
7654 vcurrent.textureindex = textureindex;
7655 vcurrent.submodelindex = submodelindex;
7656 if (v && index1 >= 0 && index1 < numv)
7657 VectorCopy(v + 3*index1, vcurrent.v);
7658 if (vt && index2 >= 0 && index2 < numvt)
7659 Vector2Copy(vt + 2*index2, vcurrent.vt);
7660 if (vn && index3 >= 0 && index3 < numvn)
7661 VectorCopy(vn + 3*index3, vcurrent.vn);
7662 if (numtriangles == 0)
7664 VectorCopy(vcurrent.v, mins);
7665 VectorCopy(vcurrent.v, maxs);
7669 mins[0] = min(mins[0], vcurrent.v[0]);
7670 mins[1] = min(mins[1], vcurrent.v[1]);
7671 mins[2] = min(mins[2], vcurrent.v[2]);
7672 maxs[0] = max(maxs[0], vcurrent.v[0]);
7673 maxs[1] = max(maxs[1], vcurrent.v[1]);
7674 maxs[2] = max(maxs[2], vcurrent.v[2]);
7680 if (maxtriangles <= numtriangles)
7682 maxtriangles = max(maxtriangles * 2, 32768);
7683 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7685 if(mod_obj_orientation.integer)
7687 vertices[numtriangles*3+0] = vfirst;
7688 vertices[numtriangles*3+1] = vprev;
7689 vertices[numtriangles*3+2] = vcurrent;
7693 vertices[numtriangles*3+0] = vfirst;
7694 vertices[numtriangles*3+2] = vprev;
7695 vertices[numtriangles*3+1] = vcurrent;
7702 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7704 submodelindex = atof(argv[1]);
7705 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7707 else if (!strcmp(argv[0], "usemtl"))
7709 for (i = 0;i < numtextures;i++)
7710 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7712 if (i < numtextures)
7716 if (maxtextures <= numtextures)
7718 maxtextures = max(maxtextures * 2, 256);
7719 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7721 textureindex = numtextures++;
7722 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7727 // now that we have the OBJ data loaded as-is, we can convert it
7729 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7730 VectorCopy(mins, loadmodel->normalmins);
7731 VectorCopy(maxs, loadmodel->normalmaxs);
7732 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7733 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7734 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7735 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7736 modelradius = modelyawradius + modelradius * modelradius;
7737 modelyawradius = sqrt(modelyawradius);
7738 modelradius = sqrt(modelradius);
7739 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7740 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7741 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7742 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7743 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7744 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7745 loadmodel->radius = modelradius;
7746 loadmodel->radius2 = modelradius * modelradius;
7748 // allocate storage for triangles
7749 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7750 // allocate vertex hash structures to build an optimal vertex subset
7751 vertexhashsize = numtriangles*2;
7752 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7753 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7754 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7755 vertexhashcount = 0;
7757 // gather surface stats for assigning vertex/triangle ranges
7761 loadmodel->num_surfaces = 0;
7762 // allocate storage for the worst case number of surfaces, later we resize
7763 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7764 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7765 surface = tempsurfaces;
7766 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7768 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7769 for (textureindex = 0;textureindex < numtextures;textureindex++)
7771 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7773 thisvertex = vertices + vertexindex;
7774 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7777 // skip the surface creation if there are no triangles for it
7778 if (vertexindex == numtriangles*3)
7780 // create a surface for these vertices
7781 surfacevertices = 0;
7782 surfaceelements = 0;
7783 // we hack in a texture index in the surface to be fixed up later...
7784 surface->texture = (texture_t *)((size_t)textureindex);
7785 // calculate bounds as we go
7786 VectorCopy(thisvertex->v, surface->mins);
7787 VectorCopy(thisvertex->v, surface->maxs);
7788 for (;vertexindex < numtriangles*3;vertexindex++)
7790 thisvertex = vertices + vertexindex;
7791 if (thisvertex->submodelindex != submodelindex)
7793 if (thisvertex->textureindex != textureindex)
7795 // add vertex to surface bounds
7796 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7797 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7798 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7799 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7800 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7801 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7802 // add the vertex if it is not found in the merged set, and
7803 // get its index (triangle element) for the surface
7804 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7805 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7807 vdata = vertexhashdata + i;
7808 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7813 i = vertexhashcount++;
7814 vdata = vertexhashdata + i;
7815 *vdata = *thisvertex;
7816 vdata->nextindex = vertexhashtable[vertexhashindex];
7817 vertexhashtable[vertexhashindex] = i;
7820 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7823 surfacetriangles = surfaceelements / 3;
7824 surface->num_vertices = surfacevertices;
7825 surface->num_triangles = surfacetriangles;
7826 surface->num_firstvertex = firstvertex;
7827 surface->num_firsttriangle = firsttriangle;
7828 firstvertex += surface->num_vertices;
7829 firsttriangle += surface->num_triangles;
7831 loadmodel->num_surfaces++;
7834 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7835 numvertices = firstvertex;
7836 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7837 tempsurfaces = NULL;
7839 // allocate storage for final mesh data
7840 loadmodel->num_textures = numtextures * loadmodel->numskins;
7841 loadmodel->num_texturesperskin = numtextures;
7842 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 *));
7843 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7844 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7845 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7846 loadmodel->surfmesh.num_vertices = numvertices;
7847 loadmodel->surfmesh.num_triangles = numtriangles;
7848 if (r_enableshadowvolumes.integer)
7849 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7850 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7851 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7852 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7853 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7854 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7855 if (loadmodel->surfmesh.num_vertices <= 65536)
7856 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7858 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7860 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7861 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7862 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7865 // load the textures
7866 for (textureindex = 0;textureindex < numtextures;textureindex++)
7867 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7868 Mod_FreeSkinFiles(skinfiles);
7870 // set the surface textures to their real values now that we loaded them...
7871 for (i = 0;i < loadmodel->num_surfaces;i++)
7872 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7876 Mem_Free(texturenames);
7880 Mem_Free(vertexhashtable);
7881 Mem_Free(vertexhashdata);
7883 // make a single combined shadow mesh to allow optimized shadow volume creation
7884 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7886 // compute all the mesh information that was not loaded from the file
7887 if (loadmodel->surfmesh.data_element3s)
7888 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7889 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7890 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7891 // generate normals if the file did not have them
7892 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7893 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);
7894 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);
7895 if (loadmodel->surfmesh.data_neighbor3i)
7896 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7898 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7899 loadmodel->brush.num_visleafs = 1;
7900 loadmodel->brush.num_leafs = 1;
7901 loadmodel->brush.num_nodes = 0;
7902 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7903 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7904 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7905 loadmodel->brush.num_pvsclusters = 1;
7906 loadmodel->brush.num_pvsclusterbytes = 1;
7907 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7908 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7909 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7910 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7911 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7912 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7913 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7914 loadmodel->brush.data_leafs->clusterindex = 0;
7915 loadmodel->brush.data_leafs->areaindex = 0;
7916 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7917 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7918 loadmodel->brush.data_leafs->numleafbrushes = 0;
7919 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7920 loadmodel->brush.supportwateralpha = true;
7922 if (loadmodel->brush.numsubmodels)
7923 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7926 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7931 // duplicate the basic information
7932 dpsnprintf(name, sizeof(name), "*%i", i);
7933 mod = Mod_FindName(name, loadmodel->name);
7934 // copy the base model to this one
7936 // rename the clone back to its proper name
7937 strlcpy(mod->name, name, sizeof(mod->name));
7938 mod->brush.parentmodel = loadmodel;
7939 // textures and memory belong to the main model
7940 mod->texturepool = NULL;
7941 mod->mempool = NULL;
7942 mod->brush.GetPVS = NULL;
7943 mod->brush.FatPVS = NULL;
7944 mod->brush.BoxTouchingPVS = NULL;
7945 mod->brush.BoxTouchingLeafPVS = NULL;
7946 mod->brush.BoxTouchingVisibleLeafs = NULL;
7947 mod->brush.FindBoxClusters = NULL;
7948 mod->brush.LightPoint = NULL;
7949 mod->brush.AmbientSoundLevelsForPoint = NULL;
7951 mod->brush.submodel = i;
7952 if (loadmodel->brush.submodels)
7953 loadmodel->brush.submodels[i] = mod;
7955 // make the model surface list (used by shadowing/lighting)
7956 mod->firstmodelsurface = submodelfirstsurface[i];
7957 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7958 mod->firstmodelbrush = 0;
7959 mod->nummodelbrushes = 0;
7960 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7961 Mod_MakeSortedSurfaces(mod);
7963 VectorClear(mod->normalmins);
7964 VectorClear(mod->normalmaxs);
7966 for (j = 0;j < mod->nummodelsurfaces;j++)
7968 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7969 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7971 if (!surface->num_vertices)
7976 VectorCopy(v, mod->normalmins);
7977 VectorCopy(v, mod->normalmaxs);
7979 for (k = 0;k < surface->num_vertices;k++, v += 3)
7981 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7982 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7983 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7984 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7985 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7986 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7989 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7990 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7991 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7992 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7993 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7994 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7995 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7996 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7997 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7998 mod->yawmins[2] = mod->normalmins[2];
7999 mod->yawmaxs[2] = mod->normalmaxs[2];
8000 mod->radius = modelradius;
8001 mod->radius2 = modelradius * modelradius;
8003 // this gets altered below if sky or water is used
8004 mod->DrawSky = NULL;
8005 mod->DrawAddWaterPlanes = NULL;
8007 for (j = 0;j < mod->nummodelsurfaces;j++)
8008 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8010 if (j < mod->nummodelsurfaces)
8011 mod->DrawSky = R_Q1BSP_DrawSky;
8013 for (j = 0;j < mod->nummodelsurfaces;j++)
8014 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8016 if (j < mod->nummodelsurfaces)
8017 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8019 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8020 mod->render_bih = mod->collision_bih;
8022 // generate VBOs and other shared data before cloning submodels
8027 Mem_Free(submodelfirstsurface);
8029 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);