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_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);
908 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)
910 RecursiveHullCheckTraceInfo_t rhc;
912 if (VectorCompare(start, end))
914 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
918 // sometimes we want to traceline against polygons so we can report the texture that was hit rather than merely a contents, but using this method breaks one of negke's maps so it must be a cvar check...
919 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
921 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
925 memset(&rhc, 0, sizeof(rhc));
926 memset(trace, 0, sizeof(trace_t));
928 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
929 rhc.trace->fraction = 1;
930 rhc.trace->realfraction = 1;
931 rhc.trace->allsolid = true;
932 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
933 VectorCopy(start, rhc.start);
934 VectorCopy(end, rhc.end);
935 VectorSubtract(rhc.end, rhc.start, rhc.dist);
936 #if COLLISIONPARANOID >= 2
937 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]);
938 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
943 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
944 memset(&testtrace, 0, sizeof(trace_t));
945 rhc.trace = &testtrace;
946 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
947 rhc.trace->fraction = 1;
948 rhc.trace->realfraction = 1;
949 rhc.trace->allsolid = true;
950 VectorCopy(test, rhc.start);
951 VectorCopy(test, rhc.end);
952 VectorClear(rhc.dist);
953 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
954 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
955 if (!trace->startsolid && testtrace.startsolid)
956 Con_Printf(" - ended in solid!\n");
960 if (VectorLength2(rhc.dist))
961 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
963 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
967 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)
969 // this function currently only supports same size start and end
971 RecursiveHullCheckTraceInfo_t rhc;
973 if (VectorCompare(boxmins, boxmaxs))
975 if (VectorCompare(start, end))
976 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
978 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
982 memset(&rhc, 0, sizeof(rhc));
983 memset(trace, 0, sizeof(trace_t));
985 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
986 rhc.trace->fraction = 1;
987 rhc.trace->realfraction = 1;
988 rhc.trace->allsolid = true;
989 VectorSubtract(boxmaxs, boxmins, boxsize);
991 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
992 else if (model->brush.ishlbsp)
994 // LordHavoc: this has to have a minor tolerance (the .1) because of
995 // minor float precision errors from the box being transformed around
996 if (boxsize[0] < 32.1)
998 if (boxsize[2] < 54) // pick the nearest of 36 or 72
999 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
1001 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1004 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1008 // LordHavoc: this has to have a minor tolerance (the .1) because of
1009 // minor float precision errors from the box being transformed around
1010 if (boxsize[0] < 32.1)
1011 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1013 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1015 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1016 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1017 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1018 #if COLLISIONPARANOID >= 2
1019 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]);
1020 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1025 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1026 memset(&testtrace, 0, sizeof(trace_t));
1027 rhc.trace = &testtrace;
1028 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1029 rhc.trace->fraction = 1;
1030 rhc.trace->realfraction = 1;
1031 rhc.trace->allsolid = true;
1032 VectorCopy(test, rhc.start);
1033 VectorCopy(test, rhc.end);
1034 VectorClear(rhc.dist);
1035 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1036 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1037 if (!trace->startsolid && testtrace.startsolid)
1038 Con_Printf(" - ended in solid!\n");
1042 if (VectorLength2(rhc.dist))
1043 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1045 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1049 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1051 int num = model->brushq1.hulls[0].firstclipnode;
1053 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1054 mplane_t *planes = model->brushq1.hulls[0].planes;
1057 plane = planes + nodes[num].planenum;
1058 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1060 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1063 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)
1067 colplanef_t cbox_planes[6];
1069 cbox.hasaabbplanes = true;
1070 cbox.supercontents = boxsupercontents;
1073 cbox.numtriangles = 0;
1074 cbox.planes = cbox_planes;
1076 cbox.elements = NULL;
1084 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];
1085 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];
1086 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];
1087 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];
1088 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];
1089 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];
1090 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1091 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1092 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1093 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1094 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1095 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1096 memset(trace, 0, sizeof(trace_t));
1097 trace->hitsupercontentsmask = hitsupercontentsmask;
1098 trace->fraction = 1;
1099 trace->realfraction = 1;
1100 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1102 RecursiveHullCheckTraceInfo_t rhc;
1103 static hull_t box_hull;
1104 static mclipnode_t box_clipnodes[6];
1105 static mplane_t box_planes[6];
1106 // fill in a default trace
1107 memset(&rhc, 0, sizeof(rhc));
1108 memset(trace, 0, sizeof(trace_t));
1109 //To keep everything totally uniform, bounding boxes are turned into small
1110 //BSP trees instead of being compared directly.
1111 // create a temp hull from bounding box sizes
1112 box_planes[0].dist = cmaxs[0] - mins[0];
1113 box_planes[1].dist = cmins[0] - maxs[0];
1114 box_planes[2].dist = cmaxs[1] - mins[1];
1115 box_planes[3].dist = cmins[1] - maxs[1];
1116 box_planes[4].dist = cmaxs[2] - mins[2];
1117 box_planes[5].dist = cmins[2] - maxs[2];
1118 #if COLLISIONPARANOID >= 3
1119 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]);
1122 if (box_hull.clipnodes == NULL)
1126 //Set up the planes and clipnodes so that the six floats of a bounding box
1127 //can just be stored out and get a proper hull_t structure.
1129 box_hull.clipnodes = box_clipnodes;
1130 box_hull.planes = box_planes;
1131 box_hull.firstclipnode = 0;
1132 box_hull.lastclipnode = 5;
1134 for (i = 0;i < 6;i++)
1136 box_clipnodes[i].planenum = i;
1140 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1142 box_clipnodes[i].children[side^1] = i + 1;
1144 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1146 box_planes[i].type = i>>1;
1147 box_planes[i].normal[i>>1] = 1;
1151 // trace a line through the generated clipping hull
1152 //rhc.boxsupercontents = boxsupercontents;
1153 rhc.hull = &box_hull;
1155 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1156 rhc.trace->fraction = 1;
1157 rhc.trace->realfraction = 1;
1158 rhc.trace->allsolid = true;
1159 VectorCopy(start, rhc.start);
1160 VectorCopy(end, rhc.end);
1161 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1162 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1163 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1164 if (rhc.trace->startsupercontents)
1165 rhc.trace->startsupercontents = boxsupercontents;
1169 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)
1171 memset(trace, 0, sizeof(trace_t));
1172 trace->fraction = 1;
1173 trace->realfraction = 1;
1174 if (BoxesOverlap(start, start, cmins, cmaxs))
1176 trace->startsupercontents |= boxsupercontents;
1177 if (hitsupercontentsmask & boxsupercontents)
1179 trace->startsolid = true;
1180 trace->allsolid = true;
1185 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1188 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1189 return trace.fraction == 1;
1192 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(dp_model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1196 float mid, distz = endz - startz;
1200 return false; // didn't hit anything
1202 switch (node->plane->type)
1205 node = node->children[x < node->plane->dist];
1208 node = node->children[y < node->plane->dist];
1211 side = startz < node->plane->dist;
1212 if ((endz < node->plane->dist) == side)
1214 node = node->children[side];
1217 // found an intersection
1218 mid = node->plane->dist;
1221 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1222 front += startz * node->plane->normal[2];
1223 back += endz * node->plane->normal[2];
1224 side = front < node->plane->dist;
1225 if ((back < node->plane->dist) == side)
1227 node = node->children[side];
1230 // found an intersection
1231 mid = startz + distz * (front - node->plane->dist) / (front - back);
1235 // go down front side
1236 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1237 return true; // hit something
1240 // check for impact on this node
1241 if (node->numsurfaces)
1244 int dsi, dti, lmwidth, lmheight;
1246 msurface_t *surface;
1247 unsigned char *lightmap;
1248 int maps, line3, size3;
1251 float scale, w, w00, w01, w10, w11;
1253 surface = model->data_surfaces + node->firstsurface;
1254 for (i = 0;i < node->numsurfaces;i++, surface++)
1256 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1257 continue; // no lightmaps
1259 // location we want to sample in the lightmap
1260 ds = ((x * surface->lightmapinfo->texinfo->vecs[0][0] + y * surface->lightmapinfo->texinfo->vecs[0][1] + mid * surface->lightmapinfo->texinfo->vecs[0][2] + surface->lightmapinfo->texinfo->vecs[0][3]) - surface->lightmapinfo->texturemins[0]) * 0.0625f;
1261 dt = ((x * surface->lightmapinfo->texinfo->vecs[1][0] + y * surface->lightmapinfo->texinfo->vecs[1][1] + mid * surface->lightmapinfo->texinfo->vecs[1][2] + surface->lightmapinfo->texinfo->vecs[1][3]) - surface->lightmapinfo->texturemins[1]) * 0.0625f;
1266 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1267 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1270 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1272 // calculate bilinear interpolation factors
1273 // and also multiply by fixedpoint conversion factors
1276 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1277 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1278 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1279 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1281 // values for pointer math
1282 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1283 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1285 // look up the pixel
1286 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1288 // bilinear filter each lightmap style, and sum them
1289 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1291 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1292 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1293 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1294 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1295 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1299 return true; // success
1304 // go down back side
1305 node = node->children[side ^ 1];
1307 distz = endz - startz;
1312 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1314 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1315 VectorSet(diffusenormal, 0, 0, 1);
1317 if (!model->brushq1.lightdata)
1319 VectorSet(ambientcolor, 1, 1, 1);
1320 VectorSet(diffusecolor, 0, 0, 0);
1324 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);
1327 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1332 const msurface_t *surface;
1337 float edgenormal[3];
1344 surface = model->data_surfaces + node->firstsurface;
1345 for (i = 0;i < node->numsurfaces;i++, surface++)
1347 // skip surfaces whose bounding box does not include the point
1348 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1350 // skip faces with contents we don't care about
1351 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1353 // get the surface normal - since it is flat we know any vertex normal will suffice
1354 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1356 if (DotProduct(t->dist, normal) > 0)
1358 // iterate edges and see if the point is outside one of them
1359 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1361 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1362 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1363 VectorSubtract(v0, v1, edgedir);
1364 CrossProduct(edgedir, normal, edgenormal);
1365 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1368 // if the point is outside one of the edges, it is not within the surface
1369 if (j < surface->num_vertices)
1372 // we hit a surface, this is the impact point...
1373 VectorCopy(normal, t->trace->plane.normal);
1374 t->trace->plane.dist = DotProduct(normal, p);
1376 // calculate the true fraction
1377 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1378 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1379 midf = t1 / (t1 - t2);
1380 t->trace->realfraction = midf;
1382 // calculate the return fraction which is nudged off the surface a bit
1383 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1384 t->trace->fraction = bound(0, midf, 1);
1386 if (collision_prefernudgedfraction.integer)
1387 t->trace->realfraction = t->trace->fraction;
1389 t->trace->hittexture = surface->texture->currentframe;
1390 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1391 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1392 return surface->texture->currentframe;
1397 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])
1399 const mplane_t *plane;
1402 double midf, mid[3];
1403 const mleaf_t *leaf;
1407 plane = node->plane;
1408 if (plane->type < 3)
1410 t1 = p1[plane->type] - plane->dist;
1411 t2 = p2[plane->type] - plane->dist;
1415 t1 = DotProduct (plane->normal, p1) - plane->dist;
1416 t2 = DotProduct (plane->normal, p2) - plane->dist;
1422 node = node->children[1];
1431 node = node->children[0];
1437 // the line intersects, find intersection point
1438 // LordHavoc: this uses the original trace for maximum accuracy
1439 if (plane->type < 3)
1441 t1 = t->start[plane->type] - plane->dist;
1442 t2 = t->end[plane->type] - plane->dist;
1446 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1447 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1450 midf = t1 / (t1 - t2);
1451 VectorMA(t->start, midf, t->dist, mid);
1453 // recurse both sides, front side first, return if we hit a surface
1454 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1455 return HULLCHECKSTATE_DONE;
1457 // test each surface on the node
1458 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1459 if (t->trace->hittexture)
1460 return HULLCHECKSTATE_DONE;
1462 // recurse back side
1463 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1465 leaf = (const mleaf_t *)node;
1466 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1467 if (!t->trace->startfound)
1469 t->trace->startfound = true;
1470 t->trace->startsupercontents |= side;
1472 if (side & SUPERCONTENTS_LIQUIDSMASK)
1473 t->trace->inwater = true;
1475 t->trace->inopen = true;
1476 if (side & t->trace->hitsupercontentsmask)
1478 // if the first leaf is solid, set startsolid
1479 if (t->trace->allsolid)
1480 t->trace->startsolid = true;
1481 return HULLCHECKSTATE_SOLID;
1485 t->trace->allsolid = false;
1486 return HULLCHECKSTATE_EMPTY;
1490 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)
1492 RecursiveHullCheckTraceInfo_t rhc;
1494 memset(&rhc, 0, sizeof(rhc));
1495 memset(trace, 0, sizeof(trace_t));
1497 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1498 rhc.trace->fraction = 1;
1499 rhc.trace->realfraction = 1;
1500 rhc.trace->allsolid = true;
1501 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1502 VectorCopy(start, rhc.start);
1503 VectorCopy(end, rhc.end);
1504 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1505 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1506 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1509 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1512 unsigned char *outstart = out;
1513 while (out < outend)
1517 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));
1527 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));
1530 for (c = *in++;c > 0;c--)
1534 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));
1545 R_Q1BSP_LoadSplitSky
1547 A sky texture is 256*128, with the right side being a masked overlay
1550 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1555 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1556 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1558 // allocate a texture pool if we need it
1559 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1560 loadmodel->texturepool = R_AllocTexturePool();
1562 if (bytesperpixel == 4)
1564 for (y = 0;y < h;y++)
1566 for (x = 0;x < w;x++)
1568 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1569 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1575 // make an average value for the back to avoid
1576 // a fringe on the top level
1585 for (y = 0;y < h;y++)
1587 for (x = 0;x < w;x++)
1589 p = src[x*width+y+w];
1590 r += palette_rgb[p][0];
1591 g += palette_rgb[p][1];
1592 b += palette_rgb[p][2];
1595 bgra.b[2] = r/(w*h);
1596 bgra.b[1] = g/(w*h);
1597 bgra.b[0] = b/(w*h);
1599 for (y = 0;y < h;y++)
1601 for (x = 0;x < w;x++)
1603 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1605 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1610 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1611 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1612 Mem_Free(solidpixels);
1613 Mem_Free(alphapixels);
1616 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1618 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1619 skinframe_t *skinframe;
1620 texture_t *tx, *tx2, *anims[10], *altanims[10];
1621 texture_t backuptex;
1622 unsigned char *data, *mtdata;
1624 char mapname[MAX_QPATH], name[MAX_QPATH];
1625 unsigned char zeroopaque[4], zerotrans[4];
1628 Vector4Set(zeroopaque, 0, 0, 0, 255);
1629 Vector4Set(zerotrans, 0, 0, 0, 128);
1631 loadmodel->data_textures = NULL;
1633 // add two slots for notexture walls and notexture liquids
1636 nummiptex = MSG_ReadLittleLong(sb);
1637 loadmodel->num_textures = nummiptex + 2;
1638 loadmodel->num_texturesperskin = loadmodel->num_textures;
1642 loadmodel->num_textures = 2;
1643 loadmodel->num_texturesperskin = loadmodel->num_textures;
1646 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1648 // fill out all slots with notexture
1649 if (cls.state != ca_dedicated)
1650 skinframe = R_SkinFrame_LoadMissing();
1653 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1655 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1658 if (cls.state != ca_dedicated)
1660 tx->numskinframes = 1;
1661 tx->skinframerate = 1;
1662 tx->skinframes[0] = skinframe;
1663 tx->currentskinframe = tx->skinframes[0];
1665 tx->basematerialflags = MATERIALFLAG_WALL;
1666 if (i == loadmodel->num_textures - 1)
1668 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1669 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1670 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1674 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1675 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1677 tx->currentframe = tx;
1679 // clear water settings
1682 tx->refractfactor = 1;
1683 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1684 tx->reflectfactor = 1;
1685 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1686 tx->r_water_wateralpha = 1;
1687 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1688 tx->offsetscale = 1;
1690 tx->specularscalemod = 1;
1691 tx->specularpowermod = 1;
1692 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1693 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1694 // JUST GREP FOR "specularscalemod = 1".
1699 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1703 s = loadmodel->name;
1704 if (!strncasecmp(s, "maps/", 5))
1706 FS_StripExtension(s, mapname, sizeof(mapname));
1708 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1709 // LordHavoc: mostly rewritten map texture loader
1710 for (i = 0;i < nummiptex;i++)
1712 doffset = MSG_ReadLittleLong(sb);
1713 if (r_nosurftextures.integer)
1717 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1721 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1723 // copy name, but only up to 16 characters
1724 // (the output buffer can hold more than this, but the input buffer is
1726 for (j = 0;j < 16;j++)
1727 name[j] = MSG_ReadByte(&miptexsb);
1729 // pretty up the buffer (replacing any trailing garbage with 0)
1730 for (j = strlen(name);j < 16;j++)
1735 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1736 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1739 mtwidth = MSG_ReadLittleLong(&miptexsb);
1740 mtheight = MSG_ReadLittleLong(&miptexsb);
1742 j = MSG_ReadLittleLong(&miptexsb);
1746 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1748 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1751 mtdata = miptexsb.data + j;
1754 if ((mtwidth & 15) || (mtheight & 15))
1755 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1757 // LordHavoc: force all names to lowercase
1758 for (j = 0;name[j];j++)
1759 if (name[j] >= 'A' && name[j] <= 'Z')
1760 name[j] += 'a' - 'A';
1762 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1763 backuptex = loadmodel->data_textures[i];
1764 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1766 loadmodel->data_textures[i] = backuptex;
1768 tx = loadmodel->data_textures + i;
1769 strlcpy(tx->name, name, sizeof(tx->name));
1770 tx->width = mtwidth;
1771 tx->height = mtheight;
1773 if (tx->name[0] == '*')
1775 if (!strncmp(tx->name, "*lava", 5))
1777 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1778 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1780 else if (!strncmp(tx->name, "*slime", 6))
1782 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1783 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1787 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1788 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1791 else if (!strncmp(tx->name, "sky", 3))
1793 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1794 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1795 // for the surface traceline we need to hit this surface as a solid...
1796 tx->supercontents |= SUPERCONTENTS_SOLID;
1800 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1801 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1804 if (cls.state != ca_dedicated)
1806 // LordHavoc: HL sky textures are entirely different than quake
1807 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1809 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1811 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1812 if (data && image_width == image_height * 2)
1814 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1817 else if (mtdata != NULL)
1818 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1822 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);
1824 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);
1826 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1829 // did not find external texture, load it from the bsp or wad3
1830 if (loadmodel->brush.ishlbsp)
1832 // internal texture overrides wad
1833 unsigned char *pixels, *freepixels;
1834 pixels = freepixels = NULL;
1836 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1838 pixels = freepixels = W_GetTextureBGRA(tx->name);
1841 tx->width = image_width;
1842 tx->height = image_height;
1843 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1846 Mem_Free(freepixels);
1848 else if (mtdata) // texture included
1849 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1851 // if skinframe is still NULL the "missing" texture will be used
1853 tx->skinframes[0] = skinframe;
1855 // LordHavoc: some Tenebrae textures get replaced by black
1856 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1857 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1858 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1859 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1862 tx->basematerialflags = MATERIALFLAG_WALL;
1863 if (tx->name[0] == '*')
1865 // LordHavoc: some turbulent textures should not be affected by wateralpha
1866 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1867 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1868 else if (!strncmp(tx->name,"*lava",5)
1869 || !strncmp(tx->name,"*teleport",9)
1870 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1871 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1873 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1874 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1875 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1877 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1879 // replace the texture with black
1880 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1882 else if (!strncmp(tx->name, "sky", 3))
1883 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1884 else if (!strcmp(tx->name, "caulk"))
1885 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1886 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1887 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1889 // start out with no animation
1890 tx->currentframe = tx;
1891 tx->currentskinframe = tx->skinframes[0];
1892 tx->currentmaterialflags = tx->basematerialflags;
1895 // sequence the animations
1896 for (i = 0;i < nummiptex;i++)
1898 tx = loadmodel->data_textures + i;
1899 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1901 if (tx->anim_total[0] || tx->anim_total[1])
1902 continue; // already sequenced
1904 // find the number of frames in the animation
1905 memset(anims, 0, sizeof(anims));
1906 memset(altanims, 0, sizeof(altanims));
1908 for (j = i;j < nummiptex;j++)
1910 tx2 = loadmodel->data_textures + j;
1911 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1915 if (num >= '0' && num <= '9')
1916 anims[num - '0'] = tx2;
1917 else if (num >= 'a' && num <= 'j')
1918 altanims[num - 'a'] = tx2;
1920 Con_Printf("Bad animating texture %s\n", tx->name);
1924 for (j = 0;j < 10;j++)
1931 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1934 for (j = 0;j < max;j++)
1938 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1942 for (j = 0;j < altmax;j++)
1946 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1955 // if there is no alternate animation, duplicate the primary
1956 // animation into the alternate
1958 for (k = 0;k < 10;k++)
1959 altanims[k] = anims[k];
1962 // link together the primary animation
1963 for (j = 0;j < max;j++)
1966 tx2->animated = true;
1967 tx2->anim_total[0] = max;
1968 tx2->anim_total[1] = altmax;
1969 for (k = 0;k < 10;k++)
1971 tx2->anim_frames[0][k] = anims[k];
1972 tx2->anim_frames[1][k] = altanims[k];
1976 // if there really is an alternate anim...
1977 if (anims[0] != altanims[0])
1979 // link together the alternate animation
1980 for (j = 0;j < altmax;j++)
1983 tx2->animated = true;
1984 // the primary/alternate are reversed here
1985 tx2->anim_total[0] = altmax;
1986 tx2->anim_total[1] = max;
1987 for (k = 0;k < 10;k++)
1989 tx2->anim_frames[0][k] = altanims[k];
1990 tx2->anim_frames[1][k] = anims[k];
1997 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2000 unsigned char *in, *out, *data, d;
2001 char litfilename[MAX_QPATH];
2002 char dlitfilename[MAX_QPATH];
2003 fs_offset_t filesize;
2004 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2006 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2007 for (i = 0;i < sb->cursize;i++)
2008 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2010 else // LordHavoc: bsp version 29 (normal white lighting)
2012 // LordHavoc: hope is not lost yet, check for a .lit file to load
2013 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2014 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2015 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2016 strlcat (litfilename, ".lit", sizeof (litfilename));
2017 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2018 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2021 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2023 i = LittleLong(((int *)data)[1]);
2026 if (developer_loading.integer)
2027 Con_Printf("loaded %s\n", litfilename);
2028 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2029 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2031 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2034 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2036 i = LittleLong(((int *)data)[1]);
2039 if (developer_loading.integer)
2040 Con_Printf("loaded %s\n", dlitfilename);
2041 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2042 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2043 loadmodel->brushq3.deluxemapping_modelspace = false;
2044 loadmodel->brushq3.deluxemapping = true;
2053 Con_Printf("Unknown .lit file version (%d)\n", i);
2055 else if (filesize == 8)
2056 Con_Print("Empty .lit file, ignoring\n");
2058 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2065 // LordHavoc: oh well, expand the white lighting data
2068 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2070 out = loadmodel->brushq1.lightdata;
2071 for (i = 0;i < sb->cursize;i++)
2081 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2083 loadmodel->brushq1.num_compressedpvs = 0;
2084 loadmodel->brushq1.data_compressedpvs = NULL;
2087 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2088 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2089 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2092 // used only for HalfLife maps
2093 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2095 char key[128], value[4096];
2099 if (!COM_ParseToken_Simple(&data, false, false, true))
2101 if (com_token[0] != '{')
2105 if (!COM_ParseToken_Simple(&data, false, false, true))
2107 if (com_token[0] == '}')
2108 break; // end of worldspawn
2109 if (com_token[0] == '_')
2110 strlcpy(key, com_token + 1, sizeof(key));
2112 strlcpy(key, com_token, sizeof(key));
2113 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2114 key[strlen(key)-1] = 0;
2115 if (!COM_ParseToken_Simple(&data, false, false, true))
2117 dpsnprintf(value, sizeof(value), "%s", com_token);
2118 if (!strcmp("wad", key)) // for HalfLife maps
2120 if (loadmodel->brush.ishlbsp)
2123 for (i = 0;i < (int)sizeof(value);i++)
2124 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2128 for (;i < (int)sizeof(value);i++)
2130 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2131 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2133 else if (value[i] == ';' || value[i] == 0)
2137 W_LoadTextureWadFile(&value[j], false);
2149 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2151 loadmodel->brush.entities = NULL;
2154 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2155 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2156 loadmodel->brush.entities[sb->cursize] = 0;
2157 if (loadmodel->brush.ishlbsp)
2158 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2162 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2166 size_t structsize = 12;
2168 if (sb->cursize % structsize)
2169 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2170 count = sb->cursize / structsize;
2171 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2173 loadmodel->brushq1.vertexes = out;
2174 loadmodel->brushq1.numvertexes = count;
2176 for ( i=0 ; i<count ; i++, out++)
2178 out->position[0] = MSG_ReadLittleFloat(sb);
2179 out->position[1] = MSG_ReadLittleFloat(sb);
2180 out->position[2] = MSG_ReadLittleFloat(sb);
2184 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2188 size_t structsize = (48+4*hullinfo->filehulls);
2190 if (sb->cursize % structsize)
2191 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2193 count = sb->cursize / structsize;
2194 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2196 loadmodel->brushq1.submodels = out;
2197 loadmodel->brush.numsubmodels = count;
2199 for (i = 0; i < count; i++, out++)
2201 // spread out the mins / maxs by a pixel
2202 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2203 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2204 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2205 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2206 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2207 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2208 out->origin[0] = MSG_ReadLittleFloat(sb);
2209 out->origin[1] = MSG_ReadLittleFloat(sb);
2210 out->origin[2] = MSG_ReadLittleFloat(sb);
2211 for (j = 0; j < hullinfo->filehulls; j++)
2212 out->headnode[j] = MSG_ReadLittleLong(sb);
2213 out->visleafs = MSG_ReadLittleLong(sb);
2214 out->firstface = MSG_ReadLittleLong(sb);
2215 out->numfaces = MSG_ReadLittleLong(sb);
2219 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2223 size_t structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2225 if (sb->cursize % structsize)
2226 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2227 count = sb->cursize / structsize;
2228 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2230 loadmodel->brushq1.edges = out;
2231 loadmodel->brushq1.numedges = count;
2233 for ( i=0 ; i<count ; i++, out++)
2235 if (loadmodel->brush.isbsp2)
2237 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2238 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2242 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2243 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2245 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2247 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);
2248 if(!loadmodel->brushq1.numvertexes)
2249 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2257 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2260 int i, j, k, count, miptex;
2261 size_t structsize = 40;
2263 if (sb->cursize % structsize)
2264 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2265 count = sb->cursize / structsize;
2266 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2268 loadmodel->brushq1.texinfo = out;
2269 loadmodel->brushq1.numtexinfo = count;
2271 for (i = 0;i < count;i++, out++)
2273 for (k = 0;k < 2;k++)
2274 for (j = 0;j < 4;j++)
2275 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2277 miptex = MSG_ReadLittleLong(sb);
2278 out->flags = MSG_ReadLittleLong(sb);
2280 out->texture = NULL;
2281 if (loadmodel->data_textures)
2283 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2284 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2286 out->texture = loadmodel->data_textures + miptex;
2288 if (out->flags & TEX_SPECIAL)
2290 // if texture chosen is NULL or the shader needs a lightmap,
2291 // force to notexture water shader
2292 if (out->texture == NULL)
2293 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2297 // if texture chosen is NULL, force to notexture
2298 if (out->texture == NULL)
2299 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2305 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2310 mins[0] = mins[1] = mins[2] = 9999;
2311 maxs[0] = maxs[1] = maxs[2] = -9999;
2313 for (i = 0;i < numverts;i++)
2315 for (j = 0;j < 3;j++, v++)
2325 #define MAX_SUBDIVPOLYTRIANGLES 4096
2326 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2328 static int subdivpolyverts, subdivpolytriangles;
2329 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2330 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2332 static int subdivpolylookupvert(vec3_t v)
2335 for (i = 0;i < subdivpolyverts;i++)
2336 if (subdivpolyvert[i][0] == v[0]
2337 && subdivpolyvert[i][1] == v[1]
2338 && subdivpolyvert[i][2] == v[2])
2340 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2341 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2342 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2343 return subdivpolyverts++;
2346 static void SubdividePolygon(int numverts, float *verts)
2348 int i, i1, i2, i3, f, b, c, p;
2349 vec3_t mins, maxs, front[256], back[256];
2350 float m, *pv, *cv, dist[256], frac;
2353 Host_Error("SubdividePolygon: ran out of verts in buffer");
2355 BoundPoly(numverts, verts, mins, maxs);
2357 for (i = 0;i < 3;i++)
2359 m = (mins[i] + maxs[i]) * 0.5;
2360 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2361 if (maxs[i] - m < 8)
2363 if (m - mins[i] < 8)
2367 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2368 dist[c] = cv[i] - m;
2371 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2375 VectorCopy(pv, front[f]);
2380 VectorCopy(pv, back[b]);
2383 if (dist[p] == 0 || dist[c] == 0)
2385 if ((dist[p] > 0) != (dist[c] > 0) )
2388 frac = dist[p] / (dist[p] - dist[c]);
2389 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2390 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2391 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2397 SubdividePolygon(f, front[0]);
2398 SubdividePolygon(b, back[0]);
2402 i1 = subdivpolylookupvert(verts);
2403 i2 = subdivpolylookupvert(verts + 3);
2404 for (i = 2;i < numverts;i++)
2406 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2408 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2412 i3 = subdivpolylookupvert(verts + i * 3);
2413 subdivpolyindex[subdivpolytriangles][0] = i1;
2414 subdivpolyindex[subdivpolytriangles][1] = i2;
2415 subdivpolyindex[subdivpolytriangles][2] = i3;
2417 subdivpolytriangles++;
2421 //Breaks a polygon up along axial 64 unit
2422 //boundaries so that turbulent and sky warps
2423 //can be done reasonably.
2424 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2430 subdivpolytriangles = 0;
2431 subdivpolyverts = 0;
2432 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2433 if (subdivpolytriangles < 1)
2434 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2436 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2437 mesh->num_vertices = subdivpolyverts;
2438 mesh->num_triangles = subdivpolytriangles;
2439 mesh->vertex = (surfvertex_t *)(mesh + 1);
2440 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2441 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2443 for (i = 0;i < mesh->num_triangles;i++)
2444 for (j = 0;j < 3;j++)
2445 mesh->index[i*3+j] = subdivpolyindex[i][j];
2447 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2449 VectorCopy(subdivpolyvert[i], v->v);
2450 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2451 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2456 extern cvar_t gl_max_lightmapsize;
2457 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2459 msurface_t *surface;
2460 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2461 float texmins[2], texmaxs[2], val;
2462 rtexture_t *lightmaptexture, *deluxemaptexture;
2464 size_t structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2466 if (sb->cursize % structsize)
2467 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2468 count = sb->cursize / structsize;
2469 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2470 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2472 loadmodel->num_surfaces = count;
2474 loadmodel->brushq1.firstrender = true;
2475 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2479 for (surfacenum = 0;surfacenum < count;surfacenum++)
2481 if (loadmodel->brush.isbsp2)
2482 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2484 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2485 totalverts += numedges;
2486 totaltris += numedges - 2;
2489 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2491 lightmaptexture = NULL;
2492 deluxemaptexture = r_texture_blanknormalmap;
2494 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2495 totallightmapsamples = 0;
2499 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2501 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2502 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2503 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2504 firstedge = MSG_ReadLittleLong(sb);
2505 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2506 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2507 for (i = 0;i < MAXLIGHTMAPS;i++)
2508 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2509 lightmapoffset = MSG_ReadLittleLong(sb);
2511 // FIXME: validate edges, texinfo, etc?
2512 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)
2513 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2514 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2515 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2516 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2517 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2519 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2520 surface->texture = surface->lightmapinfo->texinfo->texture;
2522 //surface->flags = surface->texture->flags;
2523 //if (LittleShort(in->side))
2524 // surface->flags |= SURF_PLANEBACK;
2525 //surface->plane = loadmodel->brush.data_planes + planenum;
2527 surface->num_firstvertex = totalverts;
2528 surface->num_vertices = numedges;
2529 surface->num_firsttriangle = totaltris;
2530 surface->num_triangles = numedges - 2;
2531 totalverts += numedges;
2532 totaltris += numedges - 2;
2534 // convert edges back to a normal polygon
2535 for (i = 0;i < surface->num_vertices;i++)
2537 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2539 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2541 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2543 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2544 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2545 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2546 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2547 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2548 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2549 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2550 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2553 for (i = 0;i < surface->num_triangles;i++)
2555 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2556 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2557 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2560 // compile additional data about the surface geometry
2561 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);
2562 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);
2563 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2565 // generate surface extents information
2566 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2567 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2568 for (i = 1;i < surface->num_vertices;i++)
2570 for (j = 0;j < 2;j++)
2572 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2573 texmins[j] = min(texmins[j], val);
2574 texmaxs[j] = max(texmaxs[j], val);
2577 for (i = 0;i < 2;i++)
2579 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2580 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2583 smax = surface->lightmapinfo->extents[0] >> 4;
2584 tmax = surface->lightmapinfo->extents[1] >> 4;
2585 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2586 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2589 surface->lightmaptexture = NULL;
2590 surface->deluxemaptexture = r_texture_blanknormalmap;
2591 if (lightmapoffset == -1)
2593 surface->lightmapinfo->samples = NULL;
2595 // give non-lightmapped water a 1x white lightmap
2596 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2598 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2599 surface->lightmapinfo->styles[0] = 0;
2600 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2604 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2605 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2606 else // LordHavoc: white lighting (bsp version 29)
2608 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2609 if (loadmodel->brushq1.nmaplightdata)
2610 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2613 // check if we should apply a lightmap to this
2614 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2616 if (ssize > 256 || tsize > 256)
2617 Host_Error("Bad surface extents");
2619 if (lightmapsize < ssize)
2620 lightmapsize = ssize;
2621 if (lightmapsize < tsize)
2622 lightmapsize = tsize;
2624 totallightmapsamples += ssize*tsize;
2626 // force lightmap upload on first time seeing the surface
2628 // additionally this is used by the later code to see if a
2629 // lightmap is needed on this surface (rather than duplicating the
2631 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2632 loadmodel->lit = true;
2636 // small maps (such as ammo boxes especially) don't need big lightmap
2637 // textures, so this code tries to guess a good size based on
2638 // totallightmapsamples (size of the lightmaps lump basically), as well as
2639 // trying to max out the size if there is a lot of lightmap data to store
2640 // additionally, never choose a lightmapsize that is smaller than the
2641 // largest surface encountered (as it would fail)
2643 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2646 // now that we've decided the lightmap texture size, we can do the rest
2647 if (cls.state != ca_dedicated)
2649 int stainmapsize = 0;
2650 mod_alloclightmap_state_t allocState;
2652 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2653 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2655 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2656 float u, v, ubase, vbase, uscale, vscale;
2658 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2661 smax = surface->lightmapinfo->extents[0] >> 4;
2662 tmax = surface->lightmapinfo->extents[1] >> 4;
2663 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2664 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2665 stainmapsize += ssize * tsize * 3;
2667 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2669 // allocate a texture pool if we need it
2670 if (loadmodel->texturepool == NULL)
2671 loadmodel->texturepool = R_AllocTexturePool();
2672 // could not find room, make a new lightmap
2673 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2674 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2675 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2676 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);
2677 if (loadmodel->brushq1.nmaplightdata)
2678 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);
2680 Mod_AllocLightmap_Reset(&allocState);
2681 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2683 surface->lightmaptexture = lightmaptexture;
2684 surface->deluxemaptexture = deluxemaptexture;
2685 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2686 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2688 uscale = 1.0f / (float)lightmapsize;
2689 vscale = 1.0f / (float)lightmapsize;
2690 ubase = lightmapx * uscale;
2691 vbase = lightmapy * vscale;
2693 for (i = 0;i < surface->num_vertices;i++)
2695 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);
2696 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);
2697 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2698 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2699 // LordHavoc: calc lightmap data offset for vertex lighting to use
2702 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2706 if (cl_stainmaps.integer)
2708 // allocate stainmaps for permanent marks on walls and clear white
2709 unsigned char *stainsamples = NULL;
2710 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2711 memset(stainsamples, 255, stainmapsize);
2713 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2715 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2717 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2718 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2719 surface->lightmapinfo->stainsamples = stainsamples;
2720 stainsamples += ssize * tsize * 3;
2725 // generate ushort elements array if possible
2726 if (loadmodel->surfmesh.data_element3s)
2727 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2728 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2731 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2734 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2735 node->parent = parent;
2738 // this is a node, recurse to children
2739 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2740 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2741 // combine supercontents of children
2742 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2747 mleaf_t *leaf = (mleaf_t *)node;
2748 // if this is a leaf, calculate supercontents mask from all collidable
2749 // primitives in the leaf (brushes and collision surfaces)
2750 // also flag if the leaf contains any collision surfaces
2751 leaf->combinedsupercontents = 0;
2752 // combine the supercontents values of all brushes in this leaf
2753 for (j = 0;j < leaf->numleafbrushes;j++)
2754 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2755 // check if this leaf contains any collision surfaces (q3 patches)
2756 for (j = 0;j < leaf->numleafsurfaces;j++)
2758 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2759 if (surface->num_collisiontriangles)
2761 leaf->containscollisionsurfaces = true;
2762 leaf->combinedsupercontents |= surface->texture->supercontents;
2768 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2770 int i, j, count, p, child[2];
2772 size_t structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2774 if (sb->cursize % structsize)
2775 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2776 count = sb->cursize / structsize;
2778 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2779 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2781 loadmodel->brush.data_nodes = out;
2782 loadmodel->brush.num_nodes = count;
2784 for ( i=0 ; i<count ; i++, out++)
2786 p = MSG_ReadLittleLong(sb);
2787 out->plane = loadmodel->brush.data_planes + p;
2789 if (loadmodel->brush.isbsp2rmqe)
2791 child[0] = MSG_ReadLittleLong(sb);
2792 child[1] = MSG_ReadLittleLong(sb);
2793 out->mins[0] = MSG_ReadLittleShort(sb);
2794 out->mins[1] = MSG_ReadLittleShort(sb);
2795 out->mins[2] = MSG_ReadLittleShort(sb);
2796 out->maxs[0] = MSG_ReadLittleShort(sb);
2797 out->maxs[1] = MSG_ReadLittleShort(sb);
2798 out->maxs[2] = MSG_ReadLittleShort(sb);
2799 out->firstsurface = MSG_ReadLittleLong(sb);
2800 out->numsurfaces = MSG_ReadLittleLong(sb);
2802 else if (loadmodel->brush.isbsp2)
2804 child[0] = MSG_ReadLittleLong(sb);
2805 child[1] = MSG_ReadLittleLong(sb);
2806 out->mins[0] = MSG_ReadLittleFloat(sb);
2807 out->mins[1] = MSG_ReadLittleFloat(sb);
2808 out->mins[2] = MSG_ReadLittleFloat(sb);
2809 out->maxs[0] = MSG_ReadLittleFloat(sb);
2810 out->maxs[1] = MSG_ReadLittleFloat(sb);
2811 out->maxs[2] = MSG_ReadLittleFloat(sb);
2812 out->firstsurface = MSG_ReadLittleLong(sb);
2813 out->numsurfaces = MSG_ReadLittleLong(sb);
2817 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2818 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2819 if (child[0] >= count)
2821 if (child[1] >= count)
2824 out->mins[0] = MSG_ReadLittleShort(sb);
2825 out->mins[1] = MSG_ReadLittleShort(sb);
2826 out->mins[2] = MSG_ReadLittleShort(sb);
2827 out->maxs[0] = MSG_ReadLittleShort(sb);
2828 out->maxs[1] = MSG_ReadLittleShort(sb);
2829 out->maxs[2] = MSG_ReadLittleShort(sb);
2831 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2832 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2835 for (j=0 ; j<2 ; j++)
2837 // LordHavoc: this code supports broken bsp files produced by
2838 // arguire qbsp which can produce more than 32768 nodes, any value
2839 // below count is assumed to be a node number, any other value is
2840 // assumed to be a leaf number
2844 if (p < loadmodel->brush.num_nodes)
2845 out->children[j] = loadmodel->brush.data_nodes + p;
2848 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2849 // map it to the solid leaf
2850 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2855 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2857 if (p < loadmodel->brush.num_leafs)
2858 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2861 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2862 // map it to the solid leaf
2863 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2869 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2872 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2875 int i, j, count, p, firstmarksurface, nummarksurfaces;
2876 size_t structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2878 if (sb->cursize % structsize)
2879 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2880 count = sb->cursize / structsize;
2881 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2883 loadmodel->brush.data_leafs = out;
2884 loadmodel->brush.num_leafs = count;
2885 // get visleafs from the submodel data
2886 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2887 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2888 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2889 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2891 // FIXME: this function could really benefit from some error checking
2892 for ( i=0 ; i<count ; i++, out++)
2894 out->contents = MSG_ReadLittleLong(sb);
2896 out->clusterindex = i - 1;
2897 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2898 out->clusterindex = -1;
2900 p = MSG_ReadLittleLong(sb);
2901 // ignore visofs errors on leaf 0 (solid)
2902 if (p >= 0 && out->clusterindex >= 0)
2904 if (p >= loadmodel->brushq1.num_compressedpvs)
2905 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2907 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);
2910 if (loadmodel->brush.isbsp2rmqe)
2912 out->mins[0] = MSG_ReadLittleShort(sb);
2913 out->mins[1] = MSG_ReadLittleShort(sb);
2914 out->mins[2] = MSG_ReadLittleShort(sb);
2915 out->maxs[0] = MSG_ReadLittleShort(sb);
2916 out->maxs[1] = MSG_ReadLittleShort(sb);
2917 out->maxs[2] = MSG_ReadLittleShort(sb);
2919 firstmarksurface = MSG_ReadLittleLong(sb);
2920 nummarksurfaces = MSG_ReadLittleLong(sb);
2922 else if (loadmodel->brush.isbsp2)
2924 out->mins[0] = MSG_ReadLittleFloat(sb);
2925 out->mins[1] = MSG_ReadLittleFloat(sb);
2926 out->mins[2] = MSG_ReadLittleFloat(sb);
2927 out->maxs[0] = MSG_ReadLittleFloat(sb);
2928 out->maxs[1] = MSG_ReadLittleFloat(sb);
2929 out->maxs[2] = MSG_ReadLittleFloat(sb);
2931 firstmarksurface = MSG_ReadLittleLong(sb);
2932 nummarksurfaces = MSG_ReadLittleLong(sb);
2936 out->mins[0] = MSG_ReadLittleShort(sb);
2937 out->mins[1] = MSG_ReadLittleShort(sb);
2938 out->mins[2] = MSG_ReadLittleShort(sb);
2939 out->maxs[0] = MSG_ReadLittleShort(sb);
2940 out->maxs[1] = MSG_ReadLittleShort(sb);
2941 out->maxs[2] = MSG_ReadLittleShort(sb);
2943 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2944 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2947 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2949 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2950 out->numleafsurfaces = nummarksurfaces;
2954 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2955 out->firstleafsurface = NULL;
2956 out->numleafsurfaces = 0;
2959 for (j = 0;j < 4;j++)
2960 out->ambient_sound_level[j] = MSG_ReadByte(sb);
2964 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2968 const unsigned char *pvs;
2969 // if there's no vis data, assume supported (because everything is visible all the time)
2970 if (!loadmodel->brush.data_pvsclusters)
2972 // check all liquid leafs to see if they can see into empty leafs, if any
2973 // can we can assume this map supports r_wateralpha
2974 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2976 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2978 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2979 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2980 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2987 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
2992 size_t structsize = loadmodel->brush.isbsp2 ? 12 : 8;
2994 if (sb->cursize % structsize)
2995 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2996 count = sb->cursize / structsize;
2997 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2999 loadmodel->brushq1.clipnodes = out;
3000 loadmodel->brushq1.numclipnodes = count;
3002 for (i = 1; i < MAX_MAP_HULLS; i++)
3004 hull = &loadmodel->brushq1.hulls[i];
3005 hull->clipnodes = out;
3006 hull->firstclipnode = 0;
3007 hull->lastclipnode = count-1;
3008 hull->planes = loadmodel->brush.data_planes;
3009 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3010 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3011 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3012 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3013 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3014 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3015 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3018 for (i=0 ; i<count ; i++, out++)
3020 out->planenum = MSG_ReadLittleLong(sb);
3021 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3022 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3023 if (loadmodel->brush.isbsp2)
3025 out->children[0] = MSG_ReadLittleLong(sb);
3026 out->children[1] = MSG_ReadLittleLong(sb);
3027 if (out->children[0] >= count)
3028 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3029 if (out->children[1] >= count)
3030 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3034 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3035 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3036 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3037 if (out->children[0] >= count)
3038 out->children[0] -= 65536;
3039 if (out->children[1] >= count)
3040 out->children[1] -= 65536;
3045 //Duplicate the drawing hull structure as a clipping hull
3046 static void Mod_Q1BSP_MakeHull0(void)
3053 hull = &loadmodel->brushq1.hulls[0];
3055 in = loadmodel->brush.data_nodes;
3056 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3058 hull->clipnodes = out;
3059 hull->firstclipnode = 0;
3060 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3061 hull->planes = loadmodel->brush.data_planes;
3063 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3065 out->planenum = in->plane - loadmodel->brush.data_planes;
3066 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3067 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3071 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3074 size_t structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3076 if (sb->cursize % structsize)
3077 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3078 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3079 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3081 if (loadmodel->brush.isbsp2)
3083 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3085 j = MSG_ReadLittleLong(sb);
3086 if (j < 0 || j >= loadmodel->num_surfaces)
3087 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3088 loadmodel->brush.data_leafsurfaces[i] = j;
3093 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3095 j = (unsigned short) MSG_ReadLittleShort(sb);
3096 if (j >= loadmodel->num_surfaces)
3097 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3098 loadmodel->brush.data_leafsurfaces[i] = j;
3103 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3106 size_t structsize = 4;
3108 if (sb->cursize % structsize)
3109 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3110 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3111 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3113 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3114 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3118 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3122 size_t structsize = 20;
3124 if (sb->cursize % structsize)
3125 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3126 loadmodel->brush.num_planes = sb->cursize / structsize;
3127 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3129 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3131 out->normal[0] = MSG_ReadLittleFloat(sb);
3132 out->normal[1] = MSG_ReadLittleFloat(sb);
3133 out->normal[2] = MSG_ReadLittleFloat(sb);
3134 out->dist = MSG_ReadLittleFloat(sb);
3135 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3140 static void Mod_Q1BSP_LoadMapBrushes(void)
3144 int submodel, numbrushes;
3145 qboolean firstbrush;
3146 char *text, *maptext;
3147 char mapfilename[MAX_QPATH];
3148 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3149 strlcat (mapfilename, ".map", sizeof (mapfilename));
3150 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3154 if (!COM_ParseToken_Simple(&data, false, false, true))
3159 if (!COM_ParseToken_Simple(&data, false, false, true))
3161 if (com_token[0] != '{')
3167 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3170 if (!COM_ParseToken_Simple(&data, false, false, true))
3172 if (com_token[0] == '}')
3173 break; // end of entity
3174 if (com_token[0] == '{')
3181 if (submodel > loadmodel->brush.numsubmodels)
3183 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3187 model = loadmodel->brush.submodels[submodel];
3194 if (!COM_ParseToken_Simple(&data, false, false, true))
3196 if (com_token[0] == '}')
3197 break; // end of brush
3198 // each brush face should be this format:
3199 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3200 // FIXME: support hl .map format
3201 for (pointnum = 0;pointnum < 3;pointnum++)
3203 COM_ParseToken_Simple(&data, false, false, true);
3204 for (componentnum = 0;componentnum < 3;componentnum++)
3206 COM_ParseToken_Simple(&data, false, false, true);
3207 point[pointnum][componentnum] = atof(com_token);
3209 COM_ParseToken_Simple(&data, false, false, true);
3211 COM_ParseToken_Simple(&data, false, false, true);
3212 strlcpy(facetexture, com_token, sizeof(facetexture));
3213 COM_ParseToken_Simple(&data, false, false, true);
3214 //scroll_s = atof(com_token);
3215 COM_ParseToken_Simple(&data, false, false, true);
3216 //scroll_t = atof(com_token);
3217 COM_ParseToken_Simple(&data, false, false, true);
3218 //rotate = atof(com_token);
3219 COM_ParseToken_Simple(&data, false, false, true);
3220 //scale_s = atof(com_token);
3221 COM_ParseToken_Simple(&data, false, false, true);
3222 //scale_t = atof(com_token);
3223 TriangleNormal(point[0], point[1], point[2], planenormal);
3224 VectorNormalizeDouble(planenormal);
3225 planedist = DotProduct(point[0], planenormal);
3226 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3236 #define MAX_PORTALPOINTS 64
3238 typedef struct portal_s
3241 mnode_t *nodes[2]; // [0] = front side of plane
3242 struct portal_s *next[2];
3244 double points[3*MAX_PORTALPOINTS];
3245 struct portal_s *chain; // all portals are linked into a list
3249 static memexpandablearray_t portalarray;
3251 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3253 // process only nodes (leafs already had their box calculated)
3257 // calculate children first
3258 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3259 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3261 // make combined bounding box from children
3262 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3263 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3264 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3265 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3266 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3267 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3270 static void Mod_Q1BSP_FinalizePortals(void)
3272 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3276 mleaf_t *leaf, *endleaf;
3278 // tally up portal and point counts and recalculate bounding boxes for all
3279 // leafs (because qbsp is very sloppy)
3280 leaf = loadmodel->brush.data_leafs;
3281 endleaf = leaf + loadmodel->brush.num_leafs;
3282 if (mod_recalculatenodeboxes.integer)
3284 for (;leaf < endleaf;leaf++)
3286 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3287 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3292 for (portalindex = 0;portalindex < portalrange;portalindex++)
3294 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3297 // note: this check must match the one below or it will usually corrupt memory
3298 // 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
3299 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3302 numpoints += p->numpoints * 2;
3305 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3306 loadmodel->brush.num_portals = numportals;
3307 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3308 loadmodel->brush.num_portalpoints = numpoints;
3309 // clear all leaf portal chains
3310 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3311 loadmodel->brush.data_leafs[i].portals = NULL;
3312 // process all portals in the global portal chain, while freeing them
3313 portal = loadmodel->brush.data_portals;
3314 point = loadmodel->brush.data_portalpoints;
3315 for (portalindex = 0;portalindex < portalrange;portalindex++)
3317 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3320 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3322 // note: this check must match the one above or it will usually corrupt memory
3323 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3324 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3326 // first make the back to front portal(forward portal)
3327 portal->points = point;
3328 portal->numpoints = p->numpoints;
3329 portal->plane.dist = p->plane.dist;
3330 VectorCopy(p->plane.normal, portal->plane.normal);
3331 portal->here = (mleaf_t *)p->nodes[1];
3332 portal->past = (mleaf_t *)p->nodes[0];
3334 for (j = 0;j < portal->numpoints;j++)
3336 VectorCopy(p->points + j*3, point->position);
3339 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3340 PlaneClassify(&portal->plane);
3342 // link into leaf's portal chain
3343 portal->next = portal->here->portals;
3344 portal->here->portals = portal;
3346 // advance to next portal
3349 // then make the front to back portal(backward portal)
3350 portal->points = point;
3351 portal->numpoints = p->numpoints;
3352 portal->plane.dist = -p->plane.dist;
3353 VectorNegate(p->plane.normal, portal->plane.normal);
3354 portal->here = (mleaf_t *)p->nodes[0];
3355 portal->past = (mleaf_t *)p->nodes[1];
3357 for (j = portal->numpoints - 1;j >= 0;j--)
3359 VectorCopy(p->points + j*3, point->position);
3362 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3363 PlaneClassify(&portal->plane);
3365 // link into leaf's portal chain
3366 portal->next = portal->here->portals;
3367 portal->here->portals = portal;
3369 // advance to next portal
3372 // add the portal's polygon points to the leaf bounding boxes
3373 if (mod_recalculatenodeboxes.integer)
3375 for (i = 0;i < 2;i++)
3377 leaf = (mleaf_t *)p->nodes[i];
3378 for (j = 0;j < p->numpoints;j++)
3380 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3381 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3382 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3383 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3384 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3385 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3391 // now recalculate the node bounding boxes from the leafs
3392 if (mod_recalculatenodeboxes.integer)
3393 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3401 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3404 Host_Error("AddPortalToNodes: NULL front node");
3406 Host_Error("AddPortalToNodes: NULL back node");
3407 if (p->nodes[0] || p->nodes[1])
3408 Host_Error("AddPortalToNodes: already included");
3409 // 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
3411 p->nodes[0] = front;
3412 p->next[0] = (portal_t *)front->portals;
3413 front->portals = (mportal_t *)p;
3416 p->next[1] = (portal_t *)back->portals;
3417 back->portals = (mportal_t *)p;
3422 RemovePortalFromNode
3425 static void RemovePortalFromNodes(portal_t *portal)
3429 void **portalpointer;
3431 for (i = 0;i < 2;i++)
3433 node = portal->nodes[i];
3435 portalpointer = (void **) &node->portals;
3438 t = (portal_t *)*portalpointer;
3440 Host_Error("RemovePortalFromNodes: portal not in leaf");
3444 if (portal->nodes[0] == node)
3446 *portalpointer = portal->next[0];
3447 portal->nodes[0] = NULL;
3449 else if (portal->nodes[1] == node)
3451 *portalpointer = portal->next[1];
3452 portal->nodes[1] = NULL;
3455 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3459 if (t->nodes[0] == node)
3460 portalpointer = (void **) &t->next[0];
3461 else if (t->nodes[1] == node)
3462 portalpointer = (void **) &t->next[1];
3464 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3469 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3470 static double *portalpointsbuffer;
3471 static int portalpointsbufferoffset;
3472 static int portalpointsbuffersize;
3473 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3476 mnode_t *front, *back, *other_node;
3477 mplane_t clipplane, *plane;
3478 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3479 int numfrontpoints, numbackpoints;
3480 double *frontpoints, *backpoints;
3482 // if a leaf, we're done
3486 // get some space for our clipping operations to use
3487 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3489 portalpointsbuffersize = portalpointsbufferoffset * 2;
3490 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3492 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3493 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3494 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3495 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3497 plane = node->plane;
3499 front = node->children[0];
3500 back = node->children[1];
3502 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3504 // create the new portal by generating a polygon for the node plane,
3505 // and clipping it by all of the other portals(which came from nodes above this one)
3506 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3507 nodeportal->plane = *plane;
3509 // 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)
3510 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);
3511 nodeportal->numpoints = 4;
3512 // side = 0; // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3513 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3515 clipplane = portal->plane;
3516 if (portal->nodes[0] == portal->nodes[1])
3517 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3518 if (portal->nodes[0] == node)
3520 else if (portal->nodes[1] == node)
3522 clipplane.dist = -clipplane.dist;
3523 VectorNegate(clipplane.normal, clipplane.normal);
3528 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3529 side = 0; // hush warning
3532 for (i = 0;i < nodeportal->numpoints*3;i++)
3533 frontpoints[i] = nodeportal->points[i];
3534 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);
3535 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3539 if (nodeportal->numpoints < 3)
3541 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3542 nodeportal->numpoints = 0;
3544 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3546 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3547 nodeportal->numpoints = 0;
3550 AddPortalToNodes(nodeportal, front, back);
3552 // split the portals of this node along this node's plane and assign them to the children of this node
3553 // (migrating the portals downward through the tree)
3554 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3556 if (portal->nodes[0] == portal->nodes[1])
3557 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3558 if (portal->nodes[0] == node)
3560 else if (portal->nodes[1] == node)
3564 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3565 side = 0; // hush warning
3567 nextportal = portal->next[side];
3568 if (!portal->numpoints)
3571 other_node = portal->nodes[!side];
3572 RemovePortalFromNodes(portal);
3574 // cut the portal into two portals, one on each side of the node plane
3575 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);
3577 if (!numfrontpoints)
3580 AddPortalToNodes(portal, back, other_node);
3582 AddPortalToNodes(portal, other_node, back);
3588 AddPortalToNodes(portal, front, other_node);
3590 AddPortalToNodes(portal, other_node, front);
3594 // the portal is split
3595 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3596 temp = splitportal->chain;
3597 *splitportal = *portal;
3598 splitportal->chain = temp;
3599 for (i = 0;i < numbackpoints*3;i++)
3600 splitportal->points[i] = backpoints[i];
3601 splitportal->numpoints = numbackpoints;
3602 for (i = 0;i < numfrontpoints*3;i++)
3603 portal->points[i] = frontpoints[i];
3604 portal->numpoints = numfrontpoints;
3608 AddPortalToNodes(portal, front, other_node);
3609 AddPortalToNodes(splitportal, back, other_node);
3613 AddPortalToNodes(portal, other_node, front);
3614 AddPortalToNodes(splitportal, other_node, back);
3618 Mod_Q1BSP_RecursiveNodePortals(front);
3619 Mod_Q1BSP_RecursiveNodePortals(back);
3621 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3624 static void Mod_Q1BSP_MakePortals(void)
3626 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3627 portalpointsbufferoffset = 0;
3628 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3629 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3630 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3631 Mem_Free(portalpointsbuffer);
3632 portalpointsbuffer = NULL;
3633 portalpointsbufferoffset = 0;
3634 portalpointsbuffersize = 0;
3635 Mod_Q1BSP_FinalizePortals();
3636 Mem_ExpandableArray_FreeArray(&portalarray);
3639 //Returns PVS data for a given point
3640 //(note: can return NULL)
3641 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3644 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3646 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3647 if (((mleaf_t *)node)->clusterindex >= 0)
3648 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3653 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)
3657 float d = PlaneDiff(org, node->plane);
3659 node = node->children[0];
3660 else if (d < -radius)
3661 node = node->children[1];
3664 // go down both sides
3665 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3666 node = node->children[1];
3669 // if this leaf is in a cluster, accumulate the pvs bits
3670 if (((mleaf_t *)node)->clusterindex >= 0)
3673 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3674 for (i = 0;i < pvsbytes;i++)
3675 pvsbuffer[i] |= pvs[i];
3679 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3680 //of the given point.
3681 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3683 int bytes = model->brush.num_pvsclusterbytes;
3684 bytes = min(bytes, pvsbufferlength);
3685 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3687 memset(pvsbuffer, 0xFF, bytes);
3691 memset(pvsbuffer, 0, bytes);
3692 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3696 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3701 VectorSubtract(inmaxs, inmins, size);
3702 if (cmodel->brush.ishlbsp)
3705 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3706 else if (size[0] <= 32)
3708 if (size[2] < 54) // pick the nearest of 36 or 72
3709 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3711 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3714 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3719 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3720 else if (size[0] <= 32)
3721 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3723 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3725 VectorCopy(inmins, outmins);
3726 VectorAdd(inmins, hull->clip_size, outmaxs);
3729 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3732 int numshadowmeshtriangles = 0;
3733 msurface_t *surface;
3734 if (cls.state == ca_dedicated)
3736 // make a single combined shadow mesh to allow optimized shadow volume creation
3738 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3740 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3741 numshadowmeshtriangles += surface->num_triangles;
3743 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3744 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3745 if (surface->num_triangles > 0)
3746 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));
3747 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3748 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3749 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3751 return numshadowmeshtriangles;
3754 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);
3756 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3759 sizebuf_t lumpsb[HEADER_LUMPS];
3761 float dist, modelyawradius, modelradius;
3762 msurface_t *surface;
3763 hullinfo_t hullinfo;
3764 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3765 model_brush_lightstyleinfo_t styleinfo[256];
3766 unsigned char *datapointer;
3769 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3771 mod->type = mod_brushq1;
3773 mod->brush.isbsp2 = false;
3774 mod->brush.ishlbsp = false;
3775 i = MSG_ReadLittleLong(&sb);
3779 mod->modeldatatypestring = "Q1BSP";
3782 mod->brush.ishlbsp = true;
3783 mod->modeldatatypestring = "HLBSP";
3785 case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3786 mod->brush.isbsp2 = true;
3787 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3788 mod->modeldatatypestring = "Q1BSP2rmqe";
3790 case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3791 mod->brush.isbsp2 = true;
3792 mod->modeldatatypestring = "Q1BSP2";
3795 mod->modeldatatypestring = "Unknown BSP";
3796 Host_Error("Mod_Q1BSP_Load: %s has wrong version number %i: supported versions are 29 (Quake), 30 (Half-Life), \"BSP2\" or \"2PSB\" (rmqe)", mod->name, i);
3800 // fill in hull info
3801 VectorClear (hullinfo.hullsizes[0][0]);
3802 VectorClear (hullinfo.hullsizes[0][1]);
3803 if (mod->brush.ishlbsp)
3805 hullinfo.filehulls = 4;
3806 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3807 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3808 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3809 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3810 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3811 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3815 hullinfo.filehulls = 4;
3816 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3817 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3818 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3819 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3823 for (i = 0; i < HEADER_LUMPS; i++)
3825 int offset = MSG_ReadLittleLong(&sb);
3826 int size = MSG_ReadLittleLong(&sb);
3827 if (offset < 0 || offset + size > sb.cursize)
3828 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);
3829 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3832 mod->soundfromcenter = true;
3833 mod->TraceBox = Mod_Q1BSP_TraceBox;
3834 mod->TraceLine = Mod_Q1BSP_TraceLine;
3835 mod->TracePoint = Mod_Q1BSP_TracePoint;
3836 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3837 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3838 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3839 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3840 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3841 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3842 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3843 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3844 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3845 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3846 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3847 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3848 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3849 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3850 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3851 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3852 mod->Draw = R_Q1BSP_Draw;
3853 mod->DrawDepth = R_Q1BSP_DrawDepth;
3854 mod->DrawDebug = R_Q1BSP_DrawDebug;
3855 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3856 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3857 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3858 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3859 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3860 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3861 mod->DrawLight = R_Q1BSP_DrawLight;
3865 mod->brush.qw_md4sum = 0;
3866 mod->brush.qw_md4sum2 = 0;
3867 for (i = 0;i < HEADER_LUMPS;i++)
3870 if (i == LUMP_ENTITIES)
3872 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3873 mod->brush.qw_md4sum ^= LittleLong(temp);
3874 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3876 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3879 Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3880 Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3881 Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3882 Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3883 Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3884 Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3885 Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3886 Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3887 Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3888 Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3889 Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3890 // load submodels before leafs because they contain the number of vis leafs
3891 Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3892 Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3893 Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3894 Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3896 for (i = 0; i < HEADER_LUMPS; i++)
3897 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3898 Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3900 // check if the map supports transparent water rendering
3901 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3903 if (mod->brushq1.data_compressedpvs)
3904 Mem_Free(mod->brushq1.data_compressedpvs);
3905 mod->brushq1.data_compressedpvs = NULL;
3906 mod->brushq1.num_compressedpvs = 0;
3908 Mod_Q1BSP_MakeHull0();
3909 if (mod_bsp_portalize.integer)
3910 Mod_Q1BSP_MakePortals();
3912 mod->numframes = 2; // regular and alternate animation
3915 // make a single combined shadow mesh to allow optimized shadow volume creation
3916 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3918 if (loadmodel->brush.numsubmodels)
3919 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3921 // LordHavoc: to clear the fog around the original quake submodel code, I
3923 // first of all, some background info on the submodels:
3924 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3925 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3926 // now the weird for loop itself:
3927 // the loop functions in an odd way, on each iteration it sets up the
3928 // current 'mod' model (which despite the confusing code IS the model of
3929 // the number i), at the end of the loop it duplicates the model to become
3930 // the next submodel, and loops back to set up the new submodel.
3932 // LordHavoc: now the explanation of my sane way (which works identically):
3933 // set up the world model, then on each submodel copy from the world model
3934 // and set up the submodel with the respective model info.
3935 totalstylesurfaces = 0;
3937 for (i = 0;i < mod->brush.numsubmodels;i++)
3939 memset(stylecounts, 0, sizeof(stylecounts));
3940 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3942 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3943 for (j = 0;j < MAXLIGHTMAPS;j++)
3944 stylecounts[surface->lightmapinfo->styles[j]]++;
3946 for (k = 0;k < 255;k++)
3950 totalstylesurfaces += stylecounts[k];
3953 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3954 for (i = 0;i < mod->brush.numsubmodels;i++)
3956 // LordHavoc: this code was originally at the end of this loop, but
3957 // has been transformed to something more readable at the start here.
3962 // duplicate the basic information
3963 dpsnprintf(name, sizeof(name), "*%i", i);
3964 mod = Mod_FindName(name, loadmodel->name);
3965 // copy the base model to this one
3967 // rename the clone back to its proper name
3968 strlcpy(mod->name, name, sizeof(mod->name));
3969 mod->brush.parentmodel = loadmodel;
3970 // textures and memory belong to the main model
3971 mod->texturepool = NULL;
3972 mod->mempool = NULL;
3973 mod->brush.GetPVS = NULL;
3974 mod->brush.FatPVS = NULL;
3975 mod->brush.BoxTouchingPVS = NULL;
3976 mod->brush.BoxTouchingLeafPVS = NULL;
3977 mod->brush.BoxTouchingVisibleLeafs = NULL;
3978 mod->brush.FindBoxClusters = NULL;
3979 mod->brush.LightPoint = NULL;
3980 mod->brush.AmbientSoundLevelsForPoint = NULL;
3983 mod->brush.submodel = i;
3985 if (loadmodel->brush.submodels)
3986 loadmodel->brush.submodels[i] = mod;
3988 bm = &mod->brushq1.submodels[i];
3990 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3991 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3993 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3994 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3997 mod->firstmodelsurface = bm->firstface;
3998 mod->nummodelsurfaces = bm->numfaces;
4000 // set node/leaf parents for this submodel
4001 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4003 // make the model surface list (used by shadowing/lighting)
4004 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4005 Mod_MakeSortedSurfaces(mod);
4007 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4008 // (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)
4009 VectorCopy(bm->mins, mod->normalmins);
4010 VectorCopy(bm->maxs, mod->normalmaxs);
4011 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4012 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4013 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4014 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4015 modelradius = modelyawradius + modelradius * modelradius;
4016 modelyawradius = sqrt(modelyawradius);
4017 modelradius = sqrt(modelradius);
4018 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4019 mod->yawmins[2] = mod->normalmins[2];
4020 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
4021 mod->yawmaxs[2] = mod->normalmaxs[2];
4022 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4023 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
4024 mod->radius = modelradius;
4025 mod->radius2 = modelradius * modelradius;
4027 // this gets altered below if sky or water is used
4028 mod->DrawSky = NULL;
4029 mod->DrawAddWaterPlanes = NULL;
4031 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4032 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4033 if (mod->nummodelsurfaces)
4035 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4036 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4038 if (j < mod->nummodelsurfaces)
4039 mod->DrawSky = R_Q1BSP_DrawSky;
4041 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4042 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4044 if (j < mod->nummodelsurfaces)
4045 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4047 // build lightstyle update chains
4048 // (used to rapidly mark lightmapupdateflags on many surfaces
4049 // when d_lightstylevalue changes)
4050 memset(stylecounts, 0, sizeof(stylecounts));
4051 for (k = 0;k < mod->nummodelsurfaces;k++)
4053 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4054 for (j = 0;j < MAXLIGHTMAPS;j++)
4055 stylecounts[surface->lightmapinfo->styles[j]]++;
4057 mod->brushq1.num_lightstyles = 0;
4058 for (k = 0;k < 255;k++)
4062 styleinfo[mod->brushq1.num_lightstyles].style = k;
4063 styleinfo[mod->brushq1.num_lightstyles].value = 0;
4064 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4065 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4066 remapstyles[k] = mod->brushq1.num_lightstyles;
4067 mod->brushq1.num_lightstyles++;
4070 for (k = 0;k < mod->nummodelsurfaces;k++)
4072 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4073 for (j = 0;j < MAXLIGHTMAPS;j++)
4075 if (surface->lightmapinfo->styles[j] != 255)
4077 int r = remapstyles[surface->lightmapinfo->styles[j]];
4078 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4082 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4083 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4087 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4088 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4090 //mod->brushq1.num_visleafs = bm->visleafs;
4092 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4093 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4095 if (mod_q1bsp_polygoncollisions.integer)
4097 mod->collision_bih = mod->render_bih;
4098 // point traces and contents checks still use the bsp tree
4099 mod->TraceLine = Mod_CollisionBIH_TraceLine;
4100 mod->TraceBox = Mod_CollisionBIH_TraceBox;
4101 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4102 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4105 // generate VBOs and other shared data before cloning submodels
4109 Mod_Q1BSP_LoadMapBrushes();
4110 //Mod_Q1BSP_ProcessLightList();
4114 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);
4117 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4121 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4128 in = (void *)(mod_base + l->fileofs);
4129 if (l->filelen % sizeof(*in))
4130 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4131 count = l->filelen / sizeof(*in);
4132 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4135 loadmodel->num = count;
4137 for (i = 0;i < count;i++, in++, out++)
4143 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4150 in = (void *)(mod_base + l->fileofs);
4151 if (l->filelen % sizeof(*in))
4152 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4153 count = l->filelen / sizeof(*in);
4154 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4157 loadmodel->num = count;
4159 for (i = 0;i < count;i++, in++, out++)
4165 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4172 in = (void *)(mod_base + l->fileofs);
4173 if (l->filelen % sizeof(*in))
4174 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4175 count = l->filelen / sizeof(*in);
4176 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4179 loadmodel->num = count;
4181 for (i = 0;i < count;i++, in++, out++)
4187 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4194 in = (void *)(mod_base + l->fileofs);
4195 if (l->filelen % sizeof(*in))
4196 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4197 count = l->filelen / sizeof(*in);
4198 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4201 loadmodel->num = count;
4203 for (i = 0;i < count;i++, in++, out++)
4209 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4216 in = (void *)(mod_base + l->fileofs);
4217 if (l->filelen % sizeof(*in))
4218 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4219 count = l->filelen / sizeof(*in);
4220 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4223 loadmodel->num = count;
4225 for (i = 0;i < count;i++, in++, out++)
4231 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4238 in = (void *)(mod_base + l->fileofs);
4239 if (l->filelen % sizeof(*in))
4240 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4241 count = l->filelen / sizeof(*in);
4242 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4245 loadmodel->num = count;
4247 for (i = 0;i < count;i++, in++, out++)
4253 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4260 in = (void *)(mod_base + l->fileofs);
4261 if (l->filelen % sizeof(*in))
4262 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4263 count = l->filelen / sizeof(*in);
4264 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4267 loadmodel->num = count;
4269 for (i = 0;i < count;i++, in++, out++)
4275 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4282 in = (void *)(mod_base + l->fileofs);
4283 if (l->filelen % sizeof(*in))
4284 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4285 count = l->filelen / sizeof(*in);
4286 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4289 loadmodel->num = count;
4291 for (i = 0;i < count;i++, in++, out++)
4297 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4304 in = (void *)(mod_base + l->fileofs);
4305 if (l->filelen % sizeof(*in))
4306 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4307 count = l->filelen / sizeof(*in);
4308 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4311 loadmodel->num = count;
4313 for (i = 0;i < count;i++, in++, out++)
4319 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4326 in = (void *)(mod_base + l->fileofs);
4327 if (l->filelen % sizeof(*in))
4328 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4329 count = l->filelen / sizeof(*in);
4330 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4333 loadmodel->num = count;
4335 for (i = 0;i < count;i++, in++, out++)
4341 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4348 in = (void *)(mod_base + l->fileofs);
4349 if (l->filelen % sizeof(*in))
4350 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4351 count = l->filelen / sizeof(*in);
4352 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4355 loadmodel->num = count;
4357 for (i = 0;i < count;i++, in++, out++)
4363 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4370 in = (void *)(mod_base + l->fileofs);
4371 if (l->filelen % sizeof(*in))
4372 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4373 count = l->filelen / sizeof(*in);
4374 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4377 loadmodel->num = count;
4379 for (i = 0;i < count;i++, in++, out++)
4385 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4392 in = (void *)(mod_base + l->fileofs);
4393 if (l->filelen % sizeof(*in))
4394 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4395 count = l->filelen / sizeof(*in);
4396 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4399 loadmodel->num = count;
4401 for (i = 0;i < count;i++, in++, out++)
4407 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4414 in = (void *)(mod_base + l->fileofs);
4415 if (l->filelen % sizeof(*in))
4416 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4417 count = l->filelen / sizeof(*in);
4418 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4421 loadmodel->num = count;
4423 for (i = 0;i < count;i++, in++, out++)
4429 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4436 in = (void *)(mod_base + l->fileofs);
4437 if (l->filelen % sizeof(*in))
4438 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4439 count = l->filelen / sizeof(*in);
4440 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4443 loadmodel->num = count;
4445 for (i = 0;i < count;i++, in++, out++)
4451 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4458 in = (void *)(mod_base + l->fileofs);
4459 if (l->filelen % sizeof(*in))
4460 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4461 count = l->filelen / sizeof(*in);
4462 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4465 loadmodel->num = count;
4467 for (i = 0;i < count;i++, in++, out++)
4473 static void Mod_Q2BSP_LoadModels(lump_t *l)
4480 in = (void *)(mod_base + l->fileofs);
4481 if (l->filelen % sizeof(*in))
4482 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4483 count = l->filelen / sizeof(*in);
4484 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4487 loadmodel->num = count;
4489 for (i = 0;i < count;i++, in++, out++)
4495 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4498 q2dheader_t *header;
4500 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4502 mod->modeldatatypestring = "Q2BSP";
4504 mod->type = mod_brushq2;
4506 header = (q2dheader_t *)buffer;
4508 i = LittleLong(header->version);
4509 if (i != Q2BSPVERSION)
4510 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4512 mod_base = (unsigned char *)header;
4514 // swap all the lumps
4515 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4516 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4518 mod->brush.qw_md4sum = 0;
4519 mod->brush.qw_md4sum2 = 0;
4520 for (i = 0;i < Q2HEADER_LUMPS;i++)
4522 if (i == Q2LUMP_ENTITIES)
4524 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4525 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4527 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4530 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4531 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4532 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4533 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4534 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4535 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4536 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4537 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4538 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4539 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4540 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4541 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4542 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4543 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4544 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4545 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4546 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4547 // LordHavoc: must go last because this makes the submodels
4548 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4551 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4552 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4554 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4557 char key[128], value[MAX_INPUTLINE];
4559 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4560 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4561 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4564 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4565 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4566 loadmodel->brush.entities[l->filelen] = 0;
4567 data = loadmodel->brush.entities;
4568 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4569 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4570 loadmodel->brushq3.deluxemapping = false;
4571 if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4575 if (!COM_ParseToken_Simple(&data, false, false, true))
4577 if (com_token[0] == '}')
4578 break; // end of worldspawn
4579 if (com_token[0] == '_')
4580 strlcpy(key, com_token + 1, sizeof(key));
4582 strlcpy(key, com_token, sizeof(key));
4583 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4584 key[strlen(key)-1] = 0;
4585 if (!COM_ParseToken_Simple(&data, false, false, true))
4587 strlcpy(value, com_token, sizeof(value));
4588 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4590 #if _MSC_VER >= 1400
4591 #define sscanf sscanf_s
4594 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4595 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4597 VectorSet(v, 64, 64, 128);
4598 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4599 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]);
4600 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4601 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4604 else if (!strcmp("deluxeMaps", key))
4606 if (!strcmp(com_token, "1"))
4608 loadmodel->brushq3.deluxemapping = true;
4609 loadmodel->brushq3.deluxemapping_modelspace = true;
4611 else if (!strcmp(com_token, "2"))
4613 loadmodel->brushq3.deluxemapping = true;
4614 loadmodel->brushq3.deluxemapping_modelspace = false;
4621 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4627 in = (q3dtexture_t *)(mod_base + l->fileofs);
4628 if (l->filelen % sizeof(*in))
4629 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4630 count = l->filelen / sizeof(*in);
4631 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4633 loadmodel->data_textures = out;
4634 loadmodel->num_textures = count;
4635 loadmodel->num_texturesperskin = loadmodel->num_textures;
4637 for (i = 0;i < count;i++)
4639 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4640 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4641 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4642 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4643 // restore the surfaceflags and supercontents
4644 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4645 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4649 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4655 in = (q3dplane_t *)(mod_base + l->fileofs);
4656 if (l->filelen % sizeof(*in))
4657 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4658 count = l->filelen / sizeof(*in);
4659 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4661 loadmodel->brush.data_planes = out;
4662 loadmodel->brush.num_planes = count;
4664 for (i = 0;i < count;i++, in++, out++)
4666 out->normal[0] = LittleFloat(in->normal[0]);
4667 out->normal[1] = LittleFloat(in->normal[1]);
4668 out->normal[2] = LittleFloat(in->normal[2]);
4669 out->dist = LittleFloat(in->dist);
4674 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4677 q3mbrushside_t *out;
4680 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4681 if (l->filelen % sizeof(*in))
4682 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4683 count = l->filelen / sizeof(*in);
4684 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4686 loadmodel->brush.data_brushsides = out;
4687 loadmodel->brush.num_brushsides = count;
4689 for (i = 0;i < count;i++, in++, out++)
4691 n = LittleLong(in->planeindex);
4692 if (n < 0 || n >= loadmodel->brush.num_planes)
4693 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4694 out->plane = loadmodel->brush.data_planes + n;
4695 n = LittleLong(in->textureindex);
4696 if (n < 0 || n >= loadmodel->num_textures)
4697 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4698 out->texture = loadmodel->data_textures + n;
4702 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4704 q3dbrushside_ig_t *in;
4705 q3mbrushside_t *out;
4708 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4709 if (l->filelen % sizeof(*in))
4710 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4711 count = l->filelen / sizeof(*in);
4712 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4714 loadmodel->brush.data_brushsides = out;
4715 loadmodel->brush.num_brushsides = count;
4717 for (i = 0;i < count;i++, in++, out++)
4719 n = LittleLong(in->planeindex);
4720 if (n < 0 || n >= loadmodel->brush.num_planes)
4721 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4722 out->plane = loadmodel->brush.data_planes + n;
4723 n = LittleLong(in->textureindex);
4724 if (n < 0 || n >= loadmodel->num_textures)
4725 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4726 out->texture = loadmodel->data_textures + n;
4730 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4734 int i, j, n, c, count, maxplanes, q3surfaceflags;
4735 colplanef_t *planes;
4737 in = (q3dbrush_t *)(mod_base + l->fileofs);
4738 if (l->filelen % sizeof(*in))
4739 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4740 count = l->filelen / sizeof(*in);
4741 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4743 loadmodel->brush.data_brushes = out;
4744 loadmodel->brush.num_brushes = count;
4749 for (i = 0;i < count;i++, in++, out++)
4751 n = LittleLong(in->firstbrushside);
4752 c = LittleLong(in->numbrushsides);
4753 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4754 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4755 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4756 out->numbrushsides = c;
4757 n = LittleLong(in->textureindex);
4758 if (n < 0 || n >= loadmodel->num_textures)
4759 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4760 out->texture = loadmodel->data_textures + n;
4762 // make a list of mplane_t structs to construct a colbrush from
4763 if (maxplanes < out->numbrushsides)
4765 maxplanes = out->numbrushsides;
4768 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4771 for (j = 0;j < out->numbrushsides;j++)
4773 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4774 planes[j].dist = out->firstbrushside[j].plane->dist;
4775 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4776 planes[j].texture = out->firstbrushside[j].texture;
4777 q3surfaceflags |= planes[j].q3surfaceflags;
4779 // make the colbrush from the planes
4780 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4782 // this whole loop can take a while (e.g. on redstarrepublic4)
4783 CL_KeepaliveMessage(false);
4789 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4795 in = (q3deffect_t *)(mod_base + l->fileofs);
4796 if (l->filelen % sizeof(*in))
4797 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4798 count = l->filelen / sizeof(*in);
4799 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4801 loadmodel->brushq3.data_effects = out;
4802 loadmodel->brushq3.num_effects = count;
4804 for (i = 0;i < count;i++, in++, out++)
4806 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4807 n = LittleLong(in->brushindex);
4808 if (n >= loadmodel->brush.num_brushes)
4810 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4813 out->brushindex = n;
4814 out->unknown = LittleLong(in->unknown);
4818 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4823 in = (q3dvertex_t *)(mod_base + l->fileofs);
4824 if (l->filelen % sizeof(*in))
4825 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4826 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4827 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4828 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4829 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4830 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4831 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4833 for (i = 0;i < count;i++, in++)
4835 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4836 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4837 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4838 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4839 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4840 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4841 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4842 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4843 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4844 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4845 // svector/tvector are calculated later in face loading
4846 if(mod_q3bsp_sRGBlightmaps.integer)
4848 // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
4849 // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
4850 // working like this may be odd, but matches q3map2 -gamma 2.2
4851 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4853 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4854 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4855 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4856 // we fix the brightness consistently via lightmapscale
4860 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
4861 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
4862 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
4867 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4869 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4870 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4871 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4875 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4876 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4877 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4880 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4881 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4882 loadmodel->lit = true;
4886 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4892 in = (int *)(mod_base + l->fileofs);
4893 if (l->filelen % sizeof(int[3]))
4894 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4895 count = l->filelen / sizeof(*in);
4897 if(!loadmodel->brushq3.num_vertices)
4900 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4901 loadmodel->brushq3.num_triangles = 0;
4905 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4906 loadmodel->brushq3.num_triangles = count / 3;
4907 loadmodel->brushq3.data_element3i = out;
4909 for (i = 0;i < count;i++, in++, out++)
4911 *out = LittleLong(*in);
4912 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4914 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4920 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4922 q3dlightmap_t *input_pointer;
4940 int mergedrowsxcolumns;
4945 unsigned char *mergedpixels;
4946 unsigned char *mergeddeluxepixels;
4947 unsigned char *mergebuf;
4948 char mapname[MAX_QPATH];
4950 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4953 // defaults for q3bsp
4960 loadmodel->brushq3.lightmapsize = 128;
4962 if (cls.state == ca_dedicated)
4965 if(mod_q3bsp_nolightmaps.integer)
4971 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4972 if (developer_loading.integer)
4973 Con_Printf("Using internal lightmaps\n");
4974 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4975 if (l->filelen % sizeof(*input_pointer))
4976 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4977 count = l->filelen / sizeof(*input_pointer);
4978 for(i = 0; i < count; ++i)
4979 inpixels[i] = input_pointer[i].rgb;
4983 // no internal lightmaps
4984 // try external lightmaps
4985 if (developer_loading.integer)
4986 Con_Printf("Using external lightmaps\n");
4987 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4988 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
4992 // using EXTERNAL lightmaps instead
4993 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4995 Mem_Free(inpixels[0]);
4996 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
5006 for(count = 1; ; ++count)
5008 inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5009 if(!inpixels[count])
5010 break; // we got all of them
5011 if(image_width != size || image_height != size)
5013 Mem_Free(inpixels[count]);
5014 inpixels[count] = NULL;
5015 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);
5021 loadmodel->brushq3.lightmapsize = size;
5022 loadmodel->brushq3.num_originallightmaps = count;
5024 // now check the surfaces to see if any of them index an odd numbered
5025 // lightmap, if so this is not a deluxemapped bsp file
5027 // also check what lightmaps are actually used, because q3map2 sometimes
5028 // (always?) makes an unused one at the end, which
5029 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5030 // reason when only one lightmap is used, which can throw off the
5031 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5032 // to see if the second lightmap is blank, if so it is not deluxemapped.
5033 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5034 // in Mod_Q3BSP_LoadEntities was failed
5035 if (!loadmodel->brushq3.deluxemapping)
5037 loadmodel->brushq3.deluxemapping = !(count & 1);
5038 loadmodel->brushq3.deluxemapping_modelspace = true;
5040 if (loadmodel->brushq3.deluxemapping)
5042 int facecount = faceslump->filelen / sizeof(q3dface_t);
5043 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5044 for (i = 0;i < facecount;i++)
5046 j = LittleLong(faces[i].lightmapindex);
5049 endlightmap = max(endlightmap, j + 1);
5050 if ((j & 1) || j + 1 >= count)
5052 loadmodel->brushq3.deluxemapping = false;
5059 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5060 // reason when only one lightmap is used, which can throw off the
5061 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5062 // to see if the second lightmap is blank, if so it is not deluxemapped.
5064 // further research has shown q3map2 sometimes creates a deluxemap and two
5065 // blank lightmaps, which must be handled properly as well
5066 if (endlightmap == 1 && count > 1)
5069 for (i = 0;i < size*size;i++)
5071 if (c[bytesperpixel*i + rgbmap[0]])
5073 if (c[bytesperpixel*i + rgbmap[1]])
5075 if (c[bytesperpixel*i + rgbmap[2]])
5080 // all pixels in the unused lightmap were black...
5081 loadmodel->brushq3.deluxemapping = false;
5086 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5088 // figure out what the most reasonable merge power is within limits
5090 // find the appropriate NxN dimensions to merge to, to avoid wasted space
5091 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5093 // figure out how big the merged texture has to be
5094 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5095 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5096 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5098 mergedwidth = mergegoal;
5099 mergedheight = mergegoal;
5100 // choose non-square size (2x1 aspect) if only half the space is used;
5101 // this really only happens when the entire set fits in one texture, if
5102 // there are multiple textures, we don't worry about shrinking the last
5103 // one to fit, because the driver prefers the same texture size on
5104 // consecutive draw calls...
5105 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5108 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5109 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5110 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5111 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5112 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5113 loadmodel->brushq3.num_lightmapmergedheightpower++;
5114 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5116 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5117 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5118 powerxy = powerx+powery;
5119 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5121 mergedcolumns = 1 << powerx;
5122 mergedrows = 1 << powery;
5123 mergedrowsxcolumns = 1 << powerxy;
5125 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5126 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5127 if (loadmodel->brushq3.deluxemapping)
5128 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5130 // allocate a texture pool if we need it
5131 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5132 loadmodel->texturepool = R_AllocTexturePool();
5134 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5135 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5136 for (i = 0;i < count;i++)
5138 // figure out which merged lightmap texture this fits into
5139 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5140 lightmapindex = i >> powerdxy;
5142 // choose the destination address
5143 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5144 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5145 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5146 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);
5148 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5149 for (j = 0;j < size;j++)
5150 for (k = 0;k < size;k++)
5152 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5153 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5154 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5155 mergebuf[(j*mergedwidth+k)*4+3] = 255;
5158 // upload texture if this was the last tile being written to the texture
5159 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5161 if (loadmodel->brushq3.deluxemapping && (i & 1))
5162 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);
5165 if(mod_q3bsp_sRGBlightmaps.integer)
5168 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5170 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5171 // we fix the brightness consistently via lightmapscale
5174 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5175 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);
5179 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5180 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5181 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);
5187 if (mergeddeluxepixels)
5188 Mem_Free(mergeddeluxepixels);
5189 Mem_Free(mergedpixels);
5192 for(i = 0; i < count; ++i)
5193 Mem_Free(inpixels[i]);
5197 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5202 *collisionstride = stride;
5205 cnt = (num_triangles + stride - 1) / stride;
5206 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5207 for(j = 0; j < cnt; ++j)
5209 mins = &((*collisionbbox6f)[6 * j + 0]);
5210 maxs = &((*collisionbbox6f)[6 * j + 3]);
5211 for(k = 0; k < stride; ++k)
5213 tri = j * stride + k;
5214 if(tri >= num_triangles)
5216 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5217 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5218 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5219 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5220 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5221 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5222 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5223 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5224 if(vert[0] < mins[0]) mins[0] = vert[0];
5225 if(vert[1] < mins[1]) mins[1] = vert[1];
5226 if(vert[2] < mins[2]) mins[2] = vert[2];
5227 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5228 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5229 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5230 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5231 if(vert[0] < mins[0]) mins[0] = vert[0];
5232 if(vert[1] < mins[1]) mins[1] = vert[1];
5233 if(vert[2] < mins[2]) mins[2] = vert[2];
5234 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5235 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5236 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5241 *collisionbbox6f = NULL;
5244 typedef struct patchtess_s
5248 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5251 float *originalvertex3f;
5254 #define PATCHTESS_SAME_LODGROUP(a,b) \
5256 (a).lodgroup[0] == (b).lodgroup[0] && \
5257 (a).lodgroup[1] == (b).lodgroup[1] && \
5258 (a).lodgroup[2] == (b).lodgroup[2] && \
5259 (a).lodgroup[3] == (b).lodgroup[3] && \
5260 (a).lodgroup[4] == (b).lodgroup[4] && \
5261 (a).lodgroup[5] == (b).lodgroup[5] \
5264 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5266 q3dface_t *in, *oldin;
5267 msurface_t *out, *oldout;
5268 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;
5269 float lightmaptcbase[2], lightmaptcscale[2];
5270 //int *originalelement3i;
5271 //int *originalneighbor3i;
5272 float *originalvertex3f;
5273 //float *originalsvector3f;
5274 //float *originaltvector3f;
5275 float *originalnormal3f;
5276 float *originalcolor4f;
5277 float *originaltexcoordtexture2f;
5278 float *originaltexcoordlightmap2f;
5279 float *surfacecollisionvertex3f;
5280 int *surfacecollisionelement3i;
5282 patchtess_t *patchtess = NULL;
5283 int patchtesscount = 0;
5286 in = (q3dface_t *)(mod_base + l->fileofs);
5287 if (l->filelen % sizeof(*in))
5288 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5289 count = l->filelen / sizeof(*in);
5290 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5292 loadmodel->data_surfaces = out;
5293 loadmodel->num_surfaces = count;
5296 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5304 for (;i < count;i++, in++, out++)
5306 // check face type first
5307 type = LittleLong(in->type);
5308 if (type != Q3FACETYPE_FLAT
5309 && type != Q3FACETYPE_PATCH
5310 && type != Q3FACETYPE_MESH
5311 && type != Q3FACETYPE_FLARE)
5313 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5317 n = LittleLong(in->textureindex);
5318 if (n < 0 || n >= loadmodel->num_textures)
5320 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5323 out->texture = loadmodel->data_textures + n;
5324 n = LittleLong(in->effectindex);
5325 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5327 if (developer_extra.integer)
5328 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5334 out->effect = loadmodel->brushq3.data_effects + n;
5336 if (cls.state != ca_dedicated)
5338 out->lightmaptexture = NULL;
5339 out->deluxemaptexture = r_texture_blanknormalmap;
5340 n = LittleLong(in->lightmapindex);
5343 else if (n >= loadmodel->brushq3.num_originallightmaps)
5345 if(loadmodel->brushq3.num_originallightmaps != 0)
5346 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5351 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5352 if (loadmodel->brushq3.deluxemapping)
5353 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5354 loadmodel->lit = true;
5358 firstvertex = LittleLong(in->firstvertex);
5359 numvertices = LittleLong(in->numvertices);
5360 firstelement = LittleLong(in->firstelement);
5361 numtriangles = LittleLong(in->numelements) / 3;
5362 if (numtriangles * 3 != LittleLong(in->numelements))
5364 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));
5367 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5369 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);
5372 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5374 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);
5379 case Q3FACETYPE_FLAT:
5380 case Q3FACETYPE_MESH:
5381 // no processing necessary
5383 case Q3FACETYPE_PATCH:
5384 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5385 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5386 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))
5388 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5391 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5393 // convert patch to Q3FACETYPE_MESH
5394 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5395 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5396 // bound to user settings
5397 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5398 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5399 // bound to sanity settings
5400 xtess = bound(0, xtess, 1024);
5401 ytess = bound(0, ytess, 1024);
5403 // lower quality collision patches! Same procedure as before, but different cvars
5404 // convert patch to Q3FACETYPE_MESH
5405 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5406 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5407 // bound to user settings
5408 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5409 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5410 // bound to sanity settings
5411 cxtess = bound(0, cxtess, 1024);
5412 cytess = bound(0, cytess, 1024);
5414 // store it for the LOD grouping step
5415 patchtess[patchtesscount].info.xsize = patchsize[0];
5416 patchtess[patchtesscount].info.ysize = patchsize[1];
5417 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5418 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5419 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5420 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5422 patchtess[patchtesscount].surface_id = i;
5423 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5424 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5425 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5426 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5427 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5428 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5429 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5432 case Q3FACETYPE_FLARE:
5433 if (developer_extra.integer)
5434 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5438 out->num_vertices = numvertices;
5439 out->num_triangles = numtriangles;
5440 meshvertices += out->num_vertices;
5441 meshtriangles += out->num_triangles;
5444 // Fix patches tesselations so that they make no seams
5448 for(i = 0; i < patchtesscount; ++i)
5450 for(j = i+1; j < patchtesscount; ++j)
5452 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5455 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5462 // Calculate resulting number of triangles
5463 collisionvertices = 0;
5464 collisiontriangles = 0;
5465 for(i = 0; i < patchtesscount; ++i)
5467 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5468 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5469 numvertices = finalwidth * finalheight;
5470 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5472 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5473 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5474 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5475 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5477 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5478 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5479 numvertices = finalwidth * finalheight;
5480 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5482 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5483 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5484 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5485 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5491 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5492 if (collisiontriangles)
5494 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5495 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5499 collisionvertices = 0;
5500 collisiontriangles = 0;
5501 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5503 if (out->num_vertices < 3 || out->num_triangles < 1)
5506 type = LittleLong(in->type);
5507 firstvertex = LittleLong(in->firstvertex);
5508 firstelement = LittleLong(in->firstelement);
5509 out->num_firstvertex = meshvertices;
5510 out->num_firsttriangle = meshtriangles;
5511 out->num_firstcollisiontriangle = collisiontriangles;
5514 case Q3FACETYPE_FLAT:
5515 case Q3FACETYPE_MESH:
5516 // no processing necessary, except for lightmap merging
5517 for (j = 0;j < out->num_vertices;j++)
5519 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5520 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5521 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5522 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5523 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5524 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5525 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5526 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5527 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5528 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5529 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5530 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5531 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5532 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5534 for (j = 0;j < out->num_triangles*3;j++)
5535 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5537 case Q3FACETYPE_PATCH:
5538 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5539 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5540 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5541 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5542 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5543 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5544 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5546 xtess = ytess = cxtess = cytess = -1;
5547 for(j = 0; j < patchtesscount; ++j)
5548 if(patchtess[j].surface_id == i)
5550 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5551 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5552 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5553 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5558 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5559 xtess = ytess = cxtess = cytess = 0;
5562 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5563 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5564 finalvertices = finalwidth * finalheight;
5565 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5566 type = Q3FACETYPE_MESH;
5567 // generate geometry
5568 // (note: normals are skipped because they get recalculated)
5569 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5570 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5571 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5572 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5573 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5574 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5576 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);
5578 if (developer_extra.integer)
5580 if (out->num_triangles < finaltriangles)
5581 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);
5583 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);
5585 // q3map does not put in collision brushes for curves... ugh
5586 // build the lower quality collision geometry
5587 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5588 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5589 finalvertices = finalwidth * finalheight;
5590 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5592 // legacy collision geometry implementation
5593 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5594 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5595 out->num_collisionvertices = finalvertices;
5596 out->num_collisiontriangles = finaltriangles;
5597 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5598 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5600 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5601 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5603 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5605 // now optimize the collision mesh by finding triangle bboxes...
5606 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5607 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);
5609 // store collision geometry for BIH collision tree
5610 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5611 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5612 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5613 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5614 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5616 // remove this once the legacy code is removed
5618 int nc = out->num_collisiontriangles;
5620 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5622 if(nc != out->num_collisiontriangles)
5624 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5629 if (developer_extra.integer)
5630 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);
5632 collisionvertices += finalvertices;
5633 collisiontriangles += out->num_collisiontriangles;
5638 meshvertices += out->num_vertices;
5639 meshtriangles += out->num_triangles;
5640 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5641 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)
5643 if (invalidelements)
5645 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);
5646 for (j = 0;j < out->num_triangles * 3;j++)
5648 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5649 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)
5650 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5654 // calculate a bounding box
5655 VectorClear(out->mins);
5656 VectorClear(out->maxs);
5657 if (out->num_vertices)
5659 if (cls.state != ca_dedicated && out->lightmaptexture)
5661 // figure out which part of the merged lightmap this fits into
5662 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5663 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5664 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5665 lightmapindex &= mergewidth * mergeheight - 1;
5666 lightmaptcscale[0] = 1.0f / mergewidth;
5667 lightmaptcscale[1] = 1.0f / mergeheight;
5668 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5669 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5670 // modify the lightmap texcoords to match this region of the merged lightmap
5671 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5673 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5674 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5677 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5678 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5679 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5681 out->mins[0] = min(out->mins[0], v[0]);
5682 out->maxs[0] = max(out->maxs[0], v[0]);
5683 out->mins[1] = min(out->mins[1], v[1]);
5684 out->maxs[1] = max(out->maxs[1], v[1]);
5685 out->mins[2] = min(out->mins[2], v[2]);
5686 out->maxs[2] = max(out->maxs[2], v[2]);
5688 out->mins[0] -= 1.0f;
5689 out->mins[1] -= 1.0f;
5690 out->mins[2] -= 1.0f;
5691 out->maxs[0] += 1.0f;
5692 out->maxs[1] += 1.0f;
5693 out->maxs[2] += 1.0f;
5695 // set lightmap styles for consistency with q1bsp
5696 //out->lightmapinfo->styles[0] = 0;
5697 //out->lightmapinfo->styles[1] = 255;
5698 //out->lightmapinfo->styles[2] = 255;
5699 //out->lightmapinfo->styles[3] = 255;
5704 for (;i < count;i++, out++)
5706 if(out->num_vertices && out->num_triangles)
5708 if(out->num_vertices == 0)
5710 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5711 if(out->num_triangles == 0)
5712 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5714 else if(out->num_triangles == 0)
5715 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)",
5716 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5717 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5718 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5721 // for per pixel lighting
5722 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);
5724 // generate ushort elements array if possible
5725 if (loadmodel->surfmesh.data_element3s)
5726 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5727 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5729 // free the no longer needed vertex data
5730 loadmodel->brushq3.num_vertices = 0;
5731 if (loadmodel->brushq3.data_vertex3f)
5732 Mem_Free(loadmodel->brushq3.data_vertex3f);
5733 loadmodel->brushq3.data_vertex3f = NULL;
5734 loadmodel->brushq3.data_normal3f = NULL;
5735 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5736 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5737 loadmodel->brushq3.data_color4f = NULL;
5738 // free the no longer needed triangle data
5739 loadmodel->brushq3.num_triangles = 0;
5740 if (loadmodel->brushq3.data_element3i)
5741 Mem_Free(loadmodel->brushq3.data_element3i);
5742 loadmodel->brushq3.data_element3i = NULL;
5745 Mem_Free(patchtess);
5748 static void Mod_Q3BSP_LoadModels(lump_t *l)
5752 int i, j, n, c, count;
5754 in = (q3dmodel_t *)(mod_base + l->fileofs);
5755 if (l->filelen % sizeof(*in))
5756 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5757 count = l->filelen / sizeof(*in);
5758 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5760 loadmodel->brushq3.data_models = out;
5761 loadmodel->brushq3.num_models = count;
5763 for (i = 0;i < count;i++, in++, out++)
5765 for (j = 0;j < 3;j++)
5767 out->mins[j] = LittleFloat(in->mins[j]);
5768 out->maxs[j] = LittleFloat(in->maxs[j]);
5770 n = LittleLong(in->firstface);
5771 c = LittleLong(in->numfaces);
5772 if (n < 0 || n + c > loadmodel->num_surfaces)
5773 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5776 n = LittleLong(in->firstbrush);
5777 c = LittleLong(in->numbrushes);
5778 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5779 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5780 out->firstbrush = n;
5781 out->numbrushes = c;
5785 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5791 in = (int *)(mod_base + l->fileofs);
5792 if (l->filelen % sizeof(*in))
5793 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5794 count = l->filelen / sizeof(*in);
5795 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5797 loadmodel->brush.data_leafbrushes = out;
5798 loadmodel->brush.num_leafbrushes = count;
5800 for (i = 0;i < count;i++, in++, out++)
5802 n = LittleLong(*in);
5803 if (n < 0 || n >= loadmodel->brush.num_brushes)
5804 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5809 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5815 in = (int *)(mod_base + l->fileofs);
5816 if (l->filelen % sizeof(*in))
5817 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5818 count = l->filelen / sizeof(*in);
5819 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5821 loadmodel->brush.data_leafsurfaces = out;
5822 loadmodel->brush.num_leafsurfaces = count;
5824 for (i = 0;i < count;i++, in++, out++)
5826 n = LittleLong(*in);
5827 if (n < 0 || n >= loadmodel->num_surfaces)
5828 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5833 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5837 int i, j, n, c, count;
5839 in = (q3dleaf_t *)(mod_base + l->fileofs);
5840 if (l->filelen % sizeof(*in))
5841 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5842 count = l->filelen / sizeof(*in);
5843 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5845 loadmodel->brush.data_leafs = out;
5846 loadmodel->brush.num_leafs = count;
5848 for (i = 0;i < count;i++, in++, out++)
5852 out->clusterindex = LittleLong(in->clusterindex);
5853 out->areaindex = LittleLong(in->areaindex);
5854 for (j = 0;j < 3;j++)
5856 // yes the mins/maxs are ints
5857 out->mins[j] = LittleLong(in->mins[j]) - 1;
5858 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5860 n = LittleLong(in->firstleafface);
5861 c = LittleLong(in->numleaffaces);
5862 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5863 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5864 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5865 out->numleafsurfaces = c;
5866 n = LittleLong(in->firstleafbrush);
5867 c = LittleLong(in->numleafbrushes);
5868 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5869 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5870 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5871 out->numleafbrushes = c;
5875 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5881 in = (q3dnode_t *)(mod_base + l->fileofs);
5882 if (l->filelen % sizeof(*in))
5883 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5884 count = l->filelen / sizeof(*in);
5886 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5887 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5889 loadmodel->brush.data_nodes = out;
5890 loadmodel->brush.num_nodes = count;
5892 for (i = 0;i < count;i++, in++, out++)
5895 n = LittleLong(in->planeindex);
5896 if (n < 0 || n >= loadmodel->brush.num_planes)
5897 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5898 out->plane = loadmodel->brush.data_planes + n;
5899 for (j = 0;j < 2;j++)
5901 n = LittleLong(in->childrenindex[j]);
5904 if (n >= loadmodel->brush.num_nodes)
5905 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5906 out->children[j] = loadmodel->brush.data_nodes + n;
5911 if (n >= loadmodel->brush.num_leafs)
5912 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5913 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5916 for (j = 0;j < 3;j++)
5918 // yes the mins/maxs are ints
5919 out->mins[j] = LittleLong(in->mins[j]) - 1;
5920 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5924 // set the parent pointers
5925 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5928 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5931 q3dlightgrid_t *out;
5935 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5936 if (l->filelen % sizeof(*in))
5937 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5938 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5939 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5940 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5941 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5942 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5943 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5944 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5945 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5946 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5947 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5948 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5949 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5950 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5951 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]);
5952 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]);
5954 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5957 if (l->filelen < count * (int)sizeof(*in))
5959 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]);
5960 return; // ignore the grid if we cannot understand it
5962 if (l->filelen != count * (int)sizeof(*in))
5963 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5964 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5965 loadmodel->brushq3.data_lightgrid = out;
5966 loadmodel->brushq3.num_lightgrid = count;
5967 // no swapping or validation necessary
5968 memcpy(out, in, count * (int)sizeof(*out));
5970 if(mod_q3bsp_sRGBlightmaps.integer)
5972 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5974 // we fix the brightness consistently via lightmapscale
5978 for(i = 0; i < count; ++i)
5980 out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5981 out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5982 out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5983 out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
5984 out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
5985 out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
5991 if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5993 for(i = 0; i < count; ++i)
5995 out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5996 out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5997 out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5998 out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
5999 out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6000 out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6011 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6016 if (l->filelen == 0)
6019 // unvised maps often have cluster indices even without pvs, so check
6020 // leafs to find real number of clusters
6021 loadmodel->brush.num_pvsclusters = 1;
6022 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6023 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6026 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6027 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6028 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6029 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6033 in = (q3dpvs_t *)(mod_base + l->fileofs);
6035 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6037 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6038 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6039 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6040 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6041 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6042 if (l->filelen < totalchains + (int)sizeof(*in))
6043 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);
6045 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6046 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6049 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6051 int i, j, k, index[3];
6052 float transformed[3], blend1, blend2, blend, stylescale = 1;
6053 q3dlightgrid_t *a, *s;
6055 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6056 switch(vid.renderpath)
6058 case RENDERPATH_GL20:
6059 case RENDERPATH_D3D9:
6060 case RENDERPATH_D3D10:
6061 case RENDERPATH_D3D11:
6062 case RENDERPATH_SOFT:
6063 case RENDERPATH_GLES2:
6064 // LordHavoc: FIXME: is this true?
6065 stylescale = 1; // added while render
6067 case RENDERPATH_GL11:
6068 case RENDERPATH_GL13:
6069 case RENDERPATH_GLES1:
6070 stylescale = r_refdef.scene.rtlightstylevalue[0];
6074 if (!model->brushq3.num_lightgrid)
6076 ambientcolor[0] = stylescale;
6077 ambientcolor[1] = stylescale;
6078 ambientcolor[2] = stylescale;
6082 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6083 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6084 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6085 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6086 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6087 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6088 index[0] = (int)floor(transformed[0]);
6089 index[1] = (int)floor(transformed[1]);
6090 index[2] = (int)floor(transformed[2]);
6091 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6093 // now lerp the values
6094 VectorClear(diffusenormal);
6095 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6096 for (k = 0;k < 2;k++)
6098 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6099 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6101 for (j = 0;j < 2;j++)
6103 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6104 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6106 for (i = 0;i < 2;i++)
6108 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6109 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6111 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6112 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6113 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6114 // this uses the mod_md3_sin table because the values are
6115 // already in the 0-255 range, the 64+ bias fetches a cosine
6116 // instead of a sine value
6117 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6118 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6119 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6120 //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)));
6125 // normalize the light direction before turning
6126 VectorNormalize(diffusenormal);
6127 //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]);
6130 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6133 double midf, mid[3];
6139 // find the point distances
6140 mplane_t *plane = node->plane;
6141 if (plane->type < 3)
6143 t1 = p1[plane->type] - plane->dist;
6144 t2 = p2[plane->type] - plane->dist;
6148 t1 = DotProduct (plane->normal, p1) - plane->dist;
6149 t2 = DotProduct (plane->normal, p2) - plane->dist;
6156 node = node->children[1];
6165 node = node->children[0];
6171 midf = t1 / (t1 - t2);
6172 VectorLerp(p1, midf, p2, mid);
6174 // recurse both sides, front side first
6175 // return 2 if empty is followed by solid (hit something)
6176 // do not return 2 if both are solid or both empty,
6177 // or if start is solid and end is empty
6178 // as these degenerate cases usually indicate the eye is in solid and
6179 // should see the target point anyway
6180 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
6183 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6188 return ((mleaf_t *)node)->clusterindex < 0;
6191 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6193 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6196 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6197 return trace.fraction == 1;
6201 double tracestart[3], traceend[3];
6202 VectorCopy(start, tracestart);
6203 VectorCopy(end, traceend);
6204 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6208 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)
6211 const bih_leaf_t *leaf;
6212 const bih_node_t *node;
6213 const colbrushf_t *brush;
6216 int nodestackpos = 0;
6217 int nodestack[1024];
6219 memset(trace, 0, sizeof(*trace));
6220 trace->fraction = 1;
6221 trace->realfraction = 1;
6222 trace->hitsupercontentsmask = hitsupercontentsmask;
6224 bih = &model->collision_bih;
6228 nodenum = bih->rootnode;
6229 nodestack[nodestackpos++] = nodenum;
6230 while (nodestackpos)
6232 nodenum = nodestack[--nodestackpos];
6233 node = bih->nodes + nodenum;
6235 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6238 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6240 axis = node->type - BIH_SPLITX;
6241 if (start[axis] >= node->frontmin)
6242 nodestack[nodestackpos++] = node->front;
6243 if (start[axis] <= node->backmax)
6244 nodestack[nodestackpos++] = node->back;
6246 else if (node->type == BIH_UNORDERED)
6248 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6250 leaf = bih->leafs + node->children[axis];
6252 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6258 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6259 Collision_TracePointBrushFloat(trace, start, brush);
6261 case BIH_COLLISIONTRIANGLE:
6262 // collision triangle - skipped because they have no volume
6264 case BIH_RENDERTRIANGLE:
6265 // render triangle - skipped because they have no volume
6273 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)
6275 const bih_leaf_t *leaf;
6276 const bih_node_t *node;
6277 const colbrushf_t *brush;
6279 const texture_t *texture;
6280 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6281 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6282 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6287 if (VectorCompare(start, end))
6289 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6293 nodenum = bih->rootnode;
6295 memset(trace, 0, sizeof(*trace));
6296 trace->fraction = 1;
6297 trace->realfraction = 1;
6298 trace->hitsupercontentsmask = hitsupercontentsmask;
6301 nodestackline[nodestackpos][0] = start[0];
6302 nodestackline[nodestackpos][1] = start[1];
6303 nodestackline[nodestackpos][2] = start[2];
6304 nodestackline[nodestackpos][3] = end[0];
6305 nodestackline[nodestackpos][4] = end[1];
6306 nodestackline[nodestackpos][5] = end[2];
6307 nodestack[nodestackpos++] = nodenum;
6308 while (nodestackpos)
6310 nodenum = nodestack[--nodestackpos];
6311 node = bih->nodes + nodenum;
6312 VectorCopy(nodestackline[nodestackpos], nodestart);
6313 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6314 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]);
6315 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6317 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6319 // recurse children of the split
6320 axis = node->type - BIH_SPLITX;
6321 d1 = node->backmax - nodestart[axis];
6322 d2 = node->backmax - nodeend[axis];
6323 d3 = nodestart[axis] - node->frontmin;
6324 d4 = nodeend[axis] - node->frontmin;
6325 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6327 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;
6328 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;
6329 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;
6330 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6331 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;
6332 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;
6333 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;
6334 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6335 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;
6336 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;
6337 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;
6338 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6339 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6340 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6341 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6342 case 15: /* <<<< */ break;
6345 else if (node->type == BIH_UNORDERED)
6347 // calculate sweep bounds for this node
6348 // copy node bounds into local variables
6349 VectorCopy(node->mins, nodebigmins);
6350 VectorCopy(node->maxs, nodebigmaxs);
6351 // clip line to this node bounds
6352 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); }
6353 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); }
6354 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); }
6355 // some of the line intersected the enlarged node box
6356 // calculate sweep bounds for this node
6357 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]);
6358 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6360 leaf = bih->leafs + node->children[axis];
6361 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6366 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6367 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6369 case BIH_COLLISIONTRIANGLE:
6370 if (!mod_q3bsp_curves_collisions.integer)
6372 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6373 texture = model->data_textures + leaf->textureindex;
6374 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);
6376 case BIH_RENDERTRIANGLE:
6377 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6378 texture = model->data_textures + leaf->textureindex;
6379 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);
6387 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)
6389 if (VectorCompare(start, end))
6391 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6394 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6397 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)
6400 const bih_leaf_t *leaf;
6401 const bih_node_t *node;
6402 const colbrushf_t *brush;
6404 const texture_t *texture;
6405 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6406 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6407 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6408 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6410 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6412 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6413 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6415 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6419 bih = &model->collision_bih;
6422 nodenum = bih->rootnode;
6424 // box trace, performed as brush trace
6425 memset(trace, 0, sizeof(*trace));
6426 trace->fraction = 1;
6427 trace->realfraction = 1;
6428 trace->hitsupercontentsmask = hitsupercontentsmask;
6430 // calculate tracebox-like parameters for efficient culling
6431 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6432 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6433 VectorSubtract(thisbrush_start->mins, start, startmins);
6434 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6435 VectorSubtract(thisbrush_end->mins, end, endmins);
6436 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6437 mins[0] = min(startmins[0], endmins[0]);
6438 mins[1] = min(startmins[1], endmins[1]);
6439 mins[2] = min(startmins[2], endmins[2]);
6440 maxs[0] = max(startmaxs[0], endmaxs[0]);
6441 maxs[1] = max(startmaxs[1], endmaxs[1]);
6442 maxs[2] = max(startmaxs[2], endmaxs[2]);
6445 nodestackline[nodestackpos][0] = start[0];
6446 nodestackline[nodestackpos][1] = start[1];
6447 nodestackline[nodestackpos][2] = start[2];
6448 nodestackline[nodestackpos][3] = end[0];
6449 nodestackline[nodestackpos][4] = end[1];
6450 nodestackline[nodestackpos][5] = end[2];
6451 nodestack[nodestackpos++] = nodenum;
6452 while (nodestackpos)
6454 nodenum = nodestack[--nodestackpos];
6455 node = bih->nodes + nodenum;
6456 VectorCopy(nodestackline[nodestackpos], nodestart);
6457 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6458 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];
6459 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6461 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6463 // recurse children of the split
6464 axis = node->type - BIH_SPLITX;
6465 d1 = node->backmax - nodestart[axis] - mins[axis];
6466 d2 = node->backmax - nodeend[axis] - mins[axis];
6467 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6468 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6469 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6471 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;
6472 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;
6473 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;
6474 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6475 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;
6476 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;
6477 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;
6478 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6479 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;
6480 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;
6481 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;
6482 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6483 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6484 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6485 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6486 case 15: /* <<<< */ break;
6489 else if (node->type == BIH_UNORDERED)
6491 // calculate sweep bounds for this node
6492 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6493 VectorSubtract(node->mins, maxs, nodebigmins);
6494 VectorSubtract(node->maxs, mins, nodebigmaxs);
6495 // clip line to this node bounds
6496 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); }
6497 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); }
6498 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); }
6499 // some of the line intersected the enlarged node box
6500 // calculate sweep bounds for this node
6501 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];
6502 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6504 leaf = bih->leafs + node->children[axis];
6505 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6510 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6511 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6513 case BIH_COLLISIONTRIANGLE:
6514 if (!mod_q3bsp_curves_collisions.integer)
6516 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6517 texture = model->data_textures + leaf->textureindex;
6518 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);
6520 case BIH_RENDERTRIANGLE:
6521 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6522 texture = model->data_textures + leaf->textureindex;
6523 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);
6531 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)
6533 colboxbrushf_t thisbrush_start, thisbrush_end;
6534 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6536 // box trace, performed as brush trace
6537 VectorAdd(start, boxmins, boxstartmins);
6538 VectorAdd(start, boxmaxs, boxstartmaxs);
6539 VectorAdd(end, boxmins, boxendmins);
6540 VectorAdd(end, boxmaxs, boxendmaxs);
6541 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6542 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6543 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6547 static int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6550 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6551 return trace.startsupercontents;
6554 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)
6557 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6559 int hitsupercontents;
6560 VectorSet(end, start[0], start[1], model->normalmins[2]);
6562 memset(trace, 0, sizeof(*trace));
6563 trace->fraction = 1;
6564 trace->realfraction = 1;
6565 trace->hitsupercontentsmask = hitsupercontentsmask;
6567 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6568 hitsupercontents = trace->hitsupercontents;
6569 memset(trace, 0, sizeof(*trace));
6570 trace->fraction = 1;
6571 trace->realfraction = 1;
6572 trace->hitsupercontentsmask = hitsupercontentsmask;
6573 trace->startsupercontents = hitsupercontents;
6577 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6580 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6583 VectorSet(end, start[0], start[1], model->normalmins[2]);
6584 memset(&trace, 0, sizeof(trace));
6586 trace.realfraction = 1;
6587 trace.hitsupercontentsmask = 0;
6588 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6589 return trace.hitsupercontents;
6595 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6600 // find which leaf the point is in
6602 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6603 // point trace the brushes
6604 leaf = (mleaf_t *)node;
6605 for (i = 0;i < leaf->numleafbrushes;i++)
6607 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6608 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6610 brush->markframe = markframe;
6611 Collision_TracePointBrushFloat(trace, point, brush);
6614 // can't do point traces on curves (they have no thickness)
6617 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)
6619 int i, startside, endside;
6620 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6622 msurface_t *surface;
6625 // walk the tree until we hit a leaf, recursing for any split cases
6629 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6631 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6632 node = node->children[1];
6634 // abort if this part of the bsp tree can not be hit by this trace
6635 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6637 plane = node->plane;
6638 // axial planes are much more common than non-axial, so an optimized
6639 // axial case pays off here
6640 if (plane->type < 3)
6642 dist1 = start[plane->type] - plane->dist;
6643 dist2 = end[plane->type] - plane->dist;
6647 dist1 = DotProduct(start, plane->normal) - plane->dist;
6648 dist2 = DotProduct(end, plane->normal) - plane->dist;
6650 startside = dist1 < 0;
6651 endside = dist2 < 0;
6652 if (startside == endside)
6654 // most of the time the line fragment is on one side of the plane
6655 node = node->children[startside];
6659 // line crosses node plane, split the line
6660 dist1 = PlaneDiff(linestart, plane);
6661 dist2 = PlaneDiff(lineend, plane);
6662 midfrac = dist1 / (dist1 - dist2);
6663 VectorLerp(linestart, midfrac, lineend, mid);
6664 // take the near side first
6665 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6666 // if we found an impact on the front side, don't waste time
6667 // exploring the far side
6668 if (midfrac <= trace->realfraction)
6669 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6674 // abort if this part of the bsp tree can not be hit by this trace
6675 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6678 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6679 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6680 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6681 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6682 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6683 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6684 // line trace the brushes
6685 leaf = (mleaf_t *)node;
6687 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6690 for (i = 0;i < leaf->numleafbrushes;i++)
6692 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6693 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6695 brush->markframe = markframe;
6696 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6699 // can't do point traces on curves (they have no thickness)
6700 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6702 // line trace the curves
6703 for (i = 0;i < leaf->numleafsurfaces;i++)
6705 surface = model->data_surfaces + leaf->firstleafsurface[i];
6706 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6708 surface->deprecatedq3collisionmarkframe = markframe;
6709 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);
6715 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)
6721 msurface_t *surface;
6723 float nodesegmentmins[3], nodesegmentmaxs[3];
6724 // walk the tree until we hit a leaf, recursing for any split cases
6728 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6730 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6731 node = node->children[1];
6733 // abort if this part of the bsp tree can not be hit by this trace
6734 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6736 plane = node->plane;
6737 // axial planes are much more common than non-axial, so an optimized
6738 // axial case pays off here
6739 if (plane->type < 3)
6741 // this is an axial plane, compare bounding box directly to it and
6742 // recurse sides accordingly
6743 // recurse down node sides
6744 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6745 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6746 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6747 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6751 // this is a non-axial plane, so check if the start and end boxes
6752 // are both on one side of the plane to handle 'diagonal' cases
6753 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6757 // segment crosses plane
6758 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6761 // if sides == 0 then the trace itself is bogus (Not A Number values),
6762 // in this case we simply pretend the trace hit nothing
6764 return; // ERROR: NAN bounding box!
6765 // take whichever side the segment box is on
6766 node = node->children[sides - 1];
6769 // abort if this part of the bsp tree can not be hit by this trace
6770 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6772 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6773 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6774 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6775 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6776 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6777 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6779 leaf = (mleaf_t *)node;
6781 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6784 for (i = 0;i < leaf->numleafbrushes;i++)
6786 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6787 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6789 brush->markframe = markframe;
6790 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6793 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6795 for (i = 0;i < leaf->numleafsurfaces;i++)
6797 surface = model->data_surfaces + leaf->firstleafsurface[i];
6798 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6800 surface->deprecatedq3collisionmarkframe = markframe;
6801 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);
6808 static int markframe = 0;
6810 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)
6814 memset(trace, 0, sizeof(*trace));
6815 trace->fraction = 1;
6816 trace->realfraction = 1;
6817 trace->hitsupercontentsmask = hitsupercontentsmask;
6818 if (mod_collision_bih.integer)
6819 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6820 else if (model->brush.submodel)
6822 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6823 if (brush->colbrushf)
6824 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6827 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6830 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)
6833 float segmentmins[3], segmentmaxs[3];
6834 msurface_t *surface;
6837 if (VectorCompare(start, end))
6839 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6843 memset(trace, 0, sizeof(*trace));
6844 trace->fraction = 1;
6845 trace->realfraction = 1;
6846 trace->hitsupercontentsmask = hitsupercontentsmask;
6847 segmentmins[0] = min(start[0], end[0]) - 1;
6848 segmentmins[1] = min(start[1], end[1]) - 1;
6849 segmentmins[2] = min(start[2], end[2]) - 1;
6850 segmentmaxs[0] = max(start[0], end[0]) + 1;
6851 segmentmaxs[1] = max(start[1], end[1]) + 1;
6852 segmentmaxs[2] = max(start[2], end[2]) + 1;
6853 if (mod_collision_bih.integer)
6854 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6855 else if (model->brush.submodel)
6857 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6858 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6859 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6860 if (mod_q3bsp_curves_collisions.integer)
6861 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6862 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6863 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);
6866 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6869 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)
6871 float segmentmins[3], segmentmaxs[3];
6873 msurface_t *surface;
6876 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6878 if (VectorCompare(start->mins, end->mins))
6879 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6881 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6885 // box trace, performed as brush trace
6886 memset(trace, 0, sizeof(*trace));
6887 trace->fraction = 1;
6888 trace->realfraction = 1;
6889 trace->hitsupercontentsmask = hitsupercontentsmask;
6890 segmentmins[0] = min(start->mins[0], end->mins[0]);
6891 segmentmins[1] = min(start->mins[1], end->mins[1]);
6892 segmentmins[2] = min(start->mins[2], end->mins[2]);
6893 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6894 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6895 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6896 if (mod_collision_bih.integer)
6897 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6898 else if (model->brush.submodel)
6900 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6901 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6902 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6903 if (mod_q3bsp_curves_collisions.integer)
6904 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6905 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6906 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);
6909 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6912 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)
6914 colboxbrushf_t thisbrush_start, thisbrush_end;
6915 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6917 // box trace, performed as brush trace
6918 VectorAdd(start, boxmins, boxstartmins);
6919 VectorAdd(start, boxmaxs, boxstartmaxs);
6920 VectorAdd(end, boxmins, boxendmins);
6921 VectorAdd(end, boxmaxs, boxendmaxs);
6922 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6923 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6924 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6927 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6930 int supercontents = 0;
6932 if (mod_collision_bih.integer)
6934 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
6936 // test if the point is inside each brush
6937 else if (model->brush.submodel)
6939 // submodels are effectively one leaf
6940 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6941 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6942 supercontents |= brush->colbrushf->supercontents;
6946 mnode_t *node = model->brush.data_nodes;
6948 // find which leaf the point is in
6950 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6951 leaf = (mleaf_t *)node;
6952 // now check the brushes in the leaf
6953 for (i = 0;i < leaf->numleafbrushes;i++)
6955 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6956 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6957 supercontents |= brush->colbrushf->supercontents;
6960 return supercontents;
6963 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)
6965 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6969 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6977 int nummodelbrushes = model->nummodelbrushes;
6978 int nummodelsurfaces = model->nummodelsurfaces;
6980 const int *collisionelement3i;
6981 const float *collisionvertex3f;
6982 const int *renderelement3i;
6983 const float *rendervertex3f;
6984 bih_leaf_t *bihleafs;
6985 bih_node_t *bihnodes;
6987 int *temp_leafsortscratch;
6988 const msurface_t *surface;
6989 const q3mbrush_t *brush;
6991 // find out how many BIH leaf nodes we need
6993 if (userendersurfaces)
6995 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6996 bihnumleafs += surface->num_triangles;
7000 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7001 if (brush->colbrushf)
7003 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7005 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7006 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7008 bihnumleafs += surface->num_collisiontriangles;
7015 // allocate the memory for the BIH leaf nodes
7016 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7018 // now populate the BIH leaf nodes
7021 // add render surfaces
7022 renderelement3i = model->surfmesh.data_element3i;
7023 rendervertex3f = model->surfmesh.data_vertex3f;
7024 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7026 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7028 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7030 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7031 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7032 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7033 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7034 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7035 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7036 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7037 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7038 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7039 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7044 if (!userendersurfaces)
7046 // add collision brushes
7047 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7049 if (!brush->colbrushf)
7051 bihleafs[bihleafindex].type = BIH_BRUSH;
7052 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7053 bihleafs[bihleafindex].surfaceindex = -1;
7054 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7055 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7056 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7060 // add collision surfaces
7061 collisionelement3i = model->brush.data_collisionelement3i;
7062 collisionvertex3f = model->brush.data_collisionvertex3f;
7063 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7065 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7067 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7068 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7069 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7070 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7071 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7072 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7073 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7074 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7075 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7076 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7082 // allocate buffers for the produced and temporary data
7083 bihmaxnodes = bihnumleafs + 1;
7084 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7085 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7086 temp_leafsortscratch = temp_leafsort + bihnumleafs;
7089 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7091 // we're done with the temporary data
7092 Mem_Free(temp_leafsort);
7094 // resize the BIH nodes array if it over-allocated
7095 if (out->maxnodes > out->numnodes)
7097 out->maxnodes = out->numnodes;
7098 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7104 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7106 int supercontents = 0;
7107 if (nativecontents & CONTENTSQ3_SOLID)
7108 supercontents |= SUPERCONTENTS_SOLID;
7109 if (nativecontents & CONTENTSQ3_WATER)
7110 supercontents |= SUPERCONTENTS_WATER;
7111 if (nativecontents & CONTENTSQ3_SLIME)
7112 supercontents |= SUPERCONTENTS_SLIME;
7113 if (nativecontents & CONTENTSQ3_LAVA)
7114 supercontents |= SUPERCONTENTS_LAVA;
7115 if (nativecontents & CONTENTSQ3_BODY)
7116 supercontents |= SUPERCONTENTS_BODY;
7117 if (nativecontents & CONTENTSQ3_CORPSE)
7118 supercontents |= SUPERCONTENTS_CORPSE;
7119 if (nativecontents & CONTENTSQ3_NODROP)
7120 supercontents |= SUPERCONTENTS_NODROP;
7121 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7122 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7123 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7124 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7125 if (nativecontents & CONTENTSQ3_DONOTENTER)
7126 supercontents |= SUPERCONTENTS_DONOTENTER;
7127 if (nativecontents & CONTENTSQ3_BOTCLIP)
7128 supercontents |= SUPERCONTENTS_BOTCLIP;
7129 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7130 supercontents |= SUPERCONTENTS_OPAQUE;
7131 return supercontents;
7134 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7136 int nativecontents = 0;
7137 if (supercontents & SUPERCONTENTS_SOLID)
7138 nativecontents |= CONTENTSQ3_SOLID;
7139 if (supercontents & SUPERCONTENTS_WATER)
7140 nativecontents |= CONTENTSQ3_WATER;
7141 if (supercontents & SUPERCONTENTS_SLIME)
7142 nativecontents |= CONTENTSQ3_SLIME;
7143 if (supercontents & SUPERCONTENTS_LAVA)
7144 nativecontents |= CONTENTSQ3_LAVA;
7145 if (supercontents & SUPERCONTENTS_BODY)
7146 nativecontents |= CONTENTSQ3_BODY;
7147 if (supercontents & SUPERCONTENTS_CORPSE)
7148 nativecontents |= CONTENTSQ3_CORPSE;
7149 if (supercontents & SUPERCONTENTS_NODROP)
7150 nativecontents |= CONTENTSQ3_NODROP;
7151 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7152 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7153 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7154 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7155 if (supercontents & SUPERCONTENTS_DONOTENTER)
7156 nativecontents |= CONTENTSQ3_DONOTENTER;
7157 if (supercontents & SUPERCONTENTS_BOTCLIP)
7158 nativecontents |= CONTENTSQ3_BOTCLIP;
7159 if (!(supercontents & SUPERCONTENTS_OPAQUE))
7160 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7161 return nativecontents;
7164 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7169 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7170 node = node->children[1];
7172 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7173 if (loadmodel->brush.num_leafs < numleafs)
7174 loadmodel->brush.num_leafs = numleafs;
7177 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7180 q3dheader_t *header;
7181 float corner[3], yawradius, modelradius;
7183 mod->modeldatatypestring = "Q3BSP";
7185 mod->type = mod_brushq3;
7186 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7189 header = (q3dheader_t *)buffer;
7190 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7191 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7193 i = LittleLong(header->version);
7194 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7195 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7197 mod->soundfromcenter = true;
7198 mod->TraceBox = Mod_Q3BSP_TraceBox;
7199 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7200 mod->TraceLine = Mod_Q3BSP_TraceLine;
7201 mod->TracePoint = Mod_Q3BSP_TracePoint;
7202 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7203 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7204 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7205 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7206 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7207 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7208 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7209 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7210 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7211 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7212 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7213 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7214 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7215 mod->brush.AmbientSoundLevelsForPoint = NULL;
7216 mod->brush.RoundUpToHullSize = NULL;
7217 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7218 mod->Draw = R_Q1BSP_Draw;
7219 mod->DrawDepth = R_Q1BSP_DrawDepth;
7220 mod->DrawDebug = R_Q1BSP_DrawDebug;
7221 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7222 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7223 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7224 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7225 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7226 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7227 mod->DrawLight = R_Q1BSP_DrawLight;
7229 mod_base = (unsigned char *)header;
7231 // swap all the lumps
7232 header->ident = LittleLong(header->ident);
7233 header->version = LittleLong(header->version);
7234 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7235 for (i = 0;i < lumps;i++)
7237 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7238 if((char *) bufferend < (char *) buffer + j)
7239 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7240 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7241 if((char *) bufferend < (char *) buffer + j)
7242 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7245 * NO, do NOT clear them!
7246 * they contain actual data referenced by other stuff.
7247 * Instead, before using the advertisements lump, check header->versio
7249 * Sorry, but otherwise it breaks memory of the first lump.
7250 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7252 header->lumps[i].fileofs = 0;
7253 header->lumps[i].filelen = 0;
7257 mod->brush.qw_md4sum = 0;
7258 mod->brush.qw_md4sum2 = 0;
7259 for (i = 0;i < lumps;i++)
7261 if (i == Q3LUMP_ENTITIES)
7263 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7264 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7266 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7268 // all this checksumming can take a while, so let's send keepalives here too
7269 CL_KeepaliveMessage(false);
7272 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7273 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7274 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7275 if (header->version == Q3BSPVERSION_IG)
7276 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7278 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7279 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7280 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7281 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7282 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7283 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7284 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7285 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7286 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7287 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7288 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7289 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7290 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7291 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7292 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7294 // the MakePortals code works fine on the q3bsp data as well
7295 if (mod_bsp_portalize.integer)
7296 Mod_Q1BSP_MakePortals();
7298 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7299 loadmodel->brush.supportwateralpha = true;
7301 // make a single combined shadow mesh to allow optimized shadow volume creation
7302 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7304 loadmodel->brush.num_leafs = 0;
7305 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7307 if (loadmodel->brush.numsubmodels)
7308 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7311 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7316 // duplicate the basic information
7317 dpsnprintf(name, sizeof(name), "*%i", i);
7318 mod = Mod_FindName(name, loadmodel->name);
7319 // copy the base model to this one
7321 // rename the clone back to its proper name
7322 strlcpy(mod->name, name, sizeof(mod->name));
7323 mod->brush.parentmodel = loadmodel;
7324 // textures and memory belong to the main model
7325 mod->texturepool = NULL;
7326 mod->mempool = NULL;
7327 mod->brush.GetPVS = NULL;
7328 mod->brush.FatPVS = NULL;
7329 mod->brush.BoxTouchingPVS = NULL;
7330 mod->brush.BoxTouchingLeafPVS = NULL;
7331 mod->brush.BoxTouchingVisibleLeafs = NULL;
7332 mod->brush.FindBoxClusters = NULL;
7333 mod->brush.LightPoint = NULL;
7334 mod->brush.AmbientSoundLevelsForPoint = NULL;
7336 mod->brush.submodel = i;
7337 if (loadmodel->brush.submodels)
7338 loadmodel->brush.submodels[i] = mod;
7340 // make the model surface list (used by shadowing/lighting)
7341 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7342 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7343 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7344 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7345 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7346 Mod_MakeSortedSurfaces(mod);
7348 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7349 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7350 // enlarge the bounding box to enclose all geometry of this model,
7351 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7352 // which can in turn mess up the farclip (as well as culling when
7353 // outside the level - an unimportant concern)
7355 //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]);
7356 for (j = 0;j < mod->nummodelsurfaces;j++)
7358 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7359 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7361 if (!surface->num_vertices)
7363 for (k = 0;k < surface->num_vertices;k++, v += 3)
7365 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7366 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7367 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7368 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7369 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7370 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7373 //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]);
7374 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7375 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7376 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7377 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7378 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7379 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7380 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7381 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7382 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7383 mod->yawmins[2] = mod->normalmins[2];
7384 mod->yawmaxs[2] = mod->normalmaxs[2];
7385 mod->radius = modelradius;
7386 mod->radius2 = modelradius * modelradius;
7388 // this gets altered below if sky or water is used
7389 mod->DrawSky = NULL;
7390 mod->DrawAddWaterPlanes = NULL;
7392 for (j = 0;j < mod->nummodelsurfaces;j++)
7393 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7395 if (j < mod->nummodelsurfaces)
7396 mod->DrawSky = R_Q1BSP_DrawSky;
7398 for (j = 0;j < mod->nummodelsurfaces;j++)
7399 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7401 if (j < mod->nummodelsurfaces)
7402 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7404 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7405 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7407 // generate VBOs and other shared data before cloning submodels
7412 if (mod_q3bsp_sRGBlightmaps.integer)
7414 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7416 // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7417 // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7418 // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7419 // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7420 //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7422 else // if this is NOT set, regular rendering looks right by this requirement anyway
7425 // we want color 1 to do the same as without sRGB
7426 // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7427 loadmodel->lightmapscale *= 2.476923f; // fixes max level
7430 // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7431 // we need to undo that
7432 loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7436 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);
7439 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7441 int i = LittleLong(((int *)buffer)[1]);
7442 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7443 Mod_Q3BSP_Load(mod,buffer, bufferend);
7444 else if (i == Q2BSPVERSION)
7445 Mod_Q2BSP_Load(mod,buffer, bufferend);
7447 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7450 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7452 Host_Error("Mod_MAP_Load: not yet implemented");
7455 typedef struct objvertex_s
7466 static unsigned char nobsp_pvs[1] = {1};
7468 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7470 const char *textbase = (char *)buffer, *text = textbase;
7474 char materialname[MAX_QPATH];
7475 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7476 int index1, index2, index3;
7477 objvertex_t vfirst, vprev, vcurrent;
7480 int numtriangles = 0;
7481 int maxtriangles = 0;
7482 objvertex_t *vertices = NULL;
7484 int maxtextures = 0, numtextures = 0, textureindex = 0;
7485 int maxv = 0, numv = 1;
7486 int maxvt = 0, numvt = 1;
7487 int maxvn = 0, numvn = 1;
7488 char *texturenames = NULL;
7489 float dist, modelradius, modelyawradius, yawradius;
7496 objvertex_t *thisvertex = NULL;
7497 int vertexhashindex;
7498 int *vertexhashtable = NULL;
7499 objvertex_t *vertexhashdata = NULL;
7500 objvertex_t *vdata = NULL;
7501 int vertexhashsize = 0;
7502 int vertexhashcount = 0;
7503 skinfile_t *skinfiles = NULL;
7504 unsigned char *data = NULL;
7505 int *submodelfirstsurface;
7506 msurface_t *surface;
7507 msurface_t *tempsurfaces;
7509 memset(&vfirst, 0, sizeof(vfirst));
7510 memset(&vprev, 0, sizeof(vprev));
7511 memset(&vcurrent, 0, sizeof(vcurrent));
7513 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7515 loadmodel->modeldatatypestring = "OBJ";
7517 loadmodel->type = mod_obj;
7518 loadmodel->soundfromcenter = true;
7519 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7520 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7521 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7522 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7523 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7524 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7525 loadmodel->brush.TraceLineOfSight = NULL;
7526 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7527 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7528 loadmodel->brush.GetPVS = NULL;
7529 loadmodel->brush.FatPVS = NULL;
7530 loadmodel->brush.BoxTouchingPVS = NULL;
7531 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7532 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7533 loadmodel->brush.FindBoxClusters = NULL;
7534 loadmodel->brush.LightPoint = NULL;
7535 loadmodel->brush.FindNonSolidLocation = NULL;
7536 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7537 loadmodel->brush.RoundUpToHullSize = NULL;
7538 loadmodel->brush.PointInLeaf = NULL;
7539 loadmodel->Draw = R_Q1BSP_Draw;
7540 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7541 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7542 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7543 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7544 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7545 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7546 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7547 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7548 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7550 skinfiles = Mod_LoadSkinFiles();
7551 if (loadmodel->numskins < 1)
7552 loadmodel->numskins = 1;
7554 // make skinscenes for the skins (no groups)
7555 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7556 for (i = 0;i < loadmodel->numskins;i++)
7558 loadmodel->skinscenes[i].firstframe = i;
7559 loadmodel->skinscenes[i].framecount = 1;
7560 loadmodel->skinscenes[i].loop = true;
7561 loadmodel->skinscenes[i].framerate = 10;
7567 // we always have model 0, i.e. the first "submodel"
7568 loadmodel->brush.numsubmodels = 1;
7570 // parse the OBJ text now
7573 static char emptyarg[1] = "";
7578 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7579 line[linelen] = text[linelen];
7581 for (argc = 0;argc < 4;argc++)
7582 argv[argc] = emptyarg;
7585 while (*s == ' ' || *s == '\t')
7595 while (*s == ' ' || *s == '\t')
7605 if (argv[0][0] == '#')
7607 if (!strcmp(argv[0], "v"))
7611 maxv = max(maxv * 2, 1024);
7612 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7614 if(mod_obj_orientation.integer)
7616 v[numv*3+0] = atof(argv[1]);
7617 v[numv*3+2] = atof(argv[2]);
7618 v[numv*3+1] = atof(argv[3]);
7622 v[numv*3+0] = atof(argv[1]);
7623 v[numv*3+1] = atof(argv[2]);
7624 v[numv*3+2] = atof(argv[3]);
7628 else if (!strcmp(argv[0], "vt"))
7632 maxvt = max(maxvt * 2, 1024);
7633 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7635 vt[numvt*2+0] = atof(argv[1]);
7636 vt[numvt*2+1] = 1-atof(argv[2]);
7639 else if (!strcmp(argv[0], "vn"))
7643 maxvn = max(maxvn * 2, 1024);
7644 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7646 if(mod_obj_orientation.integer)
7648 vn[numvn*3+0] = atof(argv[1]);
7649 vn[numvn*3+2] = atof(argv[2]);
7650 vn[numvn*3+1] = atof(argv[3]);
7654 vn[numvn*3+0] = atof(argv[1]);
7655 vn[numvn*3+1] = atof(argv[2]);
7656 vn[numvn*3+2] = atof(argv[3]);
7660 else if (!strcmp(argv[0], "f"))
7664 if (maxtextures <= numtextures)
7666 maxtextures = max(maxtextures * 2, 256);
7667 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7669 textureindex = numtextures++;
7670 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7672 for (j = 1;j < argc;j++)
7674 index1 = atoi(argv[j]);
7675 while(argv[j][0] && argv[j][0] != '/')
7679 index2 = atoi(argv[j]);
7680 while(argv[j][0] && argv[j][0] != '/')
7684 index3 = atoi(argv[j]);
7685 // negative refers to a recent vertex
7686 // zero means not specified
7687 // positive means an absolute vertex index
7689 index1 = numv - index1;
7691 index2 = numvt - index2;
7693 index3 = numvn - index3;
7694 vcurrent.nextindex = -1;
7695 vcurrent.textureindex = textureindex;
7696 vcurrent.submodelindex = submodelindex;
7697 if (v && index1 >= 0 && index1 < numv)
7698 VectorCopy(v + 3*index1, vcurrent.v);
7699 if (vt && index2 >= 0 && index2 < numvt)
7700 Vector2Copy(vt + 2*index2, vcurrent.vt);
7701 if (vn && index3 >= 0 && index3 < numvn)
7702 VectorCopy(vn + 3*index3, vcurrent.vn);
7703 if (numtriangles == 0)
7705 VectorCopy(vcurrent.v, mins);
7706 VectorCopy(vcurrent.v, maxs);
7710 mins[0] = min(mins[0], vcurrent.v[0]);
7711 mins[1] = min(mins[1], vcurrent.v[1]);
7712 mins[2] = min(mins[2], vcurrent.v[2]);
7713 maxs[0] = max(maxs[0], vcurrent.v[0]);
7714 maxs[1] = max(maxs[1], vcurrent.v[1]);
7715 maxs[2] = max(maxs[2], vcurrent.v[2]);
7721 if (maxtriangles <= numtriangles)
7723 maxtriangles = max(maxtriangles * 2, 32768);
7724 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7726 if(mod_obj_orientation.integer)
7728 vertices[numtriangles*3+0] = vfirst;
7729 vertices[numtriangles*3+1] = vprev;
7730 vertices[numtriangles*3+2] = vcurrent;
7734 vertices[numtriangles*3+0] = vfirst;
7735 vertices[numtriangles*3+2] = vprev;
7736 vertices[numtriangles*3+1] = vcurrent;
7743 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7745 submodelindex = atof(argv[1]);
7746 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7748 else if (!strcmp(argv[0], "usemtl"))
7750 for (i = 0;i < numtextures;i++)
7751 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7753 if (i < numtextures)
7757 if (maxtextures <= numtextures)
7759 maxtextures = max(maxtextures * 2, 256);
7760 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7762 textureindex = numtextures++;
7763 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7768 // now that we have the OBJ data loaded as-is, we can convert it
7770 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7771 VectorCopy(mins, loadmodel->normalmins);
7772 VectorCopy(maxs, loadmodel->normalmaxs);
7773 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7774 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7775 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7776 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7777 modelradius = modelyawradius + modelradius * modelradius;
7778 modelyawradius = sqrt(modelyawradius);
7779 modelradius = sqrt(modelradius);
7780 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7781 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7782 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7783 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7784 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7785 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7786 loadmodel->radius = modelradius;
7787 loadmodel->radius2 = modelradius * modelradius;
7789 // allocate storage for triangles
7790 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7791 // allocate vertex hash structures to build an optimal vertex subset
7792 vertexhashsize = numtriangles*2;
7793 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7794 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7795 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7796 vertexhashcount = 0;
7798 // gather surface stats for assigning vertex/triangle ranges
7802 loadmodel->num_surfaces = 0;
7803 // allocate storage for the worst case number of surfaces, later we resize
7804 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7805 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7806 surface = tempsurfaces;
7807 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7809 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7810 for (textureindex = 0;textureindex < numtextures;textureindex++)
7812 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7814 thisvertex = vertices + vertexindex;
7815 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7818 // skip the surface creation if there are no triangles for it
7819 if (vertexindex == numtriangles*3)
7821 // create a surface for these vertices
7822 surfacevertices = 0;
7823 surfaceelements = 0;
7824 // we hack in a texture index in the surface to be fixed up later...
7825 surface->texture = (texture_t *)((size_t)textureindex);
7826 // calculate bounds as we go
7827 VectorCopy(thisvertex->v, surface->mins);
7828 VectorCopy(thisvertex->v, surface->maxs);
7829 for (;vertexindex < numtriangles*3;vertexindex++)
7831 thisvertex = vertices + vertexindex;
7832 if (thisvertex->submodelindex != submodelindex)
7834 if (thisvertex->textureindex != textureindex)
7836 // add vertex to surface bounds
7837 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7838 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7839 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7840 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7841 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7842 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7843 // add the vertex if it is not found in the merged set, and
7844 // get its index (triangle element) for the surface
7845 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7846 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7848 vdata = vertexhashdata + i;
7849 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7854 i = vertexhashcount++;
7855 vdata = vertexhashdata + i;
7856 *vdata = *thisvertex;
7857 vdata->nextindex = vertexhashtable[vertexhashindex];
7858 vertexhashtable[vertexhashindex] = i;
7861 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7864 surfacetriangles = surfaceelements / 3;
7865 surface->num_vertices = surfacevertices;
7866 surface->num_triangles = surfacetriangles;
7867 surface->num_firstvertex = firstvertex;
7868 surface->num_firsttriangle = firsttriangle;
7869 firstvertex += surface->num_vertices;
7870 firsttriangle += surface->num_triangles;
7872 loadmodel->num_surfaces++;
7875 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7876 numvertices = firstvertex;
7877 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7878 tempsurfaces = NULL;
7880 // allocate storage for final mesh data
7881 loadmodel->num_textures = numtextures * loadmodel->numskins;
7882 loadmodel->num_texturesperskin = numtextures;
7883 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 *));
7884 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7885 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7886 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7887 loadmodel->surfmesh.num_vertices = numvertices;
7888 loadmodel->surfmesh.num_triangles = numtriangles;
7889 if (r_enableshadowvolumes.integer)
7890 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7891 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7892 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7893 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7894 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7895 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7896 if (loadmodel->surfmesh.num_vertices <= 65536)
7897 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7899 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7901 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7902 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7903 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7906 // load the textures
7907 for (textureindex = 0;textureindex < numtextures;textureindex++)
7908 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7909 Mod_FreeSkinFiles(skinfiles);
7911 // set the surface textures to their real values now that we loaded them...
7912 for (i = 0;i < loadmodel->num_surfaces;i++)
7913 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7917 Mem_Free(texturenames);
7921 Mem_Free(vertexhashtable);
7922 Mem_Free(vertexhashdata);
7924 // make a single combined shadow mesh to allow optimized shadow volume creation
7925 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7927 // compute all the mesh information that was not loaded from the file
7928 if (loadmodel->surfmesh.data_element3s)
7929 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7930 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7931 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7932 // generate normals if the file did not have them
7933 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7934 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);
7935 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);
7936 if (loadmodel->surfmesh.data_neighbor3i)
7937 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7939 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7940 loadmodel->brush.num_visleafs = 1;
7941 loadmodel->brush.num_leafs = 1;
7942 loadmodel->brush.num_nodes = 0;
7943 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7944 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7945 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7946 loadmodel->brush.num_pvsclusters = 1;
7947 loadmodel->brush.num_pvsclusterbytes = 1;
7948 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7949 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7950 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7951 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7952 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7953 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7954 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7955 loadmodel->brush.data_leafs->clusterindex = 0;
7956 loadmodel->brush.data_leafs->areaindex = 0;
7957 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7958 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7959 loadmodel->brush.data_leafs->numleafbrushes = 0;
7960 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7961 loadmodel->brush.supportwateralpha = true;
7963 if (loadmodel->brush.numsubmodels)
7964 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7967 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7972 // duplicate the basic information
7973 dpsnprintf(name, sizeof(name), "*%i", i);
7974 mod = Mod_FindName(name, loadmodel->name);
7975 // copy the base model to this one
7977 // rename the clone back to its proper name
7978 strlcpy(mod->name, name, sizeof(mod->name));
7979 mod->brush.parentmodel = loadmodel;
7980 // textures and memory belong to the main model
7981 mod->texturepool = NULL;
7982 mod->mempool = NULL;
7983 mod->brush.GetPVS = NULL;
7984 mod->brush.FatPVS = NULL;
7985 mod->brush.BoxTouchingPVS = NULL;
7986 mod->brush.BoxTouchingLeafPVS = NULL;
7987 mod->brush.BoxTouchingVisibleLeafs = NULL;
7988 mod->brush.FindBoxClusters = NULL;
7989 mod->brush.LightPoint = NULL;
7990 mod->brush.AmbientSoundLevelsForPoint = NULL;
7992 mod->brush.submodel = i;
7993 if (loadmodel->brush.submodels)
7994 loadmodel->brush.submodels[i] = mod;
7996 // make the model surface list (used by shadowing/lighting)
7997 mod->firstmodelsurface = submodelfirstsurface[i];
7998 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7999 mod->firstmodelbrush = 0;
8000 mod->nummodelbrushes = 0;
8001 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8002 Mod_MakeSortedSurfaces(mod);
8004 VectorClear(mod->normalmins);
8005 VectorClear(mod->normalmaxs);
8007 for (j = 0;j < mod->nummodelsurfaces;j++)
8009 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8010 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8012 if (!surface->num_vertices)
8017 VectorCopy(v, mod->normalmins);
8018 VectorCopy(v, mod->normalmaxs);
8020 for (k = 0;k < surface->num_vertices;k++, v += 3)
8022 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
8023 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
8024 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
8025 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
8026 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
8027 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
8030 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8031 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8032 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8033 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8034 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8035 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8036 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8037 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8038 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8039 mod->yawmins[2] = mod->normalmins[2];
8040 mod->yawmaxs[2] = mod->normalmaxs[2];
8041 mod->radius = modelradius;
8042 mod->radius2 = modelradius * modelradius;
8044 // this gets altered below if sky or water is used
8045 mod->DrawSky = NULL;
8046 mod->DrawAddWaterPlanes = NULL;
8048 for (j = 0;j < mod->nummodelsurfaces;j++)
8049 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8051 if (j < mod->nummodelsurfaces)
8052 mod->DrawSky = R_Q1BSP_DrawSky;
8054 for (j = 0;j < mod->nummodelsurfaces;j++)
8055 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8057 if (j < mod->nummodelsurfaces)
8058 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8060 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8061 mod->render_bih = mod->collision_bih;
8063 // generate VBOs and other shared data before cloning submodels
8068 Mem_Free(submodelfirstsurface);
8070 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);