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_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
44 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)"};
45 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)"};
46 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
47 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
48 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, ..."};
49 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)"};
50 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
51 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"};
52 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
53 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
54 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
55 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
56 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)"};
57 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"};
58 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"};
60 static texture_t mod_q1bsp_texture_solid;
61 static texture_t mod_q1bsp_texture_sky;
62 static texture_t mod_q1bsp_texture_lava;
63 static texture_t mod_q1bsp_texture_slime;
64 static texture_t mod_q1bsp_texture_water;
66 void Mod_BrushInit(void)
68 // Cvar_RegisterVariable(&r_subdivide_size);
69 Cvar_RegisterVariable(&mod_bsp_portalize);
70 Cvar_RegisterVariable(&r_novis);
71 Cvar_RegisterVariable(&r_nosurftextures);
72 Cvar_RegisterVariable(&r_subdivisions_tolerance);
73 Cvar_RegisterVariable(&r_subdivisions_mintess);
74 Cvar_RegisterVariable(&r_subdivisions_maxtess);
75 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
76 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
77 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
78 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
79 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
80 Cvar_RegisterVariable(&r_trippy);
81 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
82 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
83 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
84 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
85 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
86 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
87 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
88 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
89 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
90 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
91 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
92 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
93 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
94 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
95 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
96 Cvar_RegisterVariable(&mod_collision_bih);
97 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
99 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
100 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
101 mod_q1bsp_texture_solid.surfaceflags = 0;
102 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
104 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
105 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
106 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
107 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
109 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
110 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
111 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
112 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
114 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
115 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
116 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
117 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
119 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
120 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
121 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
122 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
125 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
132 // LordHavoc: modified to start at first clip node,
133 // in other words: first node of the (sub)model
134 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
136 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
138 return (mleaf_t *)node;
141 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
145 leaf = Mod_Q1BSP_PointInLeaf(model, p);
148 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
151 memcpy(out, leaf->ambient_sound_level, i);
157 memset(out, 0, outsize);
160 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
163 int nodestackindex = 0;
164 mnode_t *node, *nodestack[1024];
165 if (!model->brush.num_pvsclusters)
167 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
173 // node - recurse down the BSP tree
174 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
178 return -1; // ERROR: NAN bounding box!
179 // box is on one side of plane, take that path
180 node = node->children[sides-1];
184 // box crosses plane, take one path and remember the other
185 if (nodestackindex < 1024)
186 nodestack[nodestackindex++] = node->children[0];
187 node = node->children[1];
193 // leaf - add clusterindex to list
194 if (numclusters < maxclusters)
195 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
199 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
203 if (nodestackindex < 1024)
204 nodestack[nodestackindex++] = node->children[0];
205 node = node->children[1];
210 // leaf - add clusterindex to list
211 if (numclusters < maxclusters)
212 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
217 // try another path we didn't take earlier
218 if (nodestackindex == 0)
220 node = nodestack[--nodestackindex];
222 // return number of clusters found (even if more than the maxclusters)
226 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
228 int nodestackindex = 0;
229 mnode_t *node, *nodestack[1024];
230 if (!model->brush.num_pvsclusters)
232 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
238 // node - recurse down the BSP tree
239 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
243 return -1; // ERROR: NAN bounding box!
244 // box is on one side of plane, take that path
245 node = node->children[sides-1];
249 // box crosses plane, take one path and remember the other
250 if (nodestackindex < 1024)
251 nodestack[nodestackindex++] = node->children[0];
252 node = node->children[1];
258 // leaf - check cluster bit
259 int clusterindex = ((mleaf_t *)node)->clusterindex;
260 if (CHECKPVSBIT(pvs, clusterindex))
262 // it is visible, return immediately with the news
267 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
271 if (nodestackindex < 1024)
272 nodestack[nodestackindex++] = node->children[0];
273 node = node->children[1];
278 // leaf - check cluster bit
279 int clusterindex = ((mleaf_t *)node)->clusterindex;
280 if (CHECKPVSBIT(pvs, clusterindex))
282 // it is visible, return immediately with the news
288 // nothing to see here, try another path we didn't take earlier
289 if (nodestackindex == 0)
291 node = nodestack[--nodestackindex];
297 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
299 int nodestackindex = 0;
300 mnode_t *node, *nodestack[1024];
301 if (!model->brush.num_leafs)
303 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
309 // node - recurse down the BSP tree
310 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
314 return -1; // ERROR: NAN bounding box!
315 // box is on one side of plane, take that path
316 node = node->children[sides-1];
320 // box crosses plane, take one path and remember the other
321 if (nodestackindex < 1024)
322 nodestack[nodestackindex++] = node->children[0];
323 node = node->children[1];
329 // leaf - check cluster bit
330 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
331 if (CHECKPVSBIT(pvs, clusterindex))
333 // it is visible, return immediately with the news
338 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
342 if (nodestackindex < 1024)
343 nodestack[nodestackindex++] = node->children[0];
344 node = node->children[1];
349 // leaf - check cluster bit
350 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
351 if (CHECKPVSBIT(pvs, clusterindex))
353 // it is visible, return immediately with the news
359 // nothing to see here, try another path we didn't take earlier
360 if (nodestackindex == 0)
362 node = nodestack[--nodestackindex];
368 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
370 int nodestackindex = 0;
371 mnode_t *node, *nodestack[1024];
372 if (!model->brush.num_leafs)
374 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
380 // node - recurse down the BSP tree
381 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
385 return -1; // ERROR: NAN bounding box!
386 // box is on one side of plane, take that path
387 node = node->children[sides-1];
391 // box crosses plane, take one path and remember the other
392 if (nodestackindex < 1024)
393 nodestack[nodestackindex++] = node->children[0];
394 node = node->children[1];
400 // leaf - check if it is visible
401 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
403 // it is visible, return immediately with the news
408 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
412 if (nodestackindex < 1024)
413 nodestack[nodestackindex++] = node->children[0];
414 node = node->children[1];
419 // leaf - check if it is visible
420 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
422 // it is visible, return immediately with the news
428 // nothing to see here, try another path we didn't take earlier
429 if (nodestackindex == 0)
431 node = nodestack[--nodestackindex];
437 typedef struct findnonsolidlocationinfo_s
440 vec3_t absmin, absmax;
446 findnonsolidlocationinfo_t;
448 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
451 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
453 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
454 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
455 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
456 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
457 VectorSubtract(vert[1], vert[0], edge[0]);
458 VectorSubtract(vert[2], vert[1], edge[1]);
459 CrossProduct(edge[1], edge[0], facenormal);
460 if (facenormal[0] || facenormal[1] || facenormal[2])
462 VectorNormalize(facenormal);
463 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
464 if (f <= info->bestdist && f >= -info->bestdist)
466 VectorSubtract(vert[0], vert[2], edge[2]);
467 VectorNormalize(edge[0]);
468 VectorNormalize(edge[1]);
469 VectorNormalize(edge[2]);
470 CrossProduct(facenormal, edge[0], edgenormal[0]);
471 CrossProduct(facenormal, edge[1], edgenormal[1]);
472 CrossProduct(facenormal, edge[2], edgenormal[2]);
474 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
475 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
476 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
478 // we got lucky, the center is within the face
479 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
483 if (info->bestdist > dist)
485 info->bestdist = dist;
486 VectorScale(facenormal, (info->radius - -dist), info->nudge);
491 if (info->bestdist > dist)
493 info->bestdist = dist;
494 VectorScale(facenormal, (info->radius - dist), info->nudge);
500 // check which edge or vertex the center is nearest
501 for (i = 0;i < 3;i++)
503 f = DotProduct(info->center, edge[i]);
504 if (f >= DotProduct(vert[0], edge[i])
505 && f <= DotProduct(vert[1], edge[i]))
508 VectorMA(info->center, -f, edge[i], point);
509 dist = sqrt(DotProduct(point, point));
510 if (info->bestdist > dist)
512 info->bestdist = dist;
513 VectorScale(point, (info->radius / dist), info->nudge);
515 // skip both vertex checks
516 // (both are further away than this edge)
521 // not on edge, check first vertex of edge
522 VectorSubtract(info->center, vert[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);
536 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
538 int surfacenum, k, *mark;
540 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
542 surface = info->model->data_surfaces + *mark;
543 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
545 if(surface->deprecatedq3num_bboxstride > 0)
548 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
549 for(i = 0; i < cnt; ++i)
551 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
553 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
555 tri = i * surface->deprecatedq3num_bboxstride + k;
556 if(tri >= surface->num_triangles)
558 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
565 for (k = 0;k < surface->num_triangles;k++)
567 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
574 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
578 float f = PlaneDiff(info->center, node->plane);
579 if (f >= -info->bestdist)
580 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
581 if (f <= info->bestdist)
582 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
586 if (((mleaf_t *)node)->numleafsurfaces)
587 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
591 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
594 findnonsolidlocationinfo_t info;
600 VectorCopy(in, info.center);
601 info.radius = radius;
606 VectorClear(info.nudge);
607 info.bestdist = radius;
608 VectorCopy(info.center, info.absmin);
609 VectorCopy(info.center, info.absmax);
610 info.absmin[0] -= info.radius + 1;
611 info.absmin[1] -= info.radius + 1;
612 info.absmin[2] -= info.radius + 1;
613 info.absmax[0] += info.radius + 1;
614 info.absmax[1] += info.radius + 1;
615 info.absmax[2] += info.radius + 1;
616 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
617 VectorAdd(info.center, info.nudge, info.center);
619 while (info.bestdist < radius && ++i < 10);
620 VectorCopy(info.center, out);
623 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
625 switch(nativecontents)
630 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
632 return SUPERCONTENTS_WATER;
634 return SUPERCONTENTS_SLIME;
636 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
638 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
643 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
645 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
646 return CONTENTS_SOLID;
647 if (supercontents & SUPERCONTENTS_SKY)
649 if (supercontents & SUPERCONTENTS_LAVA)
650 return CONTENTS_LAVA;
651 if (supercontents & SUPERCONTENTS_SLIME)
652 return CONTENTS_SLIME;
653 if (supercontents & SUPERCONTENTS_WATER)
654 return CONTENTS_WATER;
655 return CONTENTS_EMPTY;
658 typedef struct RecursiveHullCheckTraceInfo_s
660 // the hull we're tracing through
663 // the trace structure to fill in
666 // start, end, and end - start (in model space)
671 RecursiveHullCheckTraceInfo_t;
673 // 1/32 epsilon to keep floating point happy
674 #define DIST_EPSILON (0.03125)
676 #define HULLCHECKSTATE_EMPTY 0
677 #define HULLCHECKSTATE_SOLID 1
678 #define HULLCHECKSTATE_DONE 2
680 extern cvar_t collision_prefernudgedfraction;
681 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
683 // status variables, these don't need to be saved on the stack when
684 // recursing... but are because this should be thread-safe
685 // (note: tracing against a bbox is not thread-safe, yet)
690 // variables that need to be stored on the stack when recursing
695 // LordHavoc: a goto! everyone flee in terror... :)
700 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
701 if (!t->trace->startfound)
703 t->trace->startfound = true;
704 t->trace->startsupercontents |= num;
706 if (num & SUPERCONTENTS_LIQUIDSMASK)
707 t->trace->inwater = true;
709 t->trace->inopen = true;
710 if (num & SUPERCONTENTS_SOLID)
711 t->trace->hittexture = &mod_q1bsp_texture_solid;
712 else if (num & SUPERCONTENTS_SKY)
713 t->trace->hittexture = &mod_q1bsp_texture_sky;
714 else if (num & SUPERCONTENTS_LAVA)
715 t->trace->hittexture = &mod_q1bsp_texture_lava;
716 else if (num & SUPERCONTENTS_SLIME)
717 t->trace->hittexture = &mod_q1bsp_texture_slime;
719 t->trace->hittexture = &mod_q1bsp_texture_water;
720 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
721 t->trace->hitsupercontents = num;
722 if (num & t->trace->hitsupercontentsmask)
724 // if the first leaf is solid, set startsolid
725 if (t->trace->allsolid)
726 t->trace->startsolid = true;
727 #if COLLISIONPARANOID >= 3
730 return HULLCHECKSTATE_SOLID;
734 t->trace->allsolid = false;
735 #if COLLISIONPARANOID >= 3
738 return HULLCHECKSTATE_EMPTY;
742 // find the point distances
743 node = t->hull->clipnodes + num;
745 plane = t->hull->planes + node->planenum;
748 t1 = p1[plane->type] - plane->dist;
749 t2 = p2[plane->type] - plane->dist;
753 t1 = DotProduct (plane->normal, p1) - plane->dist;
754 t2 = DotProduct (plane->normal, p2) - plane->dist;
761 #if COLLISIONPARANOID >= 3
764 num = node->children[1];
773 #if COLLISIONPARANOID >= 3
776 num = node->children[0];
782 // the line intersects, find intersection point
783 // LordHavoc: this uses the original trace for maximum accuracy
784 #if COLLISIONPARANOID >= 3
789 t1 = t->start[plane->type] - plane->dist;
790 t2 = t->end[plane->type] - plane->dist;
794 t1 = DotProduct (plane->normal, t->start) - plane->dist;
795 t2 = DotProduct (plane->normal, t->end) - plane->dist;
798 midf = t1 / (t1 - t2);
799 midf = bound(p1f, midf, p2f);
800 VectorMA(t->start, midf, t->dist, mid);
802 // recurse both sides, front side first
803 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
804 // if this side is not empty, return what it is (solid or done)
805 if (ret != HULLCHECKSTATE_EMPTY)
808 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
809 // if other side is not solid, return what it is (empty or done)
810 if (ret != HULLCHECKSTATE_SOLID)
813 // front is air and back is solid, this is the impact point...
816 t->trace->plane.dist = -plane->dist;
817 VectorNegate (plane->normal, t->trace->plane.normal);
821 t->trace->plane.dist = plane->dist;
822 VectorCopy (plane->normal, t->trace->plane.normal);
825 // calculate the true fraction
826 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
827 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
828 midf = t1 / (t1 - t2);
829 t->trace->realfraction = bound(0, midf, 1);
831 // calculate the return fraction which is nudged off the surface a bit
832 midf = (t1 - DIST_EPSILON) / (t1 - t2);
833 t->trace->fraction = bound(0, midf, 1);
835 if (collision_prefernudgedfraction.integer)
836 t->trace->realfraction = t->trace->fraction;
838 #if COLLISIONPARANOID >= 3
841 return HULLCHECKSTATE_DONE;
844 //#if COLLISIONPARANOID < 2
845 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
848 mclipnode_t *nodes = t->hull->clipnodes;
849 mplane_t *planes = t->hull->planes;
851 VectorCopy(t->start, point);
854 plane = planes + nodes[num].planenum;
855 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
857 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
858 t->trace->startsupercontents |= num;
859 if (num & SUPERCONTENTS_LIQUIDSMASK)
860 t->trace->inwater = true;
862 t->trace->inopen = true;
863 if (num & t->trace->hitsupercontentsmask)
865 t->trace->allsolid = t->trace->startsolid = true;
866 return HULLCHECKSTATE_SOLID;
870 t->trace->allsolid = t->trace->startsolid = false;
871 return HULLCHECKSTATE_EMPTY;
876 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)
878 RecursiveHullCheckTraceInfo_t rhc;
880 memset(&rhc, 0, sizeof(rhc));
881 memset(trace, 0, sizeof(trace_t));
883 rhc.trace->fraction = 1;
884 rhc.trace->realfraction = 1;
885 rhc.trace->allsolid = true;
886 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
887 VectorCopy(start, rhc.start);
888 VectorCopy(start, rhc.end);
889 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
892 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)
894 RecursiveHullCheckTraceInfo_t rhc;
896 if (VectorCompare(start, end))
898 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
902 memset(&rhc, 0, sizeof(rhc));
903 memset(trace, 0, sizeof(trace_t));
905 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
906 rhc.trace->fraction = 1;
907 rhc.trace->realfraction = 1;
908 rhc.trace->allsolid = true;
909 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
910 VectorCopy(start, rhc.start);
911 VectorCopy(end, rhc.end);
912 VectorSubtract(rhc.end, rhc.start, rhc.dist);
913 #if COLLISIONPARANOID >= 2
914 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]);
915 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
920 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
921 memset(&testtrace, 0, sizeof(trace_t));
922 rhc.trace = &testtrace;
923 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
924 rhc.trace->fraction = 1;
925 rhc.trace->realfraction = 1;
926 rhc.trace->allsolid = true;
927 VectorCopy(test, rhc.start);
928 VectorCopy(test, rhc.end);
929 VectorClear(rhc.dist);
930 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
931 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
932 if (!trace->startsolid && testtrace.startsolid)
933 Con_Printf(" - ended in solid!\n");
937 if (VectorLength2(rhc.dist))
938 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
940 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
944 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)
946 // this function currently only supports same size start and end
948 RecursiveHullCheckTraceInfo_t rhc;
950 if (VectorCompare(boxmins, boxmaxs))
952 if (VectorCompare(start, end))
953 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
955 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
959 memset(&rhc, 0, sizeof(rhc));
960 memset(trace, 0, sizeof(trace_t));
962 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
963 rhc.trace->fraction = 1;
964 rhc.trace->realfraction = 1;
965 rhc.trace->allsolid = true;
966 VectorSubtract(boxmaxs, boxmins, boxsize);
968 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
969 else if (model->brush.ishlbsp)
971 // LordHavoc: this has to have a minor tolerance (the .1) because of
972 // minor float precision errors from the box being transformed around
973 if (boxsize[0] < 32.1)
975 if (boxsize[2] < 54) // pick the nearest of 36 or 72
976 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
978 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
981 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
985 // LordHavoc: this has to have a minor tolerance (the .1) because of
986 // minor float precision errors from the box being transformed around
987 if (boxsize[0] < 32.1)
988 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
990 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
992 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
993 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
994 VectorSubtract(rhc.end, rhc.start, rhc.dist);
995 #if COLLISIONPARANOID >= 2
996 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]);
997 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1002 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1003 memset(&testtrace, 0, sizeof(trace_t));
1004 rhc.trace = &testtrace;
1005 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1006 rhc.trace->fraction = 1;
1007 rhc.trace->realfraction = 1;
1008 rhc.trace->allsolid = true;
1009 VectorCopy(test, rhc.start);
1010 VectorCopy(test, rhc.end);
1011 VectorClear(rhc.dist);
1012 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1013 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1014 if (!trace->startsolid && testtrace.startsolid)
1015 Con_Printf(" - ended in solid!\n");
1019 if (VectorLength2(rhc.dist))
1020 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1022 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1026 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1028 int num = model->brushq1.hulls[0].firstclipnode;
1030 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1031 mplane_t *planes = model->brushq1.hulls[0].planes;
1034 plane = planes + nodes[num].planenum;
1035 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1037 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1040 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)
1044 colplanef_t cbox_planes[6];
1046 cbox.hasaabbplanes = true;
1047 cbox.supercontents = boxsupercontents;
1050 cbox.numtriangles = 0;
1051 cbox.planes = cbox_planes;
1053 cbox.elements = NULL;
1061 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];
1062 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];
1063 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];
1064 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];
1065 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];
1066 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];
1067 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1068 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1069 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1070 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1071 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1072 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1073 memset(trace, 0, sizeof(trace_t));
1074 trace->hitsupercontentsmask = hitsupercontentsmask;
1075 trace->fraction = 1;
1076 trace->realfraction = 1;
1077 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1079 RecursiveHullCheckTraceInfo_t rhc;
1080 static hull_t box_hull;
1081 static mclipnode_t box_clipnodes[6];
1082 static mplane_t box_planes[6];
1083 // fill in a default trace
1084 memset(&rhc, 0, sizeof(rhc));
1085 memset(trace, 0, sizeof(trace_t));
1086 //To keep everything totally uniform, bounding boxes are turned into small
1087 //BSP trees instead of being compared directly.
1088 // create a temp hull from bounding box sizes
1089 box_planes[0].dist = cmaxs[0] - mins[0];
1090 box_planes[1].dist = cmins[0] - maxs[0];
1091 box_planes[2].dist = cmaxs[1] - mins[1];
1092 box_planes[3].dist = cmins[1] - maxs[1];
1093 box_planes[4].dist = cmaxs[2] - mins[2];
1094 box_planes[5].dist = cmins[2] - maxs[2];
1095 #if COLLISIONPARANOID >= 3
1096 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]);
1099 if (box_hull.clipnodes == NULL)
1103 //Set up the planes and clipnodes so that the six floats of a bounding box
1104 //can just be stored out and get a proper hull_t structure.
1106 box_hull.clipnodes = box_clipnodes;
1107 box_hull.planes = box_planes;
1108 box_hull.firstclipnode = 0;
1109 box_hull.lastclipnode = 5;
1111 for (i = 0;i < 6;i++)
1113 box_clipnodes[i].planenum = i;
1117 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1119 box_clipnodes[i].children[side^1] = i + 1;
1121 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1123 box_planes[i].type = i>>1;
1124 box_planes[i].normal[i>>1] = 1;
1128 // trace a line through the generated clipping hull
1129 //rhc.boxsupercontents = boxsupercontents;
1130 rhc.hull = &box_hull;
1132 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1133 rhc.trace->fraction = 1;
1134 rhc.trace->realfraction = 1;
1135 rhc.trace->allsolid = true;
1136 VectorCopy(start, rhc.start);
1137 VectorCopy(end, rhc.end);
1138 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1139 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1140 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1141 if (rhc.trace->startsupercontents)
1142 rhc.trace->startsupercontents = boxsupercontents;
1146 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)
1148 memset(trace, 0, sizeof(trace_t));
1149 trace->fraction = 1;
1150 trace->realfraction = 1;
1151 if (BoxesOverlap(start, start, cmins, cmaxs))
1153 trace->startsupercontents |= boxsupercontents;
1154 if (hitsupercontentsmask & boxsupercontents)
1156 trace->startsolid = true;
1157 trace->allsolid = true;
1162 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1165 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1166 return trace.fraction == 1;
1169 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)
1173 float mid, distz = endz - startz;
1177 return false; // didn't hit anything
1179 switch (node->plane->type)
1182 node = node->children[x < node->plane->dist];
1185 node = node->children[y < node->plane->dist];
1188 side = startz < node->plane->dist;
1189 if ((endz < node->plane->dist) == side)
1191 node = node->children[side];
1194 // found an intersection
1195 mid = node->plane->dist;
1198 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1199 front += startz * node->plane->normal[2];
1200 back += endz * node->plane->normal[2];
1201 side = front < node->plane->dist;
1202 if ((back < node->plane->dist) == side)
1204 node = node->children[side];
1207 // found an intersection
1208 mid = startz + distz * (front - node->plane->dist) / (front - back);
1212 // go down front side
1213 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1214 return true; // hit something
1217 // check for impact on this node
1218 if (node->numsurfaces)
1220 int i, dsi, dti, lmwidth, lmheight;
1222 msurface_t *surface;
1223 unsigned char *lightmap;
1224 int maps, line3, size3;
1227 float scale, w, w00, w01, w10, w11;
1229 surface = model->data_surfaces + node->firstsurface;
1230 for (i = 0;i < node->numsurfaces;i++, surface++)
1232 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1233 continue; // no lightmaps
1235 // location we want to sample in the lightmap
1236 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;
1237 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;
1242 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1243 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1246 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1248 // calculate bilinear interpolation factors
1249 // and also multiply by fixedpoint conversion factors
1252 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1253 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1254 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1255 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1257 // values for pointer math
1258 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1259 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1261 // look up the pixel
1262 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1264 // bilinear filter each lightmap style, and sum them
1265 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1267 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1268 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1269 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1270 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1271 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1275 return true; // success
1280 // go down back side
1281 node = node->children[side ^ 1];
1283 distz = endz - startz;
1288 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1290 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1291 VectorSet(diffusenormal, 0, 0, 1);
1293 if (!model->brushq1.lightdata)
1295 VectorSet(ambientcolor, 1, 1, 1);
1296 VectorSet(diffusecolor, 0, 0, 0);
1300 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);
1303 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1308 const msurface_t *surface;
1313 float edgenormal[3];
1320 surface = model->data_surfaces + node->firstsurface;
1321 for (i = 0;i < node->numsurfaces;i++, surface++)
1323 // skip surfaces whose bounding box does not include the point
1324 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1326 // skip faces with contents we don't care about
1327 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1329 // get the surface normal - since it is flat we know any vertex normal will suffice
1330 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1332 if (DotProduct(t->dist, normal) > 0)
1334 // iterate edges and see if the point is outside one of them
1335 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1337 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1338 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1339 VectorSubtract(v0, v1, edgedir);
1340 CrossProduct(edgedir, normal, edgenormal);
1341 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1344 // if the point is outside one of the edges, it is not within the surface
1345 if (j < surface->num_vertices)
1348 // we hit a surface, this is the impact point...
1349 VectorCopy(normal, t->trace->plane.normal);
1350 t->trace->plane.dist = DotProduct(normal, p);
1352 // calculate the true fraction
1353 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1354 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1355 midf = t1 / (t1 - t2);
1356 t->trace->realfraction = midf;
1358 // calculate the return fraction which is nudged off the surface a bit
1359 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1360 t->trace->fraction = bound(0, midf, 1);
1362 if (collision_prefernudgedfraction.integer)
1363 t->trace->realfraction = t->trace->fraction;
1365 t->trace->hittexture = surface->texture->currentframe;
1366 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1367 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1368 return surface->texture->currentframe;
1373 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])
1375 const mplane_t *plane;
1378 double midf, mid[3];
1379 const mleaf_t *leaf;
1383 plane = node->plane;
1384 if (plane->type < 3)
1386 t1 = p1[plane->type] - plane->dist;
1387 t2 = p2[plane->type] - plane->dist;
1391 t1 = DotProduct (plane->normal, p1) - plane->dist;
1392 t2 = DotProduct (plane->normal, p2) - plane->dist;
1398 node = node->children[1];
1407 node = node->children[0];
1413 // the line intersects, find intersection point
1414 // LordHavoc: this uses the original trace for maximum accuracy
1415 if (plane->type < 3)
1417 t1 = t->start[plane->type] - plane->dist;
1418 t2 = t->end[plane->type] - plane->dist;
1422 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1423 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1426 midf = t1 / (t1 - t2);
1427 VectorMA(t->start, midf, t->dist, mid);
1429 // recurse both sides, front side first, return if we hit a surface
1430 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1431 return HULLCHECKSTATE_DONE;
1433 // test each surface on the node
1434 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1435 if (t->trace->hittexture)
1436 return HULLCHECKSTATE_DONE;
1438 // recurse back side
1439 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1441 leaf = (const mleaf_t *)node;
1442 side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1443 if (!t->trace->startfound)
1445 t->trace->startfound = true;
1446 t->trace->startsupercontents |= side;
1448 if (side & SUPERCONTENTS_LIQUIDSMASK)
1449 t->trace->inwater = true;
1451 t->trace->inopen = true;
1452 if (side & t->trace->hitsupercontentsmask)
1454 // if the first leaf is solid, set startsolid
1455 if (t->trace->allsolid)
1456 t->trace->startsolid = true;
1457 return HULLCHECKSTATE_SOLID;
1461 t->trace->allsolid = false;
1462 return HULLCHECKSTATE_EMPTY;
1466 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)
1468 RecursiveHullCheckTraceInfo_t rhc;
1470 memset(&rhc, 0, sizeof(rhc));
1471 memset(trace, 0, sizeof(trace_t));
1473 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1474 rhc.trace->fraction = 1;
1475 rhc.trace->realfraction = 1;
1476 rhc.trace->allsolid = true;
1477 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1478 VectorCopy(start, rhc.start);
1479 VectorCopy(end, rhc.end);
1480 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1481 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1482 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1485 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1488 unsigned char *outstart = out;
1489 while (out < outend)
1493 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));
1503 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));
1506 for (c = *in++;c > 0;c--)
1510 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));
1521 R_Q1BSP_LoadSplitSky
1523 A sky texture is 256*128, with the right side being a masked overlay
1526 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1531 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1532 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1534 // allocate a texture pool if we need it
1535 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1536 loadmodel->texturepool = R_AllocTexturePool();
1538 if (bytesperpixel == 4)
1540 for (y = 0;y < h;y++)
1542 for (x = 0;x < w;x++)
1544 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1545 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1551 // make an average value for the back to avoid
1552 // a fringe on the top level
1561 for (y = 0;y < h;y++)
1563 for (x = 0;x < w;x++)
1565 p = src[x*width+y+w];
1566 r += palette_rgb[p][0];
1567 g += palette_rgb[p][1];
1568 b += palette_rgb[p][2];
1571 bgra.b[2] = r/(w*h);
1572 bgra.b[1] = g/(w*h);
1573 bgra.b[0] = b/(w*h);
1575 for (y = 0;y < h;y++)
1577 for (x = 0;x < w;x++)
1579 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1581 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1586 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1587 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1588 Mem_Free(solidpixels);
1589 Mem_Free(alphapixels);
1592 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1594 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1595 skinframe_t *skinframe;
1597 texture_t *tx, *tx2, *anims[10], *altanims[10];
1598 texture_t backuptex;
1600 unsigned char *data, *mtdata;
1602 char mapname[MAX_QPATH], name[MAX_QPATH];
1603 unsigned char zeroopaque[4], zerotrans[4];
1604 Vector4Set(zeroopaque, 0, 0, 0, 255);
1605 Vector4Set(zerotrans, 0, 0, 0, 128);
1607 loadmodel->data_textures = NULL;
1609 // add two slots for notexture walls and notexture liquids
1612 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1613 m->nummiptex = LittleLong (m->nummiptex);
1614 loadmodel->num_textures = m->nummiptex + 2;
1615 loadmodel->num_texturesperskin = loadmodel->num_textures;
1620 loadmodel->num_textures = 2;
1621 loadmodel->num_texturesperskin = loadmodel->num_textures;
1624 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1626 // fill out all slots with notexture
1627 if (cls.state != ca_dedicated)
1628 skinframe = R_SkinFrame_LoadMissing();
1631 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1633 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1636 if (cls.state != ca_dedicated)
1638 tx->numskinframes = 1;
1639 tx->skinframerate = 1;
1640 tx->skinframes[0] = skinframe;
1641 tx->currentskinframe = tx->skinframes[0];
1643 tx->basematerialflags = MATERIALFLAG_WALL;
1644 if (i == loadmodel->num_textures - 1)
1646 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1647 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1648 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1652 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1653 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1655 tx->currentframe = tx;
1657 // clear water settings
1660 tx->refractfactor = 1;
1661 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1662 tx->reflectfactor = 1;
1663 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1664 tx->r_water_wateralpha = 1;
1665 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1666 tx->offsetscale = 1;
1668 tx->specularscalemod = 1;
1669 tx->specularpowermod = 1;
1674 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1678 s = loadmodel->name;
1679 if (!strncasecmp(s, "maps/", 5))
1681 FS_StripExtension(s, mapname, sizeof(mapname));
1683 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1685 // LordHavoc: mostly rewritten map texture loader
1686 for (i = 0;i < m->nummiptex;i++)
1688 dofs[i] = LittleLong(dofs[i]);
1689 if (r_nosurftextures.integer)
1693 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1696 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1698 // copy name, but only up to 16 characters
1699 // (the output buffer can hold more than this, but the input buffer is
1701 for (j = 0;j < 16 && dmiptex->name[j];j++)
1702 name[j] = dmiptex->name[j];
1707 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1708 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1711 mtwidth = LittleLong(dmiptex->width);
1712 mtheight = LittleLong(dmiptex->height);
1714 j = LittleLong(dmiptex->offsets[0]);
1718 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1720 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1723 mtdata = (unsigned char *)dmiptex + j;
1726 if ((mtwidth & 15) || (mtheight & 15))
1727 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1729 // LordHavoc: force all names to lowercase
1730 for (j = 0;name[j];j++)
1731 if (name[j] >= 'A' && name[j] <= 'Z')
1732 name[j] += 'a' - 'A';
1734 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1735 backuptex = loadmodel->data_textures[i];
1736 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1738 loadmodel->data_textures[i] = backuptex;
1740 tx = loadmodel->data_textures + i;
1741 strlcpy(tx->name, name, sizeof(tx->name));
1742 tx->width = mtwidth;
1743 tx->height = mtheight;
1745 if (tx->name[0] == '*')
1747 if (!strncmp(tx->name, "*lava", 5))
1749 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1750 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1752 else if (!strncmp(tx->name, "*slime", 6))
1754 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1755 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1759 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1760 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1763 else if (!strncmp(tx->name, "sky", 3))
1765 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1766 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1770 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1771 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1774 if (cls.state != ca_dedicated)
1776 // LordHavoc: HL sky textures are entirely different than quake
1777 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1779 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1781 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, false, NULL);
1782 if (data && image_width == image_height * 2)
1784 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1787 else if (mtdata != NULL)
1788 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1792 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1794 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1796 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1799 // did not find external texture, load it from the bsp or wad3
1800 if (loadmodel->brush.ishlbsp)
1802 // internal texture overrides wad
1803 unsigned char *pixels, *freepixels;
1804 pixels = freepixels = NULL;
1806 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1808 pixels = freepixels = W_GetTextureBGRA(tx->name);
1811 tx->width = image_width;
1812 tx->height = image_height;
1813 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1816 Mem_Free(freepixels);
1818 else if (mtdata) // texture included
1819 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1821 // if skinframe is still NULL the "missing" texture will be used
1823 tx->skinframes[0] = skinframe;
1825 // LordHavoc: some Tenebrae textures get replaced by black
1826 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1827 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1828 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1829 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1832 tx->basematerialflags = MATERIALFLAG_WALL;
1833 if (tx->name[0] == '*')
1835 // LordHavoc: some turbulent textures should not be affected by wateralpha
1836 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1837 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1838 else if (!strncmp(tx->name,"*lava",5)
1839 || !strncmp(tx->name,"*teleport",9)
1840 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1841 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1843 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1844 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1845 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1847 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1849 // replace the texture with black
1850 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1852 else if (!strncmp(tx->name, "sky", 3))
1853 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1854 else if (!strcmp(tx->name, "caulk"))
1855 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1856 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1857 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1859 // start out with no animation
1860 tx->currentframe = tx;
1861 tx->currentskinframe = tx->skinframes[0];
1862 tx->currentmaterialflags = tx->basematerialflags;
1865 // sequence the animations
1866 for (i = 0;i < m->nummiptex;i++)
1868 tx = loadmodel->data_textures + i;
1869 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1871 if (tx->anim_total[0] || tx->anim_total[1])
1872 continue; // already sequenced
1874 // find the number of frames in the animation
1875 memset(anims, 0, sizeof(anims));
1876 memset(altanims, 0, sizeof(altanims));
1878 for (j = i;j < m->nummiptex;j++)
1880 tx2 = loadmodel->data_textures + j;
1881 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1885 if (num >= '0' && num <= '9')
1886 anims[num - '0'] = tx2;
1887 else if (num >= 'a' && num <= 'j')
1888 altanims[num - 'a'] = tx2;
1890 Con_Printf("Bad animating texture %s\n", tx->name);
1894 for (j = 0;j < 10;j++)
1901 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1904 for (j = 0;j < max;j++)
1908 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1912 for (j = 0;j < altmax;j++)
1916 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1925 // if there is no alternate animation, duplicate the primary
1926 // animation into the alternate
1928 for (k = 0;k < 10;k++)
1929 altanims[k] = anims[k];
1932 // link together the primary animation
1933 for (j = 0;j < max;j++)
1936 tx2->animated = true;
1937 tx2->anim_total[0] = max;
1938 tx2->anim_total[1] = altmax;
1939 for (k = 0;k < 10;k++)
1941 tx2->anim_frames[0][k] = anims[k];
1942 tx2->anim_frames[1][k] = altanims[k];
1946 // if there really is an alternate anim...
1947 if (anims[0] != altanims[0])
1949 // link together the alternate animation
1950 for (j = 0;j < altmax;j++)
1953 tx2->animated = true;
1954 // the primary/alternate are reversed here
1955 tx2->anim_total[0] = altmax;
1956 tx2->anim_total[1] = max;
1957 for (k = 0;k < 10;k++)
1959 tx2->anim_frames[0][k] = altanims[k];
1960 tx2->anim_frames[1][k] = anims[k];
1967 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1970 unsigned char *in, *out, *data, d;
1971 char litfilename[MAX_QPATH];
1972 char dlitfilename[MAX_QPATH];
1973 fs_offset_t filesize;
1974 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1976 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1977 for (i=0; i<l->filelen; i++)
1978 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1980 else // LordHavoc: bsp version 29 (normal white lighting)
1982 // LordHavoc: hope is not lost yet, check for a .lit file to load
1983 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1984 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1985 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1986 strlcat (litfilename, ".lit", sizeof (litfilename));
1987 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1988 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1991 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1993 i = LittleLong(((int *)data)[1]);
1996 if (developer_loading.integer)
1997 Con_Printf("loaded %s\n", litfilename);
1998 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1999 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2001 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2004 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2006 i = LittleLong(((int *)data)[1]);
2009 if (developer_loading.integer)
2010 Con_Printf("loaded %s\n", dlitfilename);
2011 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2012 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2013 loadmodel->brushq3.deluxemapping_modelspace = false;
2014 loadmodel->brushq3.deluxemapping = true;
2023 Con_Printf("Unknown .lit file version (%d)\n", i);
2025 else if (filesize == 8)
2026 Con_Print("Empty .lit file, ignoring\n");
2028 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
2035 // LordHavoc: oh well, expand the white lighting data
2038 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
2039 in = mod_base + l->fileofs;
2040 out = loadmodel->brushq1.lightdata;
2041 for (i = 0;i < l->filelen;i++)
2051 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
2053 loadmodel->brushq1.num_compressedpvs = 0;
2054 loadmodel->brushq1.data_compressedpvs = NULL;
2057 loadmodel->brushq1.num_compressedpvs = l->filelen;
2058 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
2059 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
2062 // used only for HalfLife maps
2063 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2065 char key[128], value[4096];
2069 if (!COM_ParseToken_Simple(&data, false, false))
2071 if (com_token[0] != '{')
2075 if (!COM_ParseToken_Simple(&data, false, false))
2077 if (com_token[0] == '}')
2078 break; // end of worldspawn
2079 if (com_token[0] == '_')
2080 strlcpy(key, com_token + 1, sizeof(key));
2082 strlcpy(key, com_token, sizeof(key));
2083 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2084 key[strlen(key)-1] = 0;
2085 if (!COM_ParseToken_Simple(&data, false, false))
2087 dpsnprintf(value, sizeof(value), "%s", com_token);
2088 if (!strcmp("wad", key)) // for HalfLife maps
2090 if (loadmodel->brush.ishlbsp)
2093 for (i = 0;i < (int)sizeof(value);i++)
2094 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2098 for (;i < (int)sizeof(value);i++)
2100 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2101 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2103 else if (value[i] == ';' || value[i] == 0)
2107 W_LoadTextureWadFile(&value[j], false);
2119 static void Mod_Q1BSP_LoadEntities(lump_t *l)
2121 loadmodel->brush.entities = NULL;
2124 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
2125 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
2126 loadmodel->brush.entities[l->filelen] = 0;
2127 if (loadmodel->brush.ishlbsp)
2128 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2132 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
2138 in = (dvertex_t *)(mod_base + l->fileofs);
2139 if (l->filelen % sizeof(*in))
2140 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2141 count = l->filelen / sizeof(*in);
2142 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2144 loadmodel->brushq1.vertexes = out;
2145 loadmodel->brushq1.numvertexes = count;
2147 for ( i=0 ; i<count ; i++, in++, out++)
2149 out->position[0] = LittleFloat(in->point[0]);
2150 out->position[1] = LittleFloat(in->point[1]);
2151 out->position[2] = LittleFloat(in->point[2]);
2155 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
2156 // can be used for this
2158 int SB_ReadInt (unsigned char **buffer)
2161 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
2167 float SB_ReadFloat (unsigned char **buffer)
2175 u.i = SB_ReadInt (buffer);
2179 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
2181 unsigned char *index;
2185 index = (unsigned char *)(mod_base + l->fileofs);
2186 if (l->filelen % (48+4*hullinfo->filehulls))
2187 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2189 count = l->filelen / (48+4*hullinfo->filehulls);
2190 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2192 loadmodel->brushq1.submodels = out;
2193 loadmodel->brush.numsubmodels = count;
2195 for (i = 0; i < count; i++, out++)
2197 // spread out the mins / maxs by a pixel
2198 out->mins[0] = SB_ReadFloat (&index) - 1;
2199 out->mins[1] = SB_ReadFloat (&index) - 1;
2200 out->mins[2] = SB_ReadFloat (&index) - 1;
2201 out->maxs[0] = SB_ReadFloat (&index) + 1;
2202 out->maxs[1] = SB_ReadFloat (&index) + 1;
2203 out->maxs[2] = SB_ReadFloat (&index) + 1;
2204 out->origin[0] = SB_ReadFloat (&index);
2205 out->origin[1] = SB_ReadFloat (&index);
2206 out->origin[2] = SB_ReadFloat (&index);
2207 for (j = 0; j < hullinfo->filehulls; j++)
2208 out->headnode[j] = SB_ReadInt (&index);
2209 out->visleafs = SB_ReadInt (&index);
2210 out->firstface = SB_ReadInt (&index);
2211 out->numfaces = SB_ReadInt (&index);
2215 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2221 in = (dedge_t *)(mod_base + l->fileofs);
2222 if (l->filelen % sizeof(*in))
2223 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2224 count = l->filelen / sizeof(*in);
2225 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2227 loadmodel->brushq1.edges = out;
2228 loadmodel->brushq1.numedges = count;
2230 for ( i=0 ; i<count ; i++, in++, out++)
2232 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2233 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2234 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2236 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);
2237 if(!loadmodel->brushq1.numvertexes)
2238 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2246 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2250 int i, j, k, count, miptex;
2252 in = (texinfo_t *)(mod_base + l->fileofs);
2253 if (l->filelen % sizeof(*in))
2254 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2255 count = l->filelen / sizeof(*in);
2256 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2258 loadmodel->brushq1.texinfo = out;
2259 loadmodel->brushq1.numtexinfo = count;
2261 for (i = 0;i < count;i++, in++, out++)
2263 for (k = 0;k < 2;k++)
2264 for (j = 0;j < 4;j++)
2265 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2267 miptex = LittleLong(in->miptex);
2268 out->flags = LittleLong(in->flags);
2270 out->texture = NULL;
2271 if (loadmodel->data_textures)
2273 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2274 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2276 out->texture = loadmodel->data_textures + miptex;
2278 if (out->flags & TEX_SPECIAL)
2280 // if texture chosen is NULL or the shader needs a lightmap,
2281 // force to notexture water shader
2282 if (out->texture == NULL)
2283 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2287 // if texture chosen is NULL, force to notexture
2288 if (out->texture == NULL)
2289 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2295 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2300 mins[0] = mins[1] = mins[2] = 9999;
2301 maxs[0] = maxs[1] = maxs[2] = -9999;
2303 for (i = 0;i < numverts;i++)
2305 for (j = 0;j < 3;j++, v++)
2315 #define MAX_SUBDIVPOLYTRIANGLES 4096
2316 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2318 static int subdivpolyverts, subdivpolytriangles;
2319 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2320 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2322 static int subdivpolylookupvert(vec3_t v)
2325 for (i = 0;i < subdivpolyverts;i++)
2326 if (subdivpolyvert[i][0] == v[0]
2327 && subdivpolyvert[i][1] == v[1]
2328 && subdivpolyvert[i][2] == v[2])
2330 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2331 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2332 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2333 return subdivpolyverts++;
2336 static void SubdividePolygon(int numverts, float *verts)
2338 int i, i1, i2, i3, f, b, c, p;
2339 vec3_t mins, maxs, front[256], back[256];
2340 float m, *pv, *cv, dist[256], frac;
2343 Host_Error("SubdividePolygon: ran out of verts in buffer");
2345 BoundPoly(numverts, verts, mins, maxs);
2347 for (i = 0;i < 3;i++)
2349 m = (mins[i] + maxs[i]) * 0.5;
2350 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2351 if (maxs[i] - m < 8)
2353 if (m - mins[i] < 8)
2357 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2358 dist[c] = cv[i] - m;
2361 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2365 VectorCopy(pv, front[f]);
2370 VectorCopy(pv, back[b]);
2373 if (dist[p] == 0 || dist[c] == 0)
2375 if ((dist[p] > 0) != (dist[c] > 0) )
2378 frac = dist[p] / (dist[p] - dist[c]);
2379 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2380 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2381 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2387 SubdividePolygon(f, front[0]);
2388 SubdividePolygon(b, back[0]);
2392 i1 = subdivpolylookupvert(verts);
2393 i2 = subdivpolylookupvert(verts + 3);
2394 for (i = 2;i < numverts;i++)
2396 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2398 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2402 i3 = subdivpolylookupvert(verts + i * 3);
2403 subdivpolyindex[subdivpolytriangles][0] = i1;
2404 subdivpolyindex[subdivpolytriangles][1] = i2;
2405 subdivpolyindex[subdivpolytriangles][2] = i3;
2407 subdivpolytriangles++;
2411 //Breaks a polygon up along axial 64 unit
2412 //boundaries so that turbulent and sky warps
2413 //can be done reasonably.
2414 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2420 subdivpolytriangles = 0;
2421 subdivpolyverts = 0;
2422 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2423 if (subdivpolytriangles < 1)
2424 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2426 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2427 mesh->num_vertices = subdivpolyverts;
2428 mesh->num_triangles = subdivpolytriangles;
2429 mesh->vertex = (surfvertex_t *)(mesh + 1);
2430 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2431 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2433 for (i = 0;i < mesh->num_triangles;i++)
2434 for (j = 0;j < 3;j++)
2435 mesh->index[i*3+j] = subdivpolyindex[i][j];
2437 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2439 VectorCopy(subdivpolyvert[i], v->v);
2440 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2441 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2446 extern cvar_t gl_max_lightmapsize;
2447 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2450 msurface_t *surface;
2451 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2452 float texmins[2], texmaxs[2], val;
2453 rtexture_t *lightmaptexture, *deluxemaptexture;
2455 in = (dface_t *)(mod_base + l->fileofs);
2456 if (l->filelen % sizeof(*in))
2457 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2458 count = l->filelen / sizeof(*in);
2459 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2460 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2462 loadmodel->num_surfaces = count;
2464 loadmodel->brushq1.firstrender = true;
2465 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2469 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2471 numedges = (unsigned short)LittleShort(in->numedges);
2472 totalverts += numedges;
2473 totaltris += numedges - 2;
2476 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2478 lightmaptexture = NULL;
2479 deluxemaptexture = r_texture_blanknormalmap;
2481 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2482 totallightmapsamples = 0;
2486 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2488 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2490 // FIXME: validate edges, texinfo, etc?
2491 firstedge = LittleLong(in->firstedge);
2492 numedges = (unsigned short)LittleShort(in->numedges);
2493 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)
2494 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2495 i = (unsigned short)LittleShort(in->texinfo);
2496 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2497 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2498 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2499 surface->texture = surface->lightmapinfo->texinfo->texture;
2501 planenum = (unsigned short)LittleShort(in->planenum);
2502 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2503 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2505 //surface->flags = surface->texture->flags;
2506 //if (LittleShort(in->side))
2507 // surface->flags |= SURF_PLANEBACK;
2508 //surface->plane = loadmodel->brush.data_planes + planenum;
2510 surface->num_firstvertex = totalverts;
2511 surface->num_vertices = numedges;
2512 surface->num_firsttriangle = totaltris;
2513 surface->num_triangles = numedges - 2;
2514 totalverts += numedges;
2515 totaltris += numedges - 2;
2517 // convert edges back to a normal polygon
2518 for (i = 0;i < surface->num_vertices;i++)
2520 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2522 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2524 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2526 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2527 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2528 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2529 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2530 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2531 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2532 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2533 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2536 for (i = 0;i < surface->num_triangles;i++)
2538 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2539 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2540 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2543 // compile additional data about the surface geometry
2544 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);
2545 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);
2546 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2548 // generate surface extents information
2549 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2550 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2551 for (i = 1;i < surface->num_vertices;i++)
2553 for (j = 0;j < 2;j++)
2555 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2556 texmins[j] = min(texmins[j], val);
2557 texmaxs[j] = max(texmaxs[j], val);
2560 for (i = 0;i < 2;i++)
2562 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2563 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2566 smax = surface->lightmapinfo->extents[0] >> 4;
2567 tmax = surface->lightmapinfo->extents[1] >> 4;
2568 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2569 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2572 for (i = 0;i < MAXLIGHTMAPS;i++)
2573 surface->lightmapinfo->styles[i] = in->styles[i];
2574 surface->lightmaptexture = NULL;
2575 surface->deluxemaptexture = r_texture_blanknormalmap;
2576 i = LittleLong(in->lightofs);
2579 surface->lightmapinfo->samples = NULL;
2581 // give non-lightmapped water a 1x white lightmap
2582 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2584 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2585 surface->lightmapinfo->styles[0] = 0;
2586 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2590 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2591 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2592 else // LordHavoc: white lighting (bsp version 29)
2594 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2595 if (loadmodel->brushq1.nmaplightdata)
2596 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2599 // check if we should apply a lightmap to this
2600 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2602 if (ssize > 256 || tsize > 256)
2603 Host_Error("Bad surface extents");
2605 if (lightmapsize < ssize)
2606 lightmapsize = ssize;
2607 if (lightmapsize < tsize)
2608 lightmapsize = tsize;
2610 totallightmapsamples += ssize*tsize;
2612 // force lightmap upload on first time seeing the surface
2614 // additionally this is used by the later code to see if a
2615 // lightmap is needed on this surface (rather than duplicating the
2617 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2618 loadmodel->lit = true;
2622 // small maps (such as ammo boxes especially) don't need big lightmap
2623 // textures, so this code tries to guess a good size based on
2624 // totallightmapsamples (size of the lightmaps lump basically), as well as
2625 // trying to max out the size if there is a lot of lightmap data to store
2626 // additionally, never choose a lightmapsize that is smaller than the
2627 // largest surface encountered (as it would fail)
2629 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2632 // now that we've decided the lightmap texture size, we can do the rest
2633 if (cls.state != ca_dedicated)
2635 int stainmapsize = 0;
2636 mod_alloclightmap_state_t allocState;
2638 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2639 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2641 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2642 float u, v, ubase, vbase, uscale, vscale;
2644 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2647 smax = surface->lightmapinfo->extents[0] >> 4;
2648 tmax = surface->lightmapinfo->extents[1] >> 4;
2649 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2650 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2651 stainmapsize += ssize * tsize * 3;
2653 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2655 // allocate a texture pool if we need it
2656 if (loadmodel->texturepool == NULL)
2657 loadmodel->texturepool = R_AllocTexturePool();
2658 // could not find room, make a new lightmap
2659 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2660 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2661 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2662 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2663 if (loadmodel->brushq1.nmaplightdata)
2664 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2666 Mod_AllocLightmap_Reset(&allocState);
2667 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2669 surface->lightmaptexture = lightmaptexture;
2670 surface->deluxemaptexture = deluxemaptexture;
2671 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2672 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2674 uscale = 1.0f / (float)lightmapsize;
2675 vscale = 1.0f / (float)lightmapsize;
2676 ubase = lightmapx * uscale;
2677 vbase = lightmapy * vscale;
2679 for (i = 0;i < surface->num_vertices;i++)
2681 u = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3]) + 8 - surface->lightmapinfo->texturemins[0]) * (1.0 / 16.0);
2682 v = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3]) + 8 - surface->lightmapinfo->texturemins[1]) * (1.0 / 16.0);
2683 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2684 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2685 // LordHavoc: calc lightmap data offset for vertex lighting to use
2688 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2692 if (cl_stainmaps.integer)
2694 // allocate stainmaps for permanent marks on walls and clear white
2695 unsigned char *stainsamples = NULL;
2696 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2697 memset(stainsamples, 255, stainmapsize);
2699 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2701 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2703 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2704 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2705 surface->lightmapinfo->stainsamples = stainsamples;
2706 stainsamples += ssize * tsize * 3;
2711 // generate ushort elements array if possible
2712 if (loadmodel->surfmesh.data_element3s)
2713 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2714 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2717 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2720 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2721 node->parent = parent;
2724 // this is a node, recurse to children
2725 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2726 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2727 // combine supercontents of children
2728 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2733 mleaf_t *leaf = (mleaf_t *)node;
2734 // if this is a leaf, calculate supercontents mask from all collidable
2735 // primitives in the leaf (brushes and collision surfaces)
2736 // also flag if the leaf contains any collision surfaces
2737 leaf->combinedsupercontents = 0;
2738 // combine the supercontents values of all brushes in this leaf
2739 for (j = 0;j < leaf->numleafbrushes;j++)
2740 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2741 // check if this leaf contains any collision surfaces (q3 patches)
2742 for (j = 0;j < leaf->numleafsurfaces;j++)
2744 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2745 if (surface->num_collisiontriangles)
2747 leaf->containscollisionsurfaces = true;
2748 leaf->combinedsupercontents |= surface->texture->supercontents;
2754 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2760 in = (dnode_t *)(mod_base + l->fileofs);
2761 if (l->filelen % sizeof(*in))
2762 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2763 count = l->filelen / sizeof(*in);
2765 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2766 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2768 loadmodel->brush.data_nodes = out;
2769 loadmodel->brush.num_nodes = count;
2771 for ( i=0 ; i<count ; i++, in++, out++)
2773 for (j=0 ; j<3 ; j++)
2775 out->mins[j] = LittleShort(in->mins[j]);
2776 out->maxs[j] = LittleShort(in->maxs[j]);
2779 p = LittleLong(in->planenum);
2780 out->plane = loadmodel->brush.data_planes + p;
2782 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2783 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2785 for (j=0 ; j<2 ; j++)
2787 // LordHavoc: this code supports broken bsp files produced by
2788 // arguire qbsp which can produce more than 32768 nodes, any value
2789 // below count is assumed to be a node number, any other value is
2790 // assumed to be a leaf number
2791 p = (unsigned short)LittleShort(in->children[j]);
2794 if (p < loadmodel->brush.num_nodes)
2795 out->children[j] = loadmodel->brush.data_nodes + p;
2798 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2799 // map it to the solid leaf
2800 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2805 // note this uses 65535 intentionally, -1 is leaf 0
2807 if (p < loadmodel->brush.num_leafs)
2808 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2811 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2812 // map it to the solid leaf
2813 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2819 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2822 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2828 in = (dleaf_t *)(mod_base + l->fileofs);
2829 if (l->filelen % sizeof(*in))
2830 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2831 count = l->filelen / sizeof(*in);
2832 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2834 loadmodel->brush.data_leafs = out;
2835 loadmodel->brush.num_leafs = count;
2836 // get visleafs from the submodel data
2837 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2838 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2839 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2840 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2842 for ( i=0 ; i<count ; i++, in++, out++)
2844 for (j=0 ; j<3 ; j++)
2846 out->mins[j] = LittleShort(in->mins[j]);
2847 out->maxs[j] = LittleShort(in->maxs[j]);
2850 // FIXME: this function could really benefit from some error checking
2852 out->contents = LittleLong(in->contents);
2854 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2855 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2856 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2858 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", (int)(out->firstleafsurface - loadmodel->brush.data_leafsurfaces), (int)(out->firstleafsurface + out->numleafsurfaces - loadmodel->brush.data_leafsurfaces), 0, loadmodel->brush.num_leafsurfaces);
2859 out->firstleafsurface = NULL;
2860 out->numleafsurfaces = 0;
2863 out->clusterindex = i - 1;
2864 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2865 out->clusterindex = -1;
2867 p = LittleLong(in->visofs);
2868 // ignore visofs errors on leaf 0 (solid)
2869 if (p >= 0 && out->clusterindex >= 0)
2871 if (p >= loadmodel->brushq1.num_compressedpvs)
2872 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2874 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);
2877 for (j = 0;j < 4;j++)
2878 out->ambient_sound_level[j] = in->ambient_level[j];
2880 // FIXME: Insert caustics here
2884 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2888 const unsigned char *pvs;
2889 // if there's no vis data, assume supported (because everything is visible all the time)
2890 if (!loadmodel->brush.data_pvsclusters)
2892 // check all liquid leafs to see if they can see into empty leafs, if any
2893 // can we can assume this map supports r_wateralpha
2894 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2896 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2898 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2899 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2900 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2907 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2914 in = (dclipnode_t *)(mod_base + l->fileofs);
2915 if (l->filelen % sizeof(*in))
2916 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2917 count = l->filelen / sizeof(*in);
2918 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2920 loadmodel->brushq1.clipnodes = out;
2921 loadmodel->brushq1.numclipnodes = count;
2923 for (i = 1; i < MAX_MAP_HULLS; i++)
2925 hull = &loadmodel->brushq1.hulls[i];
2926 hull->clipnodes = out;
2927 hull->firstclipnode = 0;
2928 hull->lastclipnode = count-1;
2929 hull->planes = loadmodel->brush.data_planes;
2930 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2931 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2932 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2933 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2934 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2935 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2936 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2939 for (i=0 ; i<count ; i++, out++, in++)
2941 out->planenum = LittleLong(in->planenum);
2942 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2943 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2944 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2945 if (out->children[0] >= count)
2946 out->children[0] -= 65536;
2947 if (out->children[1] >= count)
2948 out->children[1] -= 65536;
2949 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2950 Host_Error("Corrupt clipping hull(out of range planenum)");
2954 //Duplicate the drawing hull structure as a clipping hull
2955 static void Mod_Q1BSP_MakeHull0(void)
2962 hull = &loadmodel->brushq1.hulls[0];
2964 in = loadmodel->brush.data_nodes;
2965 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2967 hull->clipnodes = out;
2968 hull->firstclipnode = 0;
2969 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2970 hull->planes = loadmodel->brush.data_planes;
2972 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2974 out->planenum = in->plane - loadmodel->brush.data_planes;
2975 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2976 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2980 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2985 in = (short *)(mod_base + l->fileofs);
2986 if (l->filelen % sizeof(*in))
2987 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2988 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2989 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2991 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2993 j = (unsigned short) LittleShort(in[i]);
2994 if (j >= loadmodel->num_surfaces)
2995 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2996 loadmodel->brush.data_leafsurfaces[i] = j;
3000 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
3005 in = (int *)(mod_base + l->fileofs);
3006 if (l->filelen % sizeof(*in))
3007 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3008 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
3009 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3011 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3012 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
3016 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
3022 in = (dplane_t *)(mod_base + l->fileofs);
3023 if (l->filelen % sizeof(*in))
3024 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3026 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
3027 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3029 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
3031 out->normal[0] = LittleFloat(in->normal[0]);
3032 out->normal[1] = LittleFloat(in->normal[1]);
3033 out->normal[2] = LittleFloat(in->normal[2]);
3034 out->dist = LittleFloat(in->dist);
3040 static void Mod_Q1BSP_LoadMapBrushes(void)
3044 int submodel, numbrushes;
3045 qboolean firstbrush;
3046 char *text, *maptext;
3047 char mapfilename[MAX_QPATH];
3048 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3049 strlcat (mapfilename, ".map", sizeof (mapfilename));
3050 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3054 if (!COM_ParseToken_Simple(&data, false, false))
3059 if (!COM_ParseToken_Simple(&data, false, false))
3061 if (com_token[0] != '{')
3067 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3070 if (!COM_ParseToken_Simple(&data, false, false))
3072 if (com_token[0] == '}')
3073 break; // end of entity
3074 if (com_token[0] == '{')
3081 if (submodel > loadmodel->brush.numsubmodels)
3083 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3087 model = loadmodel->brush.submodels[submodel];
3094 if (!COM_ParseToken_Simple(&data, false, false))
3096 if (com_token[0] == '}')
3097 break; // end of brush
3098 // each brush face should be this format:
3099 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3100 // FIXME: support hl .map format
3101 for (pointnum = 0;pointnum < 3;pointnum++)
3103 COM_ParseToken_Simple(&data, false, false);
3104 for (componentnum = 0;componentnum < 3;componentnum++)
3106 COM_ParseToken_Simple(&data, false, false);
3107 point[pointnum][componentnum] = atof(com_token);
3109 COM_ParseToken_Simple(&data, false, false);
3111 COM_ParseToken_Simple(&data, false, false);
3112 strlcpy(facetexture, com_token, sizeof(facetexture));
3113 COM_ParseToken_Simple(&data, false, false);
3114 //scroll_s = atof(com_token);
3115 COM_ParseToken_Simple(&data, false, false);
3116 //scroll_t = atof(com_token);
3117 COM_ParseToken_Simple(&data, false, false);
3118 //rotate = atof(com_token);
3119 COM_ParseToken_Simple(&data, false, false);
3120 //scale_s = atof(com_token);
3121 COM_ParseToken_Simple(&data, false, false);
3122 //scale_t = atof(com_token);
3123 TriangleNormal(point[0], point[1], point[2], planenormal);
3124 VectorNormalizeDouble(planenormal);
3125 planedist = DotProduct(point[0], planenormal);
3126 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3136 #define MAX_PORTALPOINTS 64
3138 typedef struct portal_s
3141 mnode_t *nodes[2]; // [0] = front side of plane
3142 struct portal_s *next[2];
3144 double points[3*MAX_PORTALPOINTS];
3145 struct portal_s *chain; // all portals are linked into a list
3149 static memexpandablearray_t portalarray;
3151 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3153 // process only nodes (leafs already had their box calculated)
3157 // calculate children first
3158 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3159 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3161 // make combined bounding box from children
3162 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3163 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3164 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3165 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3166 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3167 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3170 static void Mod_Q1BSP_FinalizePortals(void)
3172 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3176 mleaf_t *leaf, *endleaf;
3178 // tally up portal and point counts and recalculate bounding boxes for all
3179 // leafs (because qbsp is very sloppy)
3180 leaf = loadmodel->brush.data_leafs;
3181 endleaf = leaf + loadmodel->brush.num_leafs;
3182 if (mod_recalculatenodeboxes.integer)
3184 for (;leaf < endleaf;leaf++)
3186 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
3187 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3192 for (portalindex = 0;portalindex < portalrange;portalindex++)
3194 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3197 // note: this check must match the one below or it will usually corrupt memory
3198 // 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
3199 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3202 numpoints += p->numpoints * 2;
3205 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3206 loadmodel->brush.num_portals = numportals;
3207 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3208 loadmodel->brush.num_portalpoints = numpoints;
3209 // clear all leaf portal chains
3210 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3211 loadmodel->brush.data_leafs[i].portals = NULL;
3212 // process all portals in the global portal chain, while freeing them
3213 portal = loadmodel->brush.data_portals;
3214 point = loadmodel->brush.data_portalpoints;
3215 for (portalindex = 0;portalindex < portalrange;portalindex++)
3217 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3220 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3222 // note: this check must match the one above or it will usually corrupt memory
3223 // 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
3224 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3226 // first make the back to front portal(forward portal)
3227 portal->points = point;
3228 portal->numpoints = p->numpoints;
3229 portal->plane.dist = p->plane.dist;
3230 VectorCopy(p->plane.normal, portal->plane.normal);
3231 portal->here = (mleaf_t *)p->nodes[1];
3232 portal->past = (mleaf_t *)p->nodes[0];
3234 for (j = 0;j < portal->numpoints;j++)
3236 VectorCopy(p->points + j*3, point->position);
3239 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3240 PlaneClassify(&portal->plane);
3242 // link into leaf's portal chain
3243 portal->next = portal->here->portals;
3244 portal->here->portals = portal;
3246 // advance to next portal
3249 // then make the front to back portal(backward portal)
3250 portal->points = point;
3251 portal->numpoints = p->numpoints;
3252 portal->plane.dist = -p->plane.dist;
3253 VectorNegate(p->plane.normal, portal->plane.normal);
3254 portal->here = (mleaf_t *)p->nodes[0];
3255 portal->past = (mleaf_t *)p->nodes[1];
3257 for (j = portal->numpoints - 1;j >= 0;j--)
3259 VectorCopy(p->points + j*3, point->position);
3262 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3263 PlaneClassify(&portal->plane);
3265 // link into leaf's portal chain
3266 portal->next = portal->here->portals;
3267 portal->here->portals = portal;
3269 // advance to next portal
3272 // add the portal's polygon points to the leaf bounding boxes
3273 if (mod_recalculatenodeboxes.integer)
3275 for (i = 0;i < 2;i++)
3277 leaf = (mleaf_t *)p->nodes[i];
3278 for (j = 0;j < p->numpoints;j++)
3280 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3281 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3282 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3283 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3284 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3285 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3291 // now recalculate the node bounding boxes from the leafs
3292 if (mod_recalculatenodeboxes.integer)
3293 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3301 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3304 Host_Error("AddPortalToNodes: NULL front node");
3306 Host_Error("AddPortalToNodes: NULL back node");
3307 if (p->nodes[0] || p->nodes[1])
3308 Host_Error("AddPortalToNodes: already included");
3309 // 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
3311 p->nodes[0] = front;
3312 p->next[0] = (portal_t *)front->portals;
3313 front->portals = (mportal_t *)p;
3316 p->next[1] = (portal_t *)back->portals;
3317 back->portals = (mportal_t *)p;
3322 RemovePortalFromNode
3325 static void RemovePortalFromNodes(portal_t *portal)
3329 void **portalpointer;
3331 for (i = 0;i < 2;i++)
3333 node = portal->nodes[i];
3335 portalpointer = (void **) &node->portals;
3338 t = (portal_t *)*portalpointer;
3340 Host_Error("RemovePortalFromNodes: portal not in leaf");
3344 if (portal->nodes[0] == node)
3346 *portalpointer = portal->next[0];
3347 portal->nodes[0] = NULL;
3349 else if (portal->nodes[1] == node)
3351 *portalpointer = portal->next[1];
3352 portal->nodes[1] = NULL;
3355 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3359 if (t->nodes[0] == node)
3360 portalpointer = (void **) &t->next[0];
3361 else if (t->nodes[1] == node)
3362 portalpointer = (void **) &t->next[1];
3364 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3369 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3370 static double *portalpointsbuffer;
3371 static int portalpointsbufferoffset;
3372 static int portalpointsbuffersize;
3373 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3376 mnode_t *front, *back, *other_node;
3377 mplane_t clipplane, *plane;
3378 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3379 int numfrontpoints, numbackpoints;
3380 double *frontpoints, *backpoints;
3382 // if a leaf, we're done
3386 // get some space for our clipping operations to use
3387 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3389 portalpointsbuffersize = portalpointsbufferoffset * 2;
3390 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3392 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3393 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3394 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3395 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3397 plane = node->plane;
3399 front = node->children[0];
3400 back = node->children[1];
3402 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3404 // create the new portal by generating a polygon for the node plane,
3405 // and clipping it by all of the other portals(which came from nodes above this one)
3406 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3407 nodeportal->plane = *plane;
3409 // 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)
3410 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);
3411 nodeportal->numpoints = 4;
3412 side = 0; // shut up compiler warning
3413 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3415 clipplane = portal->plane;
3416 if (portal->nodes[0] == portal->nodes[1])
3417 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3418 if (portal->nodes[0] == node)
3420 else if (portal->nodes[1] == node)
3422 clipplane.dist = -clipplane.dist;
3423 VectorNegate(clipplane.normal, clipplane.normal);
3427 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3429 for (i = 0;i < nodeportal->numpoints*3;i++)
3430 frontpoints[i] = nodeportal->points[i];
3431 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);
3432 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3436 if (nodeportal->numpoints < 3)
3438 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3439 nodeportal->numpoints = 0;
3441 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3443 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3444 nodeportal->numpoints = 0;
3447 AddPortalToNodes(nodeportal, front, back);
3449 // split the portals of this node along this node's plane and assign them to the children of this node
3450 // (migrating the portals downward through the tree)
3451 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3453 if (portal->nodes[0] == portal->nodes[1])
3454 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3455 if (portal->nodes[0] == node)
3457 else if (portal->nodes[1] == node)
3460 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3461 nextportal = portal->next[side];
3462 if (!portal->numpoints)
3465 other_node = portal->nodes[!side];
3466 RemovePortalFromNodes(portal);
3468 // cut the portal into two portals, one on each side of the node plane
3469 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);
3471 if (!numfrontpoints)
3474 AddPortalToNodes(portal, back, other_node);
3476 AddPortalToNodes(portal, other_node, back);
3482 AddPortalToNodes(portal, front, other_node);
3484 AddPortalToNodes(portal, other_node, front);
3488 // the portal is split
3489 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3490 temp = splitportal->chain;
3491 *splitportal = *portal;
3492 splitportal->chain = temp;
3493 for (i = 0;i < numbackpoints*3;i++)
3494 splitportal->points[i] = backpoints[i];
3495 splitportal->numpoints = numbackpoints;
3496 for (i = 0;i < numfrontpoints*3;i++)
3497 portal->points[i] = frontpoints[i];
3498 portal->numpoints = numfrontpoints;
3502 AddPortalToNodes(portal, front, other_node);
3503 AddPortalToNodes(splitportal, back, other_node);
3507 AddPortalToNodes(portal, other_node, front);
3508 AddPortalToNodes(splitportal, other_node, back);
3512 Mod_Q1BSP_RecursiveNodePortals(front);
3513 Mod_Q1BSP_RecursiveNodePortals(back);
3515 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3518 static void Mod_Q1BSP_MakePortals(void)
3520 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3521 portalpointsbufferoffset = 0;
3522 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3523 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3524 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3525 Mem_Free(portalpointsbuffer);
3526 portalpointsbuffer = NULL;
3527 portalpointsbufferoffset = 0;
3528 portalpointsbuffersize = 0;
3529 Mod_Q1BSP_FinalizePortals();
3530 Mem_ExpandableArray_FreeArray(&portalarray);
3533 //Returns PVS data for a given point
3534 //(note: can return NULL)
3535 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3538 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3540 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3541 if (((mleaf_t *)node)->clusterindex >= 0)
3542 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3547 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)
3551 float d = PlaneDiff(org, node->plane);
3553 node = node->children[0];
3554 else if (d < -radius)
3555 node = node->children[1];
3558 // go down both sides
3559 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3560 node = node->children[1];
3563 // if this leaf is in a cluster, accumulate the pvs bits
3564 if (((mleaf_t *)node)->clusterindex >= 0)
3567 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3568 for (i = 0;i < pvsbytes;i++)
3569 pvsbuffer[i] |= pvs[i];
3573 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3574 //of the given point.
3575 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3577 int bytes = model->brush.num_pvsclusterbytes;
3578 bytes = min(bytes, pvsbufferlength);
3579 if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3581 memset(pvsbuffer, 0xFF, bytes);
3585 memset(pvsbuffer, 0, bytes);
3586 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3590 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3595 VectorSubtract(inmaxs, inmins, size);
3596 if (cmodel->brush.ishlbsp)
3599 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3600 else if (size[0] <= 32)
3602 if (size[2] < 54) // pick the nearest of 36 or 72
3603 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3605 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3608 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3613 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3614 else if (size[0] <= 32)
3615 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3617 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3619 VectorCopy(inmins, outmins);
3620 VectorAdd(inmins, hull->clip_size, outmaxs);
3623 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3626 int numshadowmeshtriangles = 0;
3627 msurface_t *surface;
3628 if (cls.state == ca_dedicated)
3630 // make a single combined shadow mesh to allow optimized shadow volume creation
3632 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3634 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3635 numshadowmeshtriangles += surface->num_triangles;
3637 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3638 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3639 if (surface->num_triangles > 0)
3640 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));
3641 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3642 if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3643 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3645 return numshadowmeshtriangles;
3648 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);
3650 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3655 float dist, modelyawradius, modelradius;
3656 msurface_t *surface;
3657 hullinfo_t hullinfo;
3658 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3659 model_brush_lightstyleinfo_t styleinfo[256];
3660 unsigned char *datapointer;
3662 mod->modeldatatypestring = "Q1BSP";
3664 mod->type = mod_brushq1;
3666 header = (dheader_t *)buffer;
3668 i = LittleLong(header->version);
3669 if (i != BSPVERSION && i != 30)
3670 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3671 mod->brush.ishlbsp = i == 30;
3673 // fill in hull info
3674 VectorClear (hullinfo.hullsizes[0][0]);
3675 VectorClear (hullinfo.hullsizes[0][1]);
3676 if (mod->brush.ishlbsp)
3678 mod->modeldatatypestring = "HLBSP";
3680 hullinfo.filehulls = 4;
3681 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3682 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3683 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3684 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3685 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3686 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3690 hullinfo.filehulls = 4;
3691 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3692 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3693 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3694 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3698 mod_base = (unsigned char*)buffer;
3699 for (i = 0; i < HEADER_LUMPS; i++)
3701 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3702 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3705 mod->soundfromcenter = true;
3706 mod->TraceBox = Mod_Q1BSP_TraceBox;
3707 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
3708 mod->TraceLine = Mod_Q1BSP_TraceLineAgainstSurfaces; // LordHavoc: use the surface-hitting version of TraceLine in all cases
3710 mod->TraceLine = Mod_Q1BSP_TraceLine;
3711 mod->TracePoint = Mod_Q1BSP_TracePoint;
3712 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3713 mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3714 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3715 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3716 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3717 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3718 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3719 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3720 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3721 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3722 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3723 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3724 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3725 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3726 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3727 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3728 mod->Draw = R_Q1BSP_Draw;
3729 mod->DrawDepth = R_Q1BSP_DrawDepth;
3730 mod->DrawDebug = R_Q1BSP_DrawDebug;
3731 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3732 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3733 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3734 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3735 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3736 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3737 mod->DrawLight = R_Q1BSP_DrawLight;
3741 mod->brush.qw_md4sum = 0;
3742 mod->brush.qw_md4sum2 = 0;
3743 for (i = 0;i < HEADER_LUMPS;i++)
3746 if (i == LUMP_ENTITIES)
3748 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3749 mod->brush.qw_md4sum ^= LittleLong(temp);
3750 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3752 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3753 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3756 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3757 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3758 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3759 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3760 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3761 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3762 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3763 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3764 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3765 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3766 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3767 // load submodels before leafs because they contain the number of vis leafs
3768 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3769 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3770 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3771 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3773 // check if the map supports transparent water rendering
3774 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3776 if (mod->brushq1.data_compressedpvs)
3777 Mem_Free(mod->brushq1.data_compressedpvs);
3778 mod->brushq1.data_compressedpvs = NULL;
3779 mod->brushq1.num_compressedpvs = 0;
3781 Mod_Q1BSP_MakeHull0();
3782 if (mod_bsp_portalize.integer)
3783 Mod_Q1BSP_MakePortals();
3785 mod->numframes = 2; // regular and alternate animation
3788 // make a single combined shadow mesh to allow optimized shadow volume creation
3789 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3791 if (loadmodel->brush.numsubmodels)
3792 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3794 // LordHavoc: to clear the fog around the original quake submodel code, I
3796 // first of all, some background info on the submodels:
3797 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3798 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3799 // now the weird for loop itself:
3800 // the loop functions in an odd way, on each iteration it sets up the
3801 // current 'mod' model (which despite the confusing code IS the model of
3802 // the number i), at the end of the loop it duplicates the model to become
3803 // the next submodel, and loops back to set up the new submodel.
3805 // LordHavoc: now the explanation of my sane way (which works identically):
3806 // set up the world model, then on each submodel copy from the world model
3807 // and set up the submodel with the respective model info.
3808 totalstylesurfaces = 0;
3810 for (i = 0;i < mod->brush.numsubmodels;i++)
3812 memset(stylecounts, 0, sizeof(stylecounts));
3813 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3815 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3816 for (j = 0;j < MAXLIGHTMAPS;j++)
3817 stylecounts[surface->lightmapinfo->styles[j]]++;
3819 for (k = 0;k < 255;k++)
3823 totalstylesurfaces += stylecounts[k];
3826 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3827 for (i = 0;i < mod->brush.numsubmodels;i++)
3829 // LordHavoc: this code was originally at the end of this loop, but
3830 // has been transformed to something more readable at the start here.
3835 // duplicate the basic information
3836 dpsnprintf(name, sizeof(name), "*%i", i);
3837 mod = Mod_FindName(name, loadmodel->name);
3838 // copy the base model to this one
3840 // rename the clone back to its proper name
3841 strlcpy(mod->name, name, sizeof(mod->name));
3842 mod->brush.parentmodel = loadmodel;
3843 // textures and memory belong to the main model
3844 mod->texturepool = NULL;
3845 mod->mempool = NULL;
3846 mod->brush.GetPVS = NULL;
3847 mod->brush.FatPVS = NULL;
3848 mod->brush.BoxTouchingPVS = NULL;
3849 mod->brush.BoxTouchingLeafPVS = NULL;
3850 mod->brush.BoxTouchingVisibleLeafs = NULL;
3851 mod->brush.FindBoxClusters = NULL;
3852 mod->brush.LightPoint = NULL;
3853 mod->brush.AmbientSoundLevelsForPoint = NULL;
3856 mod->brush.submodel = i;
3858 if (loadmodel->brush.submodels)
3859 loadmodel->brush.submodels[i] = mod;
3861 bm = &mod->brushq1.submodels[i];
3863 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3864 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3866 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3867 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3870 mod->firstmodelsurface = bm->firstface;
3871 mod->nummodelsurfaces = bm->numfaces;
3873 // set node/leaf parents for this submodel
3874 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3876 // make the model surface list (used by shadowing/lighting)
3877 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3878 Mod_MakeSortedSurfaces(mod);
3880 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3881 // (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)
3882 VectorCopy(bm->mins, mod->normalmins);
3883 VectorCopy(bm->maxs, mod->normalmaxs);
3884 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3885 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3886 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3887 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3888 modelradius = modelyawradius + modelradius * modelradius;
3889 modelyawradius = sqrt(modelyawradius);
3890 modelradius = sqrt(modelradius);
3891 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3892 mod->yawmins[2] = mod->normalmins[2];
3893 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3894 mod->yawmaxs[2] = mod->normalmaxs[2];
3895 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3896 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3897 mod->radius = modelradius;
3898 mod->radius2 = modelradius * modelradius;
3900 // this gets altered below if sky or water is used
3901 mod->DrawSky = NULL;
3902 mod->DrawAddWaterPlanes = NULL;
3904 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3905 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3906 if (mod->nummodelsurfaces)
3908 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3909 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3911 if (j < mod->nummodelsurfaces)
3912 mod->DrawSky = R_Q1BSP_DrawSky;
3914 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3915 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
3917 if (j < mod->nummodelsurfaces)
3918 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3920 // build lightstyle update chains
3921 // (used to rapidly mark lightmapupdateflags on many surfaces
3922 // when d_lightstylevalue changes)
3923 memset(stylecounts, 0, sizeof(stylecounts));
3924 for (k = 0;k < mod->nummodelsurfaces;k++)
3926 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3927 for (j = 0;j < MAXLIGHTMAPS;j++)
3928 stylecounts[surface->lightmapinfo->styles[j]]++;
3930 mod->brushq1.num_lightstyles = 0;
3931 for (k = 0;k < 255;k++)
3935 styleinfo[mod->brushq1.num_lightstyles].style = k;
3936 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3937 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3938 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3939 remapstyles[k] = mod->brushq1.num_lightstyles;
3940 mod->brushq1.num_lightstyles++;
3943 for (k = 0;k < mod->nummodelsurfaces;k++)
3945 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3946 for (j = 0;j < MAXLIGHTMAPS;j++)
3948 if (surface->lightmapinfo->styles[j] != 255)
3950 int r = remapstyles[surface->lightmapinfo->styles[j]];
3951 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3955 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3956 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3960 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3961 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3963 //mod->brushq1.num_visleafs = bm->visleafs;
3965 // build a Bounding Interval Hierarchy for culling triangles in light rendering
3966 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
3968 if (mod_q1bsp_polygoncollisions.integer)
3970 mod->collision_bih = mod->render_bih;
3971 // point traces and contents checks still use the bsp tree
3972 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3973 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3974 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
3975 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
3978 // generate VBOs and other shared data before cloning submodels
3982 Mod_Q1BSP_LoadMapBrushes();
3983 //Mod_Q1BSP_ProcessLightList();
3987 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);
3990 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3994 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4001 in = (void *)(mod_base + l->fileofs);
4002 if (l->filelen % sizeof(*in))
4003 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4004 count = l->filelen / sizeof(*in);
4005 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4008 loadmodel->num = count;
4010 for (i = 0;i < count;i++, in++, out++)
4016 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4023 in = (void *)(mod_base + l->fileofs);
4024 if (l->filelen % sizeof(*in))
4025 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4026 count = l->filelen / sizeof(*in);
4027 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4030 loadmodel->num = count;
4032 for (i = 0;i < count;i++, in++, out++)
4038 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4045 in = (void *)(mod_base + l->fileofs);
4046 if (l->filelen % sizeof(*in))
4047 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4048 count = l->filelen / sizeof(*in);
4049 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4052 loadmodel->num = count;
4054 for (i = 0;i < count;i++, in++, out++)
4060 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4067 in = (void *)(mod_base + l->fileofs);
4068 if (l->filelen % sizeof(*in))
4069 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4070 count = l->filelen / sizeof(*in);
4071 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4074 loadmodel->num = count;
4076 for (i = 0;i < count;i++, in++, out++)
4082 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4089 in = (void *)(mod_base + l->fileofs);
4090 if (l->filelen % sizeof(*in))
4091 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4092 count = l->filelen / sizeof(*in);
4093 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4096 loadmodel->num = count;
4098 for (i = 0;i < count;i++, in++, out++)
4104 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4111 in = (void *)(mod_base + l->fileofs);
4112 if (l->filelen % sizeof(*in))
4113 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4114 count = l->filelen / sizeof(*in);
4115 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4118 loadmodel->num = count;
4120 for (i = 0;i < count;i++, in++, out++)
4126 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4133 in = (void *)(mod_base + l->fileofs);
4134 if (l->filelen % sizeof(*in))
4135 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4136 count = l->filelen / sizeof(*in);
4137 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4140 loadmodel->num = count;
4142 for (i = 0;i < count;i++, in++, out++)
4148 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4155 in = (void *)(mod_base + l->fileofs);
4156 if (l->filelen % sizeof(*in))
4157 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4158 count = l->filelen / sizeof(*in);
4159 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4162 loadmodel->num = count;
4164 for (i = 0;i < count;i++, in++, out++)
4170 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4177 in = (void *)(mod_base + l->fileofs);
4178 if (l->filelen % sizeof(*in))
4179 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4180 count = l->filelen / sizeof(*in);
4181 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4184 loadmodel->num = count;
4186 for (i = 0;i < count;i++, in++, out++)
4192 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4199 in = (void *)(mod_base + l->fileofs);
4200 if (l->filelen % sizeof(*in))
4201 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4202 count = l->filelen / sizeof(*in);
4203 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4206 loadmodel->num = count;
4208 for (i = 0;i < count;i++, in++, out++)
4214 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4221 in = (void *)(mod_base + l->fileofs);
4222 if (l->filelen % sizeof(*in))
4223 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4224 count = l->filelen / sizeof(*in);
4225 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4228 loadmodel->num = count;
4230 for (i = 0;i < count;i++, in++, out++)
4236 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4243 in = (void *)(mod_base + l->fileofs);
4244 if (l->filelen % sizeof(*in))
4245 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4246 count = l->filelen / sizeof(*in);
4247 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4250 loadmodel->num = count;
4252 for (i = 0;i < count;i++, in++, out++)
4258 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4265 in = (void *)(mod_base + l->fileofs);
4266 if (l->filelen % sizeof(*in))
4267 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4268 count = l->filelen / sizeof(*in);
4269 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4272 loadmodel->num = count;
4274 for (i = 0;i < count;i++, in++, out++)
4280 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4287 in = (void *)(mod_base + l->fileofs);
4288 if (l->filelen % sizeof(*in))
4289 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4290 count = l->filelen / sizeof(*in);
4291 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4294 loadmodel->num = count;
4296 for (i = 0;i < count;i++, in++, out++)
4302 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4309 in = (void *)(mod_base + l->fileofs);
4310 if (l->filelen % sizeof(*in))
4311 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4312 count = l->filelen / sizeof(*in);
4313 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4316 loadmodel->num = count;
4318 for (i = 0;i < count;i++, in++, out++)
4324 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4331 in = (void *)(mod_base + l->fileofs);
4332 if (l->filelen % sizeof(*in))
4333 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4334 count = l->filelen / sizeof(*in);
4335 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4338 loadmodel->num = count;
4340 for (i = 0;i < count;i++, in++, out++)
4346 static void Mod_Q2BSP_LoadModels(lump_t *l)
4353 in = (void *)(mod_base + l->fileofs);
4354 if (l->filelen % sizeof(*in))
4355 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4356 count = l->filelen / sizeof(*in);
4357 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4360 loadmodel->num = count;
4362 for (i = 0;i < count;i++, in++, out++)
4368 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4371 q2dheader_t *header;
4373 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4375 mod->modeldatatypestring = "Q2BSP";
4377 mod->type = mod_brushq2;
4379 header = (q2dheader_t *)buffer;
4381 i = LittleLong(header->version);
4382 if (i != Q2BSPVERSION)
4383 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4385 mod_base = (unsigned char *)header;
4387 // swap all the lumps
4388 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4389 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4391 mod->brush.qw_md4sum = 0;
4392 mod->brush.qw_md4sum2 = 0;
4393 for (i = 0;i < Q2HEADER_LUMPS;i++)
4395 if (i == Q2LUMP_ENTITIES)
4397 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4398 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4400 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4403 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4404 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4405 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4406 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4407 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4408 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4409 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4410 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4411 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4412 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4413 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4414 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4415 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4416 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4417 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4418 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4419 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4420 // LordHavoc: must go last because this makes the submodels
4421 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4424 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4425 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4427 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4430 char key[128], value[MAX_INPUTLINE];
4432 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4433 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4434 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4437 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4438 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4439 loadmodel->brush.entities[l->filelen] = 0;
4440 data = loadmodel->brush.entities;
4441 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4442 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4443 loadmodel->brushq3.deluxemapping = false;
4444 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4448 if (!COM_ParseToken_Simple(&data, false, false))
4450 if (com_token[0] == '}')
4451 break; // end of worldspawn
4452 if (com_token[0] == '_')
4453 strlcpy(key, com_token + 1, sizeof(key));
4455 strlcpy(key, com_token, sizeof(key));
4456 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4457 key[strlen(key)-1] = 0;
4458 if (!COM_ParseToken_Simple(&data, false, false))
4460 strlcpy(value, com_token, sizeof(value));
4461 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4463 #if _MSC_VER >= 1400
4464 #define sscanf sscanf_s
4467 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4468 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4470 VectorSet(v, 64, 64, 128);
4471 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4472 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]);
4473 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4474 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4477 else if (!strcmp("deluxeMaps", key))
4479 if (!strcmp(com_token, "1"))
4481 loadmodel->brushq3.deluxemapping = true;
4482 loadmodel->brushq3.deluxemapping_modelspace = true;
4484 else if (!strcmp(com_token, "2"))
4486 loadmodel->brushq3.deluxemapping = true;
4487 loadmodel->brushq3.deluxemapping_modelspace = false;
4494 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4500 in = (q3dtexture_t *)(mod_base + l->fileofs);
4501 if (l->filelen % sizeof(*in))
4502 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4503 count = l->filelen / sizeof(*in);
4504 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4506 loadmodel->data_textures = out;
4507 loadmodel->num_textures = count;
4508 loadmodel->num_texturesperskin = loadmodel->num_textures;
4510 for (i = 0;i < count;i++)
4512 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4513 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4514 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4515 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4516 // restore the surfaceflags and supercontents
4517 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4518 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4522 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4528 in = (q3dplane_t *)(mod_base + l->fileofs);
4529 if (l->filelen % sizeof(*in))
4530 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4531 count = l->filelen / sizeof(*in);
4532 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4534 loadmodel->brush.data_planes = out;
4535 loadmodel->brush.num_planes = count;
4537 for (i = 0;i < count;i++, in++, out++)
4539 out->normal[0] = LittleFloat(in->normal[0]);
4540 out->normal[1] = LittleFloat(in->normal[1]);
4541 out->normal[2] = LittleFloat(in->normal[2]);
4542 out->dist = LittleFloat(in->dist);
4547 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4550 q3mbrushside_t *out;
4553 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4554 if (l->filelen % sizeof(*in))
4555 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4556 count = l->filelen / sizeof(*in);
4557 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4559 loadmodel->brush.data_brushsides = out;
4560 loadmodel->brush.num_brushsides = count;
4562 for (i = 0;i < count;i++, in++, out++)
4564 n = LittleLong(in->planeindex);
4565 if (n < 0 || n >= loadmodel->brush.num_planes)
4566 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4567 out->plane = loadmodel->brush.data_planes + n;
4568 n = LittleLong(in->textureindex);
4569 if (n < 0 || n >= loadmodel->num_textures)
4570 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4571 out->texture = loadmodel->data_textures + n;
4575 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4577 q3dbrushside_ig_t *in;
4578 q3mbrushside_t *out;
4581 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4582 if (l->filelen % sizeof(*in))
4583 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4584 count = l->filelen / sizeof(*in);
4585 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4587 loadmodel->brush.data_brushsides = out;
4588 loadmodel->brush.num_brushsides = count;
4590 for (i = 0;i < count;i++, in++, out++)
4592 n = LittleLong(in->planeindex);
4593 if (n < 0 || n >= loadmodel->brush.num_planes)
4594 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4595 out->plane = loadmodel->brush.data_planes + n;
4596 n = LittleLong(in->textureindex);
4597 if (n < 0 || n >= loadmodel->num_textures)
4598 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4599 out->texture = loadmodel->data_textures + n;
4603 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4607 int i, j, n, c, count, maxplanes, q3surfaceflags;
4608 colplanef_t *planes;
4610 in = (q3dbrush_t *)(mod_base + l->fileofs);
4611 if (l->filelen % sizeof(*in))
4612 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4613 count = l->filelen / sizeof(*in);
4614 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4616 loadmodel->brush.data_brushes = out;
4617 loadmodel->brush.num_brushes = count;
4622 for (i = 0;i < count;i++, in++, out++)
4624 n = LittleLong(in->firstbrushside);
4625 c = LittleLong(in->numbrushsides);
4626 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4627 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4628 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4629 out->numbrushsides = c;
4630 n = LittleLong(in->textureindex);
4631 if (n < 0 || n >= loadmodel->num_textures)
4632 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4633 out->texture = loadmodel->data_textures + n;
4635 // make a list of mplane_t structs to construct a colbrush from
4636 if (maxplanes < out->numbrushsides)
4638 maxplanes = out->numbrushsides;
4641 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4644 for (j = 0;j < out->numbrushsides;j++)
4646 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4647 planes[j].dist = out->firstbrushside[j].plane->dist;
4648 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4649 planes[j].texture = out->firstbrushside[j].texture;
4650 q3surfaceflags |= planes[j].q3surfaceflags;
4652 // make the colbrush from the planes
4653 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4655 // this whole loop can take a while (e.g. on redstarrepublic4)
4656 CL_KeepaliveMessage(false);
4662 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4668 in = (q3deffect_t *)(mod_base + l->fileofs);
4669 if (l->filelen % sizeof(*in))
4670 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4671 count = l->filelen / sizeof(*in);
4672 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4674 loadmodel->brushq3.data_effects = out;
4675 loadmodel->brushq3.num_effects = count;
4677 for (i = 0;i < count;i++, in++, out++)
4679 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4680 n = LittleLong(in->brushindex);
4681 if (n >= loadmodel->brush.num_brushes)
4683 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4686 out->brushindex = n;
4687 out->unknown = LittleLong(in->unknown);
4691 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4696 in = (q3dvertex_t *)(mod_base + l->fileofs);
4697 if (l->filelen % sizeof(*in))
4698 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4699 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4700 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4701 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4702 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4703 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4704 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4706 for (i = 0;i < count;i++, in++)
4708 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4709 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4710 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4711 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4712 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4713 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4714 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4715 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4716 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4717 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4718 // svector/tvector are calculated later in face loading
4719 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4720 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4721 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4722 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4723 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4724 loadmodel->lit = true;
4728 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4734 in = (int *)(mod_base + l->fileofs);
4735 if (l->filelen % sizeof(int[3]))
4736 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4737 count = l->filelen / sizeof(*in);
4739 if(!loadmodel->brushq3.num_vertices)
4742 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4743 loadmodel->brushq3.num_triangles = 0;
4747 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4748 loadmodel->brushq3.num_triangles = count / 3;
4749 loadmodel->brushq3.data_element3i = out;
4751 for (i = 0;i < count;i++, in++, out++)
4753 *out = LittleLong(*in);
4754 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4756 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4762 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4764 q3dlightmap_t *input_pointer;
4782 int mergedrowsxcolumns;
4787 unsigned char *mergedpixels;
4788 unsigned char *mergeddeluxepixels;
4789 unsigned char *mergebuf;
4790 char mapname[MAX_QPATH];
4792 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4794 // defaults for q3bsp
4801 loadmodel->brushq3.lightmapsize = 128;
4803 if (cls.state == ca_dedicated)
4806 if(mod_q3bsp_nolightmaps.integer)
4812 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4813 if (developer_loading.integer)
4814 Con_Printf("Using internal lightmaps\n");
4815 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4816 if (l->filelen % sizeof(*input_pointer))
4817 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4818 count = l->filelen / sizeof(*input_pointer);
4819 for(i = 0; i < count; ++i)
4820 inpixels[i] = input_pointer[i].rgb;
4824 // no internal lightmaps
4825 // try external lightmaps
4826 if (developer_loading.integer)
4827 Con_Printf("Using external lightmaps\n");
4828 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4829 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false, NULL);
4833 // using EXTERNAL lightmaps instead
4834 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4836 Mem_Free(inpixels[0]);
4837 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4847 for(count = 1; ; ++count)
4849 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false, NULL);
4850 if(!inpixels[count])
4851 break; // we got all of them
4852 if(image_width != size || image_height != size)
4854 Mem_Free(inpixels[count]);
4855 inpixels[count] = NULL;
4856 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);
4862 loadmodel->brushq3.lightmapsize = size;
4863 loadmodel->brushq3.num_originallightmaps = count;
4865 // now check the surfaces to see if any of them index an odd numbered
4866 // lightmap, if so this is not a deluxemapped bsp file
4868 // also check what lightmaps are actually used, because q3map2 sometimes
4869 // (always?) makes an unused one at the end, which
4870 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4871 // reason when only one lightmap is used, which can throw off the
4872 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4873 // to see if the second lightmap is blank, if so it is not deluxemapped.
4874 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4875 // in Mod_Q3BSP_LoadEntities was failed
4876 if (!loadmodel->brushq3.deluxemapping)
4878 loadmodel->brushq3.deluxemapping = !(count & 1);
4879 loadmodel->brushq3.deluxemapping_modelspace = true;
4881 if (loadmodel->brushq3.deluxemapping)
4883 int facecount = faceslump->filelen / sizeof(q3dface_t);
4884 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4885 for (i = 0;i < facecount;i++)
4887 j = LittleLong(faces[i].lightmapindex);
4890 endlightmap = max(endlightmap, j + 1);
4891 if ((j & 1) || j + 1 >= count)
4893 loadmodel->brushq3.deluxemapping = false;
4900 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4901 // reason when only one lightmap is used, which can throw off the
4902 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4903 // to see if the second lightmap is blank, if so it is not deluxemapped.
4905 // further research has shown q3map2 sometimes creates a deluxemap and two
4906 // blank lightmaps, which must be handled properly as well
4907 if (endlightmap == 1 && count > 1)
4910 for (i = 0;i < size*size;i++)
4912 if (c[bytesperpixel*i + rgbmap[0]])
4914 if (c[bytesperpixel*i + rgbmap[1]])
4916 if (c[bytesperpixel*i + rgbmap[2]])
4921 // all pixels in the unused lightmap were black...
4922 loadmodel->brushq3.deluxemapping = false;
4927 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4929 // figure out what the most reasonable merge power is within limits
4931 // find the appropriate NxN dimensions to merge to, to avoid wasted space
4932 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
4934 // figure out how big the merged texture has to be
4935 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
4936 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
4937 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
4939 mergedwidth = mergegoal;
4940 mergedheight = mergegoal;
4941 // choose non-square size (2x1 aspect) if only half the space is used;
4942 // this really only happens when the entire set fits in one texture, if
4943 // there are multiple textures, we don't worry about shrinking the last
4944 // one to fit, because the driver prefers the same texture size on
4945 // consecutive draw calls...
4946 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
4949 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
4950 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
4951 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
4952 loadmodel->brushq3.num_lightmapmergedwidthpower++;
4953 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
4954 loadmodel->brushq3.num_lightmapmergedheightpower++;
4955 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
4957 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
4958 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
4959 powerxy = powerx+powery;
4960 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
4962 mergedcolumns = 1 << powerx;
4963 mergedrows = 1 << powery;
4964 mergedrowsxcolumns = 1 << powerxy;
4966 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
4967 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4968 if (loadmodel->brushq3.deluxemapping)
4969 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4971 // allocate a texture pool if we need it
4972 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4973 loadmodel->texturepool = R_AllocTexturePool();
4975 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
4976 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
4977 for (i = 0;i < count;i++)
4979 // figure out which merged lightmap texture this fits into
4980 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
4981 lightmapindex = i >> powerdxy;
4983 // choose the destination address
4984 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
4985 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
4986 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
4987 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);
4989 // convert pixels from RGB or BGRA while copying them into the destination rectangle
4990 for (j = 0;j < size;j++)
4991 for (k = 0;k < size;k++)
4993 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
4994 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
4995 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
4996 mergebuf[(j*mergedwidth+k)*4+3] = 255;
4999 // upload texture if this was the last tile being written to the texture
5000 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5002 if (loadmodel->brushq3.deluxemapping && (i & 1))
5003 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5005 loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5009 if (mergeddeluxepixels)
5010 Mem_Free(mergeddeluxepixels);
5011 Mem_Free(mergedpixels);
5014 for(i = 0; i < count; ++i)
5015 Mem_Free(inpixels[i]);
5019 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5024 *collisionstride = stride;
5027 cnt = (num_triangles + stride - 1) / stride;
5028 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5029 for(j = 0; j < cnt; ++j)
5031 mins = &((*collisionbbox6f)[6 * j + 0]);
5032 maxs = &((*collisionbbox6f)[6 * j + 3]);
5033 for(k = 0; k < stride; ++k)
5035 tri = j * stride + k;
5036 if(tri >= num_triangles)
5038 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5039 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5040 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5041 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5042 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5043 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5044 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5045 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5046 if(vert[0] < mins[0]) mins[0] = vert[0];
5047 if(vert[1] < mins[1]) mins[1] = vert[1];
5048 if(vert[2] < mins[2]) mins[2] = vert[2];
5049 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5050 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5051 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5052 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5053 if(vert[0] < mins[0]) mins[0] = vert[0];
5054 if(vert[1] < mins[1]) mins[1] = vert[1];
5055 if(vert[2] < mins[2]) mins[2] = vert[2];
5056 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5057 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5058 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5063 *collisionbbox6f = NULL;
5066 typedef struct patchtess_s
5070 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5073 float *originalvertex3f;
5076 #define PATCHTESS_SAME_LODGROUP(a,b) \
5078 (a).lodgroup[0] == (b).lodgroup[0] && \
5079 (a).lodgroup[1] == (b).lodgroup[1] && \
5080 (a).lodgroup[2] == (b).lodgroup[2] && \
5081 (a).lodgroup[3] == (b).lodgroup[3] && \
5082 (a).lodgroup[4] == (b).lodgroup[4] && \
5083 (a).lodgroup[5] == (b).lodgroup[5] \
5086 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5088 q3dface_t *in, *oldin;
5089 msurface_t *out, *oldout;
5090 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;
5091 float lightmaptcbase[2], lightmaptcscale[2];
5092 //int *originalelement3i;
5093 //int *originalneighbor3i;
5094 float *originalvertex3f;
5095 //float *originalsvector3f;
5096 //float *originaltvector3f;
5097 float *originalnormal3f;
5098 float *originalcolor4f;
5099 float *originaltexcoordtexture2f;
5100 float *originaltexcoordlightmap2f;
5101 float *surfacecollisionvertex3f;
5102 int *surfacecollisionelement3i;
5104 patchtess_t *patchtess = NULL;
5105 int patchtesscount = 0;
5108 in = (q3dface_t *)(mod_base + l->fileofs);
5109 if (l->filelen % sizeof(*in))
5110 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5111 count = l->filelen / sizeof(*in);
5112 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5114 loadmodel->data_surfaces = out;
5115 loadmodel->num_surfaces = count;
5118 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5126 for (;i < count;i++, in++, out++)
5128 // check face type first
5129 type = LittleLong(in->type);
5130 if (type != Q3FACETYPE_FLAT
5131 && type != Q3FACETYPE_PATCH
5132 && type != Q3FACETYPE_MESH
5133 && type != Q3FACETYPE_FLARE)
5135 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5139 n = LittleLong(in->textureindex);
5140 if (n < 0 || n >= loadmodel->num_textures)
5142 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5145 out->texture = loadmodel->data_textures + n;
5146 n = LittleLong(in->effectindex);
5147 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5149 if (developer_extra.integer)
5150 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5156 out->effect = loadmodel->brushq3.data_effects + n;
5158 if (cls.state != ca_dedicated)
5160 out->lightmaptexture = NULL;
5161 out->deluxemaptexture = r_texture_blanknormalmap;
5162 n = LittleLong(in->lightmapindex);
5165 else if (n >= loadmodel->brushq3.num_originallightmaps)
5167 if(loadmodel->brushq3.num_originallightmaps != 0)
5168 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5173 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5174 if (loadmodel->brushq3.deluxemapping)
5175 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5176 loadmodel->lit = true;
5180 firstvertex = LittleLong(in->firstvertex);
5181 numvertices = LittleLong(in->numvertices);
5182 firstelement = LittleLong(in->firstelement);
5183 numtriangles = LittleLong(in->numelements) / 3;
5184 if (numtriangles * 3 != LittleLong(in->numelements))
5186 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));
5189 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5191 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);
5194 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5196 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);
5201 case Q3FACETYPE_FLAT:
5202 case Q3FACETYPE_MESH:
5203 // no processing necessary
5205 case Q3FACETYPE_PATCH:
5206 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5207 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5208 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))
5210 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5213 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5215 // convert patch to Q3FACETYPE_MESH
5216 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5217 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5218 // bound to user settings
5219 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5220 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5221 // bound to sanity settings
5222 xtess = bound(0, xtess, 1024);
5223 ytess = bound(0, ytess, 1024);
5225 // lower quality collision patches! Same procedure as before, but different cvars
5226 // convert patch to Q3FACETYPE_MESH
5227 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5228 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5229 // bound to user settings
5230 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5231 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5232 // bound to sanity settings
5233 cxtess = bound(0, cxtess, 1024);
5234 cytess = bound(0, cytess, 1024);
5236 // store it for the LOD grouping step
5237 patchtess[patchtesscount].info.xsize = patchsize[0];
5238 patchtess[patchtesscount].info.ysize = patchsize[1];
5239 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5240 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5241 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5242 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5244 patchtess[patchtesscount].surface_id = i;
5245 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5246 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5247 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5248 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5249 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5250 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5251 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5254 case Q3FACETYPE_FLARE:
5255 if (developer_extra.integer)
5256 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5260 out->num_vertices = numvertices;
5261 out->num_triangles = numtriangles;
5262 meshvertices += out->num_vertices;
5263 meshtriangles += out->num_triangles;
5266 // Fix patches tesselations so that they make no seams
5270 for(i = 0; i < patchtesscount; ++i)
5272 for(j = i+1; j < patchtesscount; ++j)
5274 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5277 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5284 // Calculate resulting number of triangles
5285 collisionvertices = 0;
5286 collisiontriangles = 0;
5287 for(i = 0; i < patchtesscount; ++i)
5289 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5290 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5291 numvertices = finalwidth * finalheight;
5292 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5294 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5295 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5296 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5297 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5299 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5300 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5301 numvertices = finalwidth * finalheight;
5302 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5304 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5305 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5306 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5307 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5313 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5314 if (collisiontriangles)
5316 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5317 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5321 collisionvertices = 0;
5322 collisiontriangles = 0;
5323 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5325 if (out->num_vertices < 3 || out->num_triangles < 1)
5328 type = LittleLong(in->type);
5329 firstvertex = LittleLong(in->firstvertex);
5330 firstelement = LittleLong(in->firstelement);
5331 out->num_firstvertex = meshvertices;
5332 out->num_firsttriangle = meshtriangles;
5333 out->num_firstcollisiontriangle = collisiontriangles;
5336 case Q3FACETYPE_FLAT:
5337 case Q3FACETYPE_MESH:
5338 // no processing necessary, except for lightmap merging
5339 for (j = 0;j < out->num_vertices;j++)
5341 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5342 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5343 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5344 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5345 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5346 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5347 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5348 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5349 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5350 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5351 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5352 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5353 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5354 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5356 for (j = 0;j < out->num_triangles*3;j++)
5357 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5359 case Q3FACETYPE_PATCH:
5360 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5361 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5362 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5363 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5364 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5365 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5366 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5368 xtess = ytess = cxtess = cytess = -1;
5369 for(j = 0; j < patchtesscount; ++j)
5370 if(patchtess[j].surface_id == i)
5372 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5373 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5374 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5375 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5380 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5381 xtess = ytess = cxtess = cytess = 0;
5384 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5385 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5386 finalvertices = finalwidth * finalheight;
5387 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5388 type = Q3FACETYPE_MESH;
5389 // generate geometry
5390 // (note: normals are skipped because they get recalculated)
5391 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5392 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5393 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5394 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5395 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5396 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5398 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);
5400 if (developer_extra.integer)
5402 if (out->num_triangles < finaltriangles)
5403 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);
5405 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);
5407 // q3map does not put in collision brushes for curves... ugh
5408 // build the lower quality collision geometry
5409 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5410 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5411 finalvertices = finalwidth * finalheight;
5412 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5414 // legacy collision geometry implementation
5415 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5416 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5417 out->num_collisionvertices = finalvertices;
5418 out->num_collisiontriangles = finaltriangles;
5419 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5420 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5422 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5423 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5425 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5427 // now optimize the collision mesh by finding triangle bboxes...
5428 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5429 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);
5431 // store collision geometry for BIH collision tree
5432 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5433 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5434 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5435 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5436 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5438 // remove this once the legacy code is removed
5440 int nc = out->num_collisiontriangles;
5442 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5444 if(nc != out->num_collisiontriangles)
5446 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5451 if (developer_extra.integer)
5452 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);
5454 collisionvertices += finalvertices;
5455 collisiontriangles += out->num_collisiontriangles;
5460 meshvertices += out->num_vertices;
5461 meshtriangles += out->num_triangles;
5462 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5463 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)
5465 if (invalidelements)
5467 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);
5468 for (j = 0;j < out->num_triangles * 3;j++)
5470 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5471 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)
5472 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5476 // calculate a bounding box
5477 VectorClear(out->mins);
5478 VectorClear(out->maxs);
5479 if (out->num_vertices)
5481 if (cls.state != ca_dedicated && out->lightmaptexture)
5483 // figure out which part of the merged lightmap this fits into
5484 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5485 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5486 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5487 lightmapindex &= mergewidth * mergeheight - 1;
5488 lightmaptcscale[0] = 1.0f / mergewidth;
5489 lightmaptcscale[1] = 1.0f / mergeheight;
5490 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5491 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5492 // modify the lightmap texcoords to match this region of the merged lightmap
5493 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5495 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5496 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5499 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5500 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5501 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5503 out->mins[0] = min(out->mins[0], v[0]);
5504 out->maxs[0] = max(out->maxs[0], v[0]);
5505 out->mins[1] = min(out->mins[1], v[1]);
5506 out->maxs[1] = max(out->maxs[1], v[1]);
5507 out->mins[2] = min(out->mins[2], v[2]);
5508 out->maxs[2] = max(out->maxs[2], v[2]);
5510 out->mins[0] -= 1.0f;
5511 out->mins[1] -= 1.0f;
5512 out->mins[2] -= 1.0f;
5513 out->maxs[0] += 1.0f;
5514 out->maxs[1] += 1.0f;
5515 out->maxs[2] += 1.0f;
5517 // set lightmap styles for consistency with q1bsp
5518 //out->lightmapinfo->styles[0] = 0;
5519 //out->lightmapinfo->styles[1] = 255;
5520 //out->lightmapinfo->styles[2] = 255;
5521 //out->lightmapinfo->styles[3] = 255;
5526 for (;i < count;i++, out++)
5528 if(out->num_vertices && out->num_triangles)
5530 if(out->num_vertices == 0)
5532 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5533 if(out->num_triangles == 0)
5534 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5536 else if(out->num_triangles == 0)
5537 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)",
5538 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5539 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5540 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5543 // for per pixel lighting
5544 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);
5546 // generate ushort elements array if possible
5547 if (loadmodel->surfmesh.data_element3s)
5548 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5549 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5551 // free the no longer needed vertex data
5552 loadmodel->brushq3.num_vertices = 0;
5553 if (loadmodel->brushq3.data_vertex3f)
5554 Mem_Free(loadmodel->brushq3.data_vertex3f);
5555 loadmodel->brushq3.data_vertex3f = NULL;
5556 loadmodel->brushq3.data_normal3f = NULL;
5557 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5558 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5559 loadmodel->brushq3.data_color4f = NULL;
5560 // free the no longer needed triangle data
5561 loadmodel->brushq3.num_triangles = 0;
5562 if (loadmodel->brushq3.data_element3i)
5563 Mem_Free(loadmodel->brushq3.data_element3i);
5564 loadmodel->brushq3.data_element3i = NULL;
5567 Mem_Free(patchtess);
5570 static void Mod_Q3BSP_LoadModels(lump_t *l)
5574 int i, j, n, c, count;
5576 in = (q3dmodel_t *)(mod_base + l->fileofs);
5577 if (l->filelen % sizeof(*in))
5578 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5579 count = l->filelen / sizeof(*in);
5580 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5582 loadmodel->brushq3.data_models = out;
5583 loadmodel->brushq3.num_models = count;
5585 for (i = 0;i < count;i++, in++, out++)
5587 for (j = 0;j < 3;j++)
5589 out->mins[j] = LittleFloat(in->mins[j]);
5590 out->maxs[j] = LittleFloat(in->maxs[j]);
5592 n = LittleLong(in->firstface);
5593 c = LittleLong(in->numfaces);
5594 if (n < 0 || n + c > loadmodel->num_surfaces)
5595 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5598 n = LittleLong(in->firstbrush);
5599 c = LittleLong(in->numbrushes);
5600 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5601 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5602 out->firstbrush = n;
5603 out->numbrushes = c;
5607 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5613 in = (int *)(mod_base + l->fileofs);
5614 if (l->filelen % sizeof(*in))
5615 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5616 count = l->filelen / sizeof(*in);
5617 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5619 loadmodel->brush.data_leafbrushes = out;
5620 loadmodel->brush.num_leafbrushes = count;
5622 for (i = 0;i < count;i++, in++, out++)
5624 n = LittleLong(*in);
5625 if (n < 0 || n >= loadmodel->brush.num_brushes)
5626 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5631 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5637 in = (int *)(mod_base + l->fileofs);
5638 if (l->filelen % sizeof(*in))
5639 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5640 count = l->filelen / sizeof(*in);
5641 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5643 loadmodel->brush.data_leafsurfaces = out;
5644 loadmodel->brush.num_leafsurfaces = count;
5646 for (i = 0;i < count;i++, in++, out++)
5648 n = LittleLong(*in);
5649 if (n < 0 || n >= loadmodel->num_surfaces)
5650 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5655 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5659 int i, j, n, c, count;
5661 in = (q3dleaf_t *)(mod_base + l->fileofs);
5662 if (l->filelen % sizeof(*in))
5663 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5664 count = l->filelen / sizeof(*in);
5665 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5667 loadmodel->brush.data_leafs = out;
5668 loadmodel->brush.num_leafs = count;
5670 for (i = 0;i < count;i++, in++, out++)
5674 out->clusterindex = LittleLong(in->clusterindex);
5675 out->areaindex = LittleLong(in->areaindex);
5676 for (j = 0;j < 3;j++)
5678 // yes the mins/maxs are ints
5679 out->mins[j] = LittleLong(in->mins[j]) - 1;
5680 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5682 n = LittleLong(in->firstleafface);
5683 c = LittleLong(in->numleaffaces);
5684 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5685 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5686 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5687 out->numleafsurfaces = c;
5688 n = LittleLong(in->firstleafbrush);
5689 c = LittleLong(in->numleafbrushes);
5690 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5691 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5692 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5693 out->numleafbrushes = c;
5697 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5703 in = (q3dnode_t *)(mod_base + l->fileofs);
5704 if (l->filelen % sizeof(*in))
5705 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5706 count = l->filelen / sizeof(*in);
5708 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5709 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5711 loadmodel->brush.data_nodes = out;
5712 loadmodel->brush.num_nodes = count;
5714 for (i = 0;i < count;i++, in++, out++)
5717 n = LittleLong(in->planeindex);
5718 if (n < 0 || n >= loadmodel->brush.num_planes)
5719 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5720 out->plane = loadmodel->brush.data_planes + n;
5721 for (j = 0;j < 2;j++)
5723 n = LittleLong(in->childrenindex[j]);
5726 if (n >= loadmodel->brush.num_nodes)
5727 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5728 out->children[j] = loadmodel->brush.data_nodes + n;
5733 if (n >= loadmodel->brush.num_leafs)
5734 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5735 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5738 for (j = 0;j < 3;j++)
5740 // yes the mins/maxs are ints
5741 out->mins[j] = LittleLong(in->mins[j]) - 1;
5742 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5746 // set the parent pointers
5747 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5750 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5753 q3dlightgrid_t *out;
5756 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5757 if (l->filelen % sizeof(*in))
5758 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5759 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5760 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5761 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5762 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5763 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5764 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5765 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5766 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5767 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5768 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5769 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5770 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5771 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5772 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]);
5773 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]);
5775 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5778 if (l->filelen < count * (int)sizeof(*in))
5780 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]);
5781 return; // ignore the grid if we cannot understand it
5783 if (l->filelen != count * (int)sizeof(*in))
5784 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5785 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5786 loadmodel->brushq3.data_lightgrid = out;
5787 loadmodel->brushq3.num_lightgrid = count;
5788 // no swapping or validation necessary
5789 memcpy(out, in, count * (int)sizeof(*out));
5793 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5798 if (l->filelen == 0)
5801 // unvised maps often have cluster indices even without pvs, so check
5802 // leafs to find real number of clusters
5803 loadmodel->brush.num_pvsclusters = 1;
5804 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5805 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5808 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5809 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5810 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5811 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5815 in = (q3dpvs_t *)(mod_base + l->fileofs);
5817 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5819 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5820 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5821 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5822 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5823 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5824 if (l->filelen < totalchains + (int)sizeof(*in))
5825 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);
5827 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5828 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5831 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5833 int i, j, k, index[3];
5834 float transformed[3], blend1, blend2, blend, stylescale = 1;
5835 q3dlightgrid_t *a, *s;
5837 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5838 switch(vid.renderpath)
5840 case RENDERPATH_GL20:
5841 case RENDERPATH_D3D9:
5842 case RENDERPATH_D3D10:
5843 case RENDERPATH_D3D11:
5844 case RENDERPATH_SOFT:
5845 case RENDERPATH_GLES2:
5846 // LordHavoc: FIXME: is this true?
5847 stylescale = 1; // added while render
5849 case RENDERPATH_GL11:
5850 case RENDERPATH_GL13:
5851 case RENDERPATH_GLES1:
5852 stylescale = r_refdef.scene.rtlightstylevalue[0];
5856 if (!model->brushq3.num_lightgrid)
5858 ambientcolor[0] = stylescale;
5859 ambientcolor[1] = stylescale;
5860 ambientcolor[2] = stylescale;
5864 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5865 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5866 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5867 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5868 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5869 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5870 index[0] = (int)floor(transformed[0]);
5871 index[1] = (int)floor(transformed[1]);
5872 index[2] = (int)floor(transformed[2]);
5873 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5875 // now lerp the values
5876 VectorClear(diffusenormal);
5877 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5878 for (k = 0;k < 2;k++)
5880 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5881 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5883 for (j = 0;j < 2;j++)
5885 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5886 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5888 for (i = 0;i < 2;i++)
5890 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5891 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5893 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5894 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5895 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5896 // this uses the mod_md3_sin table because the values are
5897 // already in the 0-255 range, the 64+ bias fetches a cosine
5898 // instead of a sine value
5899 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5900 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5901 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5902 //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)));
5907 // normalize the light direction before turning
5908 VectorNormalize(diffusenormal);
5909 //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]);
5912 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5915 double midf, mid[3];
5921 // find the point distances
5922 mplane_t *plane = node->plane;
5923 if (plane->type < 3)
5925 t1 = p1[plane->type] - plane->dist;
5926 t2 = p2[plane->type] - plane->dist;
5930 t1 = DotProduct (plane->normal, p1) - plane->dist;
5931 t2 = DotProduct (plane->normal, p2) - plane->dist;
5938 node = node->children[1];
5947 node = node->children[0];
5953 midf = t1 / (t1 - t2);
5954 VectorLerp(p1, midf, p2, mid);
5956 // recurse both sides, front side first
5957 // return 2 if empty is followed by solid (hit something)
5958 // do not return 2 if both are solid or both empty,
5959 // or if start is solid and end is empty
5960 // as these degenerate cases usually indicate the eye is in solid and
5961 // should see the target point anyway
5962 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5965 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5970 return ((mleaf_t *)node)->clusterindex < 0;
5973 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5975 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5978 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5979 return trace.fraction == 1;
5983 double tracestart[3], traceend[3];
5984 VectorCopy(start, tracestart);
5985 VectorCopy(end, traceend);
5986 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5990 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)
5993 const bih_leaf_t *leaf;
5994 const bih_node_t *node;
5995 const colbrushf_t *brush;
5998 int nodestackpos = 0;
5999 int nodestack[1024];
6001 memset(trace, 0, sizeof(*trace));
6002 trace->fraction = 1;
6003 trace->realfraction = 1;
6004 trace->hitsupercontentsmask = hitsupercontentsmask;
6006 bih = &model->collision_bih;
6010 nodenum = bih->rootnode;
6011 nodestack[nodestackpos++] = nodenum;
6012 while (nodestackpos)
6014 nodenum = nodestack[--nodestackpos];
6015 node = bih->nodes + nodenum;
6017 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6020 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6022 axis = node->type - BIH_SPLITX;
6023 if (start[axis] >= node->frontmin)
6024 nodestack[nodestackpos++] = node->front;
6025 if (start[axis] <= node->backmax)
6026 nodestack[nodestackpos++] = node->back;
6028 else if (node->type == BIH_UNORDERED)
6030 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6032 leaf = bih->leafs + node->children[axis];
6034 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6040 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6041 Collision_TracePointBrushFloat(trace, start, brush);
6043 case BIH_COLLISIONTRIANGLE:
6044 // collision triangle - skipped because they have no volume
6046 case BIH_RENDERTRIANGLE:
6047 // render triangle - skipped because they have no volume
6055 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)
6057 const bih_leaf_t *leaf;
6058 const bih_node_t *node;
6059 const colbrushf_t *brush;
6061 const texture_t *texture;
6062 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6063 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6064 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6069 if (VectorCompare(start, end))
6071 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6075 nodenum = bih->rootnode;
6077 memset(trace, 0, sizeof(*trace));
6078 trace->fraction = 1;
6079 trace->realfraction = 1;
6080 trace->hitsupercontentsmask = hitsupercontentsmask;
6083 nodestackline[nodestackpos][0] = start[0];
6084 nodestackline[nodestackpos][1] = start[1];
6085 nodestackline[nodestackpos][2] = start[2];
6086 nodestackline[nodestackpos][3] = end[0];
6087 nodestackline[nodestackpos][4] = end[1];
6088 nodestackline[nodestackpos][5] = end[2];
6089 nodestack[nodestackpos++] = nodenum;
6090 while (nodestackpos)
6092 nodenum = nodestack[--nodestackpos];
6093 node = bih->nodes + nodenum;
6094 VectorCopy(nodestackline[nodestackpos], nodestart);
6095 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6096 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]);
6097 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6099 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6101 // recurse children of the split
6102 axis = node->type - BIH_SPLITX;
6103 d1 = node->backmax - nodestart[axis];
6104 d2 = node->backmax - nodeend[axis];
6105 d3 = nodestart[axis] - node->frontmin;
6106 d4 = nodeend[axis] - node->frontmin;
6107 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6109 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;
6110 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;
6111 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;
6112 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6113 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;
6114 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;
6115 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;
6116 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6117 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;
6118 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;
6119 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;
6120 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6121 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6122 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6123 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6124 case 15: /* <<<< */ break;
6127 else if (node->type == BIH_UNORDERED)
6129 // calculate sweep bounds for this node
6130 // copy node bounds into local variables
6131 VectorCopy(node->mins, nodebigmins);
6132 VectorCopy(node->maxs, nodebigmaxs);
6133 // clip line to this node bounds
6134 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); }
6135 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); }
6136 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); }
6137 // some of the line intersected the enlarged node box
6138 // calculate sweep bounds for this node
6139 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]);
6140 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6142 leaf = bih->leafs + node->children[axis];
6143 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6148 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6149 Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6151 case BIH_COLLISIONTRIANGLE:
6152 if (!mod_q3bsp_curves_collisions.integer)
6154 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6155 texture = model->data_textures + leaf->textureindex;
6156 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);
6158 case BIH_RENDERTRIANGLE:
6159 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6160 texture = model->data_textures + leaf->textureindex;
6161 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);
6169 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)
6171 if (VectorCompare(start, end))
6173 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6176 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6179 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)
6182 const bih_leaf_t *leaf;
6183 const bih_node_t *node;
6184 const colbrushf_t *brush;
6186 const texture_t *texture;
6187 vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6188 vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6189 vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6190 int axis, nodenum, nodestackpos = 0, nodestack[1024];
6192 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6194 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6195 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6197 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6201 bih = &model->collision_bih;
6204 nodenum = bih->rootnode;
6206 // box trace, performed as brush trace
6207 memset(trace, 0, sizeof(*trace));
6208 trace->fraction = 1;
6209 trace->realfraction = 1;
6210 trace->hitsupercontentsmask = hitsupercontentsmask;
6212 // calculate tracebox-like parameters for efficient culling
6213 VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6214 VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6215 VectorSubtract(thisbrush_start->mins, start, startmins);
6216 VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6217 VectorSubtract(thisbrush_end->mins, end, endmins);
6218 VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6219 mins[0] = min(startmins[0], endmins[0]);
6220 mins[1] = min(startmins[1], endmins[1]);
6221 mins[2] = min(startmins[2], endmins[2]);
6222 maxs[0] = max(startmaxs[0], endmaxs[0]);
6223 maxs[1] = max(startmaxs[1], endmaxs[1]);
6224 maxs[2] = max(startmaxs[2], endmaxs[2]);
6227 nodestackline[nodestackpos][0] = start[0];
6228 nodestackline[nodestackpos][1] = start[1];
6229 nodestackline[nodestackpos][2] = start[2];
6230 nodestackline[nodestackpos][3] = end[0];
6231 nodestackline[nodestackpos][4] = end[1];
6232 nodestackline[nodestackpos][5] = end[2];
6233 nodestack[nodestackpos++] = nodenum;
6234 while (nodestackpos)
6236 nodenum = nodestack[--nodestackpos];
6237 node = bih->nodes + nodenum;
6238 VectorCopy(nodestackline[nodestackpos], nodestart);
6239 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6240 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];
6241 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6243 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6245 // recurse children of the split
6246 axis = node->type - BIH_SPLITX;
6247 d1 = node->backmax - nodestart[axis] - mins[axis];
6248 d2 = node->backmax - nodeend[axis] - mins[axis];
6249 d3 = nodestart[axis] - node->frontmin + maxs[axis];
6250 d4 = nodeend[axis] - node->frontmin + maxs[axis];
6251 switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6253 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;
6254 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;
6255 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;
6256 case 3: /* <<>> */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6257 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;
6258 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;
6259 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;
6260 case 7: /* <<<> */ f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6261 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;
6262 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;
6263 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;
6264 case 11: /* <<>< */ f = d3 / (d3 - d4); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6265 case 12: /* >><< */ VectorCopy(nodestart, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6266 case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy( nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6267 case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart, nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back; break;
6268 case 15: /* <<<< */ break;
6271 else if (node->type == BIH_UNORDERED)
6273 // calculate sweep bounds for this node
6274 // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6275 VectorSubtract(node->mins, maxs, nodebigmins);
6276 VectorSubtract(node->maxs, mins, nodebigmaxs);
6277 // clip line to this node bounds
6278 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); }
6279 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); }
6280 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); }
6281 // some of the line intersected the enlarged node box
6282 // calculate sweep bounds for this node
6283 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];
6284 for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6286 leaf = bih->leafs + node->children[axis];
6287 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6292 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6293 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6295 case BIH_COLLISIONTRIANGLE:
6296 if (!mod_q3bsp_curves_collisions.integer)
6298 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6299 texture = model->data_textures + leaf->textureindex;
6300 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);
6302 case BIH_RENDERTRIANGLE:
6303 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6304 texture = model->data_textures + leaf->textureindex;
6305 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);
6313 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)
6315 colboxbrushf_t thisbrush_start, thisbrush_end;
6316 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6318 // box trace, performed as brush trace
6319 VectorAdd(start, boxmins, boxstartmins);
6320 VectorAdd(start, boxmaxs, boxstartmaxs);
6321 VectorAdd(end, boxmins, boxendmins);
6322 VectorAdd(end, boxmaxs, boxendmaxs);
6323 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6324 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6325 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6329 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6332 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6333 return trace.startsupercontents;
6336 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)
6339 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6341 int hitsupercontents;
6342 VectorSet(end, start[0], start[1], model->normalmins[2]);
6344 memset(trace, 0, sizeof(*trace));
6345 trace->fraction = 1;
6346 trace->realfraction = 1;
6347 trace->hitsupercontentsmask = hitsupercontentsmask;
6349 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6350 hitsupercontents = trace->hitsupercontents;
6351 memset(trace, 0, sizeof(*trace));
6352 trace->fraction = 1;
6353 trace->realfraction = 1;
6354 trace->hitsupercontentsmask = hitsupercontentsmask;
6355 trace->startsupercontents = hitsupercontents;
6359 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6362 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6365 VectorSet(end, start[0], start[1], model->normalmins[2]);
6366 memset(&trace, 0, sizeof(trace));
6368 trace.realfraction = 1;
6369 trace.hitsupercontentsmask = 0;
6370 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6371 return trace.hitsupercontents;
6377 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6382 // find which leaf the point is in
6384 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6385 // point trace the brushes
6386 leaf = (mleaf_t *)node;
6387 for (i = 0;i < leaf->numleafbrushes;i++)
6389 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6390 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6392 brush->markframe = markframe;
6393 Collision_TracePointBrushFloat(trace, point, brush);
6396 // can't do point traces on curves (they have no thickness)
6399 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)
6401 int i, startside, endside;
6402 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6404 msurface_t *surface;
6407 // walk the tree until we hit a leaf, recursing for any split cases
6411 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6413 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6414 node = node->children[1];
6416 // abort if this part of the bsp tree can not be hit by this trace
6417 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6419 plane = node->plane;
6420 // axial planes are much more common than non-axial, so an optimized
6421 // axial case pays off here
6422 if (plane->type < 3)
6424 dist1 = start[plane->type] - plane->dist;
6425 dist2 = end[plane->type] - plane->dist;
6429 dist1 = DotProduct(start, plane->normal) - plane->dist;
6430 dist2 = DotProduct(end, plane->normal) - plane->dist;
6432 startside = dist1 < 0;
6433 endside = dist2 < 0;
6434 if (startside == endside)
6436 // most of the time the line fragment is on one side of the plane
6437 node = node->children[startside];
6441 // line crosses node plane, split the line
6442 dist1 = PlaneDiff(linestart, plane);
6443 dist2 = PlaneDiff(lineend, plane);
6444 midfrac = dist1 / (dist1 - dist2);
6445 VectorLerp(linestart, midfrac, lineend, mid);
6446 // take the near side first
6447 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6448 // if we found an impact on the front side, don't waste time
6449 // exploring the far side
6450 if (midfrac <= trace->realfraction)
6451 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6456 // abort if this part of the bsp tree can not be hit by this trace
6457 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6460 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6461 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6462 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6463 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6464 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6465 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6466 // line trace the brushes
6467 leaf = (mleaf_t *)node;
6469 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6472 for (i = 0;i < leaf->numleafbrushes;i++)
6474 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6475 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6477 brush->markframe = markframe;
6478 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6481 // can't do point traces on curves (they have no thickness)
6482 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6484 // line trace the curves
6485 for (i = 0;i < leaf->numleafsurfaces;i++)
6487 surface = model->data_surfaces + leaf->firstleafsurface[i];
6488 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6490 surface->deprecatedq3collisionmarkframe = markframe;
6491 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);
6497 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)
6503 msurface_t *surface;
6505 float nodesegmentmins[3], nodesegmentmaxs[3];
6506 // walk the tree until we hit a leaf, recursing for any split cases
6510 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6512 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6513 node = node->children[1];
6515 // abort if this part of the bsp tree can not be hit by this trace
6516 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6518 plane = node->plane;
6519 // axial planes are much more common than non-axial, so an optimized
6520 // axial case pays off here
6521 if (plane->type < 3)
6523 // this is an axial plane, compare bounding box directly to it and
6524 // recurse sides accordingly
6525 // recurse down node sides
6526 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6527 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6528 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6529 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6533 // this is a non-axial plane, so check if the start and end boxes
6534 // are both on one side of the plane to handle 'diagonal' cases
6535 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6539 // segment crosses plane
6540 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6543 // if sides == 0 then the trace itself is bogus (Not A Number values),
6544 // in this case we simply pretend the trace hit nothing
6546 return; // ERROR: NAN bounding box!
6547 // take whichever side the segment box is on
6548 node = node->children[sides - 1];
6551 // abort if this part of the bsp tree can not be hit by this trace
6552 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6554 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6555 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6556 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6557 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6558 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6559 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6561 leaf = (mleaf_t *)node;
6563 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6566 for (i = 0;i < leaf->numleafbrushes;i++)
6568 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6569 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6571 brush->markframe = markframe;
6572 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6575 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6577 for (i = 0;i < leaf->numleafsurfaces;i++)
6579 surface = model->data_surfaces + leaf->firstleafsurface[i];
6580 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6582 surface->deprecatedq3collisionmarkframe = markframe;
6583 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);
6590 static int markframe = 0;
6592 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)
6596 memset(trace, 0, sizeof(*trace));
6597 trace->fraction = 1;
6598 trace->realfraction = 1;
6599 trace->hitsupercontentsmask = hitsupercontentsmask;
6600 if (mod_collision_bih.integer)
6601 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6602 else if (model->brush.submodel)
6604 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6605 if (brush->colbrushf)
6606 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6609 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6612 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)
6615 float segmentmins[3], segmentmaxs[3];
6616 msurface_t *surface;
6619 if (VectorCompare(start, end))
6621 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6625 memset(trace, 0, sizeof(*trace));
6626 trace->fraction = 1;
6627 trace->realfraction = 1;
6628 trace->hitsupercontentsmask = hitsupercontentsmask;
6629 segmentmins[0] = min(start[0], end[0]) - 1;
6630 segmentmins[1] = min(start[1], end[1]) - 1;
6631 segmentmins[2] = min(start[2], end[2]) - 1;
6632 segmentmaxs[0] = max(start[0], end[0]) + 1;
6633 segmentmaxs[1] = max(start[1], end[1]) + 1;
6634 segmentmaxs[2] = max(start[2], end[2]) + 1;
6635 if (mod_collision_bih.integer)
6636 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6637 else if (model->brush.submodel)
6639 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6640 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6641 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6642 if (mod_q3bsp_curves_collisions.integer)
6643 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6644 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6645 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);
6648 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6651 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)
6653 float segmentmins[3], segmentmaxs[3];
6655 msurface_t *surface;
6658 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6660 if (VectorCompare(start->mins, end->mins))
6661 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6663 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6667 // box trace, performed as brush trace
6668 memset(trace, 0, sizeof(*trace));
6669 trace->fraction = 1;
6670 trace->realfraction = 1;
6671 trace->hitsupercontentsmask = hitsupercontentsmask;
6672 segmentmins[0] = min(start->mins[0], end->mins[0]);
6673 segmentmins[1] = min(start->mins[1], end->mins[1]);
6674 segmentmins[2] = min(start->mins[2], end->mins[2]);
6675 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6676 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6677 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6678 if (mod_collision_bih.integer)
6679 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6680 else if (model->brush.submodel)
6682 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6683 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6684 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6685 if (mod_q3bsp_curves_collisions.integer)
6686 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6687 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6688 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);
6691 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6694 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)
6696 colboxbrushf_t thisbrush_start, thisbrush_end;
6697 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6699 // box trace, performed as brush trace
6700 VectorAdd(start, boxmins, boxstartmins);
6701 VectorAdd(start, boxmaxs, boxstartmaxs);
6702 VectorAdd(end, boxmins, boxendmins);
6703 VectorAdd(end, boxmaxs, boxendmaxs);
6704 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6705 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6706 Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6709 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6712 int supercontents = 0;
6714 if (mod_collision_bih.integer)
6717 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6718 supercontents = trace.startsupercontents;
6720 // test if the point is inside each brush
6721 else if (model->brush.submodel)
6723 // submodels are effectively one leaf
6724 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6725 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6726 supercontents |= brush->colbrushf->supercontents;
6730 mnode_t *node = model->brush.data_nodes;
6732 // find which leaf the point is in
6734 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6735 leaf = (mleaf_t *)node;
6736 // now check the brushes in the leaf
6737 for (i = 0;i < leaf->numleafbrushes;i++)
6739 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6740 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6741 supercontents |= brush->colbrushf->supercontents;
6744 return supercontents;
6747 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)
6749 Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6753 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6761 int nummodelbrushes = model->nummodelbrushes;
6762 int nummodelsurfaces = model->nummodelsurfaces;
6764 const int *collisionelement3i;
6765 const float *collisionvertex3f;
6766 const int *renderelement3i;
6767 const float *rendervertex3f;
6768 bih_leaf_t *bihleafs;
6769 bih_node_t *bihnodes;
6771 int *temp_leafsortscratch;
6772 const msurface_t *surface;
6773 const q3mbrush_t *brush;
6775 // find out how many BIH leaf nodes we need
6777 if (userendersurfaces)
6779 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6780 bihnumleafs += surface->num_triangles;
6784 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6785 if (brush->colbrushf)
6787 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6789 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6790 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6792 bihnumleafs += surface->num_collisiontriangles;
6799 // allocate the memory for the BIH leaf nodes
6800 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6802 // now populate the BIH leaf nodes
6805 // add render surfaces
6806 renderelement3i = model->surfmesh.data_element3i;
6807 rendervertex3f = model->surfmesh.data_vertex3f;
6808 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6810 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6812 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6814 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6815 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6816 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6817 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6818 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6819 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6820 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6821 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6822 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6823 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6828 if (!userendersurfaces)
6830 // add collision brushes
6831 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6833 if (!brush->colbrushf)
6835 bihleafs[bihleafindex].type = BIH_BRUSH;
6836 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6837 bihleafs[bihleafindex].surfaceindex = -1;
6838 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6839 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6840 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6844 // add collision surfaces
6845 collisionelement3i = model->brush.data_collisionelement3i;
6846 collisionvertex3f = model->brush.data_collisionvertex3f;
6847 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6849 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6851 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6852 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6853 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6854 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6855 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6856 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6857 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6858 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6859 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6860 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6866 // allocate buffers for the produced and temporary data
6867 bihmaxnodes = bihnumleafs + 1;
6868 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6869 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6870 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6873 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6875 // we're done with the temporary data
6876 Mem_Free(temp_leafsort);
6878 // resize the BIH nodes array if it over-allocated
6879 if (out->maxnodes > out->numnodes)
6881 out->maxnodes = out->numnodes;
6882 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
6888 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6890 int supercontents = 0;
6891 if (nativecontents & CONTENTSQ3_SOLID)
6892 supercontents |= SUPERCONTENTS_SOLID;
6893 if (nativecontents & CONTENTSQ3_WATER)
6894 supercontents |= SUPERCONTENTS_WATER;
6895 if (nativecontents & CONTENTSQ3_SLIME)
6896 supercontents |= SUPERCONTENTS_SLIME;
6897 if (nativecontents & CONTENTSQ3_LAVA)
6898 supercontents |= SUPERCONTENTS_LAVA;
6899 if (nativecontents & CONTENTSQ3_BODY)
6900 supercontents |= SUPERCONTENTS_BODY;
6901 if (nativecontents & CONTENTSQ3_CORPSE)
6902 supercontents |= SUPERCONTENTS_CORPSE;
6903 if (nativecontents & CONTENTSQ3_NODROP)
6904 supercontents |= SUPERCONTENTS_NODROP;
6905 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6906 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6907 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6908 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6909 if (nativecontents & CONTENTSQ3_DONOTENTER)
6910 supercontents |= SUPERCONTENTS_DONOTENTER;
6911 if (nativecontents & CONTENTSQ3_BOTCLIP)
6912 supercontents |= SUPERCONTENTS_BOTCLIP;
6913 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6914 supercontents |= SUPERCONTENTS_OPAQUE;
6915 return supercontents;
6918 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6920 int nativecontents = 0;
6921 if (supercontents & SUPERCONTENTS_SOLID)
6922 nativecontents |= CONTENTSQ3_SOLID;
6923 if (supercontents & SUPERCONTENTS_WATER)
6924 nativecontents |= CONTENTSQ3_WATER;
6925 if (supercontents & SUPERCONTENTS_SLIME)
6926 nativecontents |= CONTENTSQ3_SLIME;
6927 if (supercontents & SUPERCONTENTS_LAVA)
6928 nativecontents |= CONTENTSQ3_LAVA;
6929 if (supercontents & SUPERCONTENTS_BODY)
6930 nativecontents |= CONTENTSQ3_BODY;
6931 if (supercontents & SUPERCONTENTS_CORPSE)
6932 nativecontents |= CONTENTSQ3_CORPSE;
6933 if (supercontents & SUPERCONTENTS_NODROP)
6934 nativecontents |= CONTENTSQ3_NODROP;
6935 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6936 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6937 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6938 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6939 if (supercontents & SUPERCONTENTS_DONOTENTER)
6940 nativecontents |= CONTENTSQ3_DONOTENTER;
6941 if (supercontents & SUPERCONTENTS_BOTCLIP)
6942 nativecontents |= CONTENTSQ3_BOTCLIP;
6943 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6944 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6945 return nativecontents;
6948 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6953 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6954 node = node->children[1];
6956 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6957 if (loadmodel->brush.num_leafs < numleafs)
6958 loadmodel->brush.num_leafs = numleafs;
6961 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6964 q3dheader_t *header;
6965 float corner[3], yawradius, modelradius;
6967 mod->modeldatatypestring = "Q3BSP";
6969 mod->type = mod_brushq3;
6970 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6973 header = (q3dheader_t *)buffer;
6974 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6975 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6977 i = LittleLong(header->version);
6978 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6979 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6981 mod->soundfromcenter = true;
6982 mod->TraceBox = Mod_Q3BSP_TraceBox;
6983 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
6984 mod->TraceLine = Mod_Q3BSP_TraceLine;
6985 mod->TracePoint = Mod_Q3BSP_TracePoint;
6986 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6987 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
6988 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6989 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6990 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6991 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6992 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6993 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6994 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6995 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6996 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6997 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6998 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6999 mod->brush.AmbientSoundLevelsForPoint = NULL;
7000 mod->brush.RoundUpToHullSize = NULL;
7001 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7002 mod->Draw = R_Q1BSP_Draw;
7003 mod->DrawDepth = R_Q1BSP_DrawDepth;
7004 mod->DrawDebug = R_Q1BSP_DrawDebug;
7005 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7006 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7007 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7008 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7009 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7010 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7011 mod->DrawLight = R_Q1BSP_DrawLight;
7013 mod_base = (unsigned char *)header;
7015 // swap all the lumps
7016 header->ident = LittleLong(header->ident);
7017 header->version = LittleLong(header->version);
7018 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7019 for (i = 0;i < lumps;i++)
7021 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7022 if((char *) bufferend < (char *) buffer + j)
7023 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7024 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7025 if((char *) bufferend < (char *) buffer + j)
7026 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7029 * NO, do NOT clear them!
7030 * they contain actual data referenced by other stuff.
7031 * Instead, before using the advertisements lump, check header->versio
7033 * Sorry, but otherwise it breaks memory of the first lump.
7034 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7036 header->lumps[i].fileofs = 0;
7037 header->lumps[i].filelen = 0;
7041 mod->brush.qw_md4sum = 0;
7042 mod->brush.qw_md4sum2 = 0;
7043 for (i = 0;i < lumps;i++)
7045 if (i == Q3LUMP_ENTITIES)
7047 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7048 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7050 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7052 // all this checksumming can take a while, so let's send keepalives here too
7053 CL_KeepaliveMessage(false);
7056 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7057 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7058 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7059 if (header->version == Q3BSPVERSION_IG)
7060 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7062 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7063 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7064 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7065 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7066 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7067 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7068 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7069 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7070 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7071 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7072 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7073 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7074 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7075 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7076 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7078 // the MakePortals code works fine on the q3bsp data as well
7079 if (mod_bsp_portalize.integer)
7080 Mod_Q1BSP_MakePortals();
7082 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7083 loadmodel->brush.supportwateralpha = true;
7085 // make a single combined shadow mesh to allow optimized shadow volume creation
7086 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7088 loadmodel->brush.num_leafs = 0;
7089 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7091 if (loadmodel->brush.numsubmodels)
7092 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7095 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7100 // duplicate the basic information
7101 dpsnprintf(name, sizeof(name), "*%i", i);
7102 mod = Mod_FindName(name, loadmodel->name);
7103 // copy the base model to this one
7105 // rename the clone back to its proper name
7106 strlcpy(mod->name, name, sizeof(mod->name));
7107 mod->brush.parentmodel = loadmodel;
7108 // textures and memory belong to the main model
7109 mod->texturepool = NULL;
7110 mod->mempool = NULL;
7111 mod->brush.GetPVS = NULL;
7112 mod->brush.FatPVS = NULL;
7113 mod->brush.BoxTouchingPVS = NULL;
7114 mod->brush.BoxTouchingLeafPVS = NULL;
7115 mod->brush.BoxTouchingVisibleLeafs = NULL;
7116 mod->brush.FindBoxClusters = NULL;
7117 mod->brush.LightPoint = NULL;
7118 mod->brush.AmbientSoundLevelsForPoint = NULL;
7120 mod->brush.submodel = i;
7121 if (loadmodel->brush.submodels)
7122 loadmodel->brush.submodels[i] = mod;
7124 // make the model surface list (used by shadowing/lighting)
7125 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7126 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7127 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7128 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7129 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7130 Mod_MakeSortedSurfaces(mod);
7132 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7133 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7134 // enlarge the bounding box to enclose all geometry of this model,
7135 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7136 // which can in turn mess up the farclip (as well as culling when
7137 // outside the level - an unimportant concern)
7139 //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]);
7140 for (j = 0;j < mod->nummodelsurfaces;j++)
7142 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7143 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7145 if (!surface->num_vertices)
7147 for (k = 0;k < surface->num_vertices;k++, v += 3)
7149 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7150 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7151 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7152 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7153 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7154 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7157 //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]);
7158 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7159 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7160 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7161 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7162 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7163 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7164 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7165 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7166 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7167 mod->yawmins[2] = mod->normalmins[2];
7168 mod->yawmaxs[2] = mod->normalmaxs[2];
7169 mod->radius = modelradius;
7170 mod->radius2 = modelradius * modelradius;
7172 // this gets altered below if sky or water is used
7173 mod->DrawSky = NULL;
7174 mod->DrawAddWaterPlanes = NULL;
7176 for (j = 0;j < mod->nummodelsurfaces;j++)
7177 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7179 if (j < mod->nummodelsurfaces)
7180 mod->DrawSky = R_Q1BSP_DrawSky;
7182 for (j = 0;j < mod->nummodelsurfaces;j++)
7183 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7185 if (j < mod->nummodelsurfaces)
7186 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7188 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7189 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7191 // generate VBOs and other shared data before cloning submodels
7196 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);
7199 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7201 int i = LittleLong(((int *)buffer)[1]);
7202 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7203 Mod_Q3BSP_Load(mod,buffer, bufferend);
7204 else if (i == Q2BSPVERSION)
7205 Mod_Q2BSP_Load(mod,buffer, bufferend);
7207 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7210 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7212 Host_Error("Mod_MAP_Load: not yet implemented");
7215 typedef struct objvertex_s
7226 static unsigned char nobsp_pvs[1] = {1};
7228 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7230 const char *textbase = (char *)buffer, *text = textbase;
7234 char materialname[MAX_QPATH];
7235 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7236 int index1, index2, index3;
7237 objvertex_t vfirst, vprev, vcurrent;
7240 int numtriangles = 0;
7241 int maxtriangles = 0;
7242 objvertex_t *vertices = NULL;
7244 int maxtextures = 0, numtextures = 0, textureindex = 0;
7245 int maxv = 0, numv = 1;
7246 int maxvt = 0, numvt = 1;
7247 int maxvn = 0, numvn = 1;
7248 char *texturenames = NULL;
7249 float dist, modelradius, modelyawradius, yawradius;
7256 objvertex_t *thisvertex = NULL;
7257 int vertexhashindex;
7258 int *vertexhashtable = NULL;
7259 objvertex_t *vertexhashdata = NULL;
7260 objvertex_t *vdata = NULL;
7261 int vertexhashsize = 0;
7262 int vertexhashcount = 0;
7263 skinfile_t *skinfiles = NULL;
7264 unsigned char *data = NULL;
7265 int *submodelfirstsurface;
7266 msurface_t *surface;
7267 msurface_t *tempsurfaces;
7269 memset(&vfirst, 0, sizeof(vfirst));
7270 memset(&vprev, 0, sizeof(vprev));
7271 memset(&vcurrent, 0, sizeof(vcurrent));
7273 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7275 loadmodel->modeldatatypestring = "OBJ";
7277 loadmodel->type = mod_obj;
7278 loadmodel->soundfromcenter = true;
7279 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7280 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7281 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7282 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7283 loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7284 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7285 loadmodel->brush.TraceLineOfSight = NULL;
7286 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7287 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7288 loadmodel->brush.GetPVS = NULL;
7289 loadmodel->brush.FatPVS = NULL;
7290 loadmodel->brush.BoxTouchingPVS = NULL;
7291 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7292 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7293 loadmodel->brush.FindBoxClusters = NULL;
7294 loadmodel->brush.LightPoint = NULL;
7295 loadmodel->brush.FindNonSolidLocation = NULL;
7296 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7297 loadmodel->brush.RoundUpToHullSize = NULL;
7298 loadmodel->brush.PointInLeaf = NULL;
7299 loadmodel->Draw = R_Q1BSP_Draw;
7300 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7301 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7302 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7303 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7304 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7305 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7306 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7307 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7308 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7310 skinfiles = Mod_LoadSkinFiles();
7311 if (loadmodel->numskins < 1)
7312 loadmodel->numskins = 1;
7314 // make skinscenes for the skins (no groups)
7315 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7316 for (i = 0;i < loadmodel->numskins;i++)
7318 loadmodel->skinscenes[i].firstframe = i;
7319 loadmodel->skinscenes[i].framecount = 1;
7320 loadmodel->skinscenes[i].loop = true;
7321 loadmodel->skinscenes[i].framerate = 10;
7327 // we always have model 0, i.e. the first "submodel"
7328 loadmodel->brush.numsubmodels = 1;
7330 // parse the OBJ text now
7333 static char emptyarg[1] = "";
7338 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7339 line[linelen] = text[linelen];
7341 for (argc = 0;argc < 4;argc++)
7342 argv[argc] = emptyarg;
7345 while (*s == ' ' || *s == '\t')
7355 while (*s == ' ' || *s == '\t')
7365 if (argv[0][0] == '#')
7367 if (!strcmp(argv[0], "v"))
7371 maxv = max(maxv * 2, 1024);
7372 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7374 v[numv*3+0] = atof(argv[1]);
7375 v[numv*3+2] = atof(argv[2]);
7376 v[numv*3+1] = atof(argv[3]);
7379 else if (!strcmp(argv[0], "vt"))
7383 maxvt = max(maxvt * 2, 1024);
7384 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7386 vt[numvt*2+0] = atof(argv[1]);
7387 vt[numvt*2+1] = 1-atof(argv[2]);
7390 else if (!strcmp(argv[0], "vn"))
7394 maxvn = max(maxvn * 2, 1024);
7395 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7397 vn[numvn*3+0] = atof(argv[1]);
7398 vn[numvn*3+2] = atof(argv[2]);
7399 vn[numvn*3+1] = atof(argv[3]);
7402 else if (!strcmp(argv[0], "f"))
7406 if (maxtextures <= numtextures)
7408 maxtextures = max(maxtextures * 2, 256);
7409 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7411 textureindex = numtextures++;
7412 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7414 for (j = 1;j < argc;j++)
7416 index1 = atoi(argv[j]);
7417 while(argv[j][0] && argv[j][0] != '/')
7421 index2 = atoi(argv[j]);
7422 while(argv[j][0] && argv[j][0] != '/')
7426 index3 = atoi(argv[j]);
7427 // negative refers to a recent vertex
7428 // zero means not specified
7429 // positive means an absolute vertex index
7431 index1 = numv - index1;
7433 index2 = numvt - index2;
7435 index3 = numvn - index3;
7436 vcurrent.nextindex = -1;
7437 vcurrent.textureindex = textureindex;
7438 vcurrent.submodelindex = submodelindex;
7439 if (v && index1 >= 0 && index1 < numv)
7440 VectorCopy(v + 3*index1, vcurrent.v);
7441 if (vt && index2 >= 0 && index2 < numvt)
7442 Vector2Copy(vt + 2*index2, vcurrent.vt);
7443 if (vn && index3 >= 0 && index3 < numvn)
7444 VectorCopy(vn + 3*index3, vcurrent.vn);
7445 if (numtriangles == 0)
7447 VectorCopy(vcurrent.v, mins);
7448 VectorCopy(vcurrent.v, maxs);
7452 mins[0] = min(mins[0], vcurrent.v[0]);
7453 mins[1] = min(mins[1], vcurrent.v[1]);
7454 mins[2] = min(mins[2], vcurrent.v[2]);
7455 maxs[0] = max(maxs[0], vcurrent.v[0]);
7456 maxs[1] = max(maxs[1], vcurrent.v[1]);
7457 maxs[2] = max(maxs[2], vcurrent.v[2]);
7463 if (maxtriangles <= numtriangles)
7465 maxtriangles = max(maxtriangles * 2, 32768);
7466 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7468 vertices[numtriangles*3+0] = vfirst;
7469 vertices[numtriangles*3+1] = vprev;
7470 vertices[numtriangles*3+2] = vcurrent;
7476 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7478 submodelindex = atof(argv[1]);
7479 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7481 else if (!strcmp(argv[0], "usemtl"))
7483 for (i = 0;i < numtextures;i++)
7484 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7486 if (i < numtextures)
7490 if (maxtextures <= numtextures)
7492 maxtextures = max(maxtextures * 2, 256);
7493 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7495 textureindex = numtextures++;
7496 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7501 // now that we have the OBJ data loaded as-is, we can convert it
7503 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7504 VectorCopy(mins, loadmodel->normalmins);
7505 VectorCopy(maxs, loadmodel->normalmaxs);
7506 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7507 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7508 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7509 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7510 modelradius = modelyawradius + modelradius * modelradius;
7511 modelyawradius = sqrt(modelyawradius);
7512 modelradius = sqrt(modelradius);
7513 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7514 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7515 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7516 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7517 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7518 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7519 loadmodel->radius = modelradius;
7520 loadmodel->radius2 = modelradius * modelradius;
7522 // allocate storage for triangles
7523 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7524 // allocate vertex hash structures to build an optimal vertex subset
7525 vertexhashsize = numtriangles*2;
7526 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7527 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7528 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7529 vertexhashcount = 0;
7531 // gather surface stats for assigning vertex/triangle ranges
7535 loadmodel->num_surfaces = 0;
7536 // allocate storage for the worst case number of surfaces, later we resize
7537 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7538 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7539 surface = tempsurfaces;
7540 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7542 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7543 for (textureindex = 0;textureindex < numtextures;textureindex++)
7545 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7547 thisvertex = vertices + vertexindex;
7548 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7551 // skip the surface creation if there are no triangles for it
7552 if (vertexindex == numtriangles*3)
7554 // create a surface for these vertices
7555 surfacevertices = 0;
7556 surfaceelements = 0;
7557 // we hack in a texture index in the surface to be fixed up later...
7558 surface->texture = (texture_t *)((size_t)textureindex);
7559 // calculate bounds as we go
7560 VectorCopy(thisvertex->v, surface->mins);
7561 VectorCopy(thisvertex->v, surface->maxs);
7562 for (;vertexindex < numtriangles*3;vertexindex++)
7564 thisvertex = vertices + vertexindex;
7565 if (thisvertex->submodelindex != submodelindex)
7567 if (thisvertex->textureindex != textureindex)
7569 // add vertex to surface bounds
7570 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7571 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7572 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7573 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7574 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7575 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7576 // add the vertex if it is not found in the merged set, and
7577 // get its index (triangle element) for the surface
7578 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7579 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7581 vdata = vertexhashdata + i;
7582 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7587 i = vertexhashcount++;
7588 vdata = vertexhashdata + i;
7589 *vdata = *thisvertex;
7590 vdata->nextindex = vertexhashtable[vertexhashindex];
7591 vertexhashtable[vertexhashindex] = i;
7594 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7597 surfacetriangles = surfaceelements / 3;
7598 surface->num_vertices = surfacevertices;
7599 surface->num_triangles = surfacetriangles;
7600 surface->num_firstvertex = firstvertex;
7601 surface->num_firsttriangle = firsttriangle;
7602 firstvertex += surface->num_vertices;
7603 firsttriangle += surface->num_triangles;
7605 loadmodel->num_surfaces++;
7608 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7609 numvertices = firstvertex;
7610 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7611 tempsurfaces = NULL;
7613 // allocate storage for final mesh data
7614 loadmodel->num_textures = numtextures * loadmodel->numskins;
7615 loadmodel->num_texturesperskin = numtextures;
7616 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 *));
7617 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7618 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7619 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7620 loadmodel->surfmesh.num_vertices = numvertices;
7621 loadmodel->surfmesh.num_triangles = numtriangles;
7622 if (r_enableshadowvolumes.integer)
7623 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7624 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7625 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7626 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7627 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7628 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7629 if (loadmodel->surfmesh.num_vertices <= 65536)
7630 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7632 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7634 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7635 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7636 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7639 // load the textures
7640 for (textureindex = 0;textureindex < numtextures;textureindex++)
7641 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7642 Mod_FreeSkinFiles(skinfiles);
7644 // set the surface textures to their real values now that we loaded them...
7645 for (i = 0;i < loadmodel->num_surfaces;i++)
7646 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7650 Mem_Free(texturenames);
7654 Mem_Free(vertexhashtable);
7655 Mem_Free(vertexhashdata);
7657 // make a single combined shadow mesh to allow optimized shadow volume creation
7658 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7660 // compute all the mesh information that was not loaded from the file
7661 if (loadmodel->surfmesh.data_element3s)
7662 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7663 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7664 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7665 // generate normals if the file did not have them
7666 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7667 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);
7668 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);
7669 if (loadmodel->surfmesh.data_neighbor3i)
7670 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7672 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7673 loadmodel->brush.num_visleafs = 1;
7674 loadmodel->brush.num_leafs = 1;
7675 loadmodel->brush.num_nodes = 0;
7676 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7677 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7678 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7679 loadmodel->brush.num_pvsclusters = 1;
7680 loadmodel->brush.num_pvsclusterbytes = 1;
7681 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7682 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7683 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7684 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7685 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7686 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7687 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7688 loadmodel->brush.data_leafs->clusterindex = 0;
7689 loadmodel->brush.data_leafs->areaindex = 0;
7690 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7691 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7692 loadmodel->brush.data_leafs->numleafbrushes = 0;
7693 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7694 loadmodel->brush.supportwateralpha = true;
7696 if (loadmodel->brush.numsubmodels)
7697 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7700 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7705 // duplicate the basic information
7706 dpsnprintf(name, sizeof(name), "*%i", i);
7707 mod = Mod_FindName(name, loadmodel->name);
7708 // copy the base model to this one
7710 // rename the clone back to its proper name
7711 strlcpy(mod->name, name, sizeof(mod->name));
7712 mod->brush.parentmodel = loadmodel;
7713 // textures and memory belong to the main model
7714 mod->texturepool = NULL;
7715 mod->mempool = NULL;
7716 mod->brush.GetPVS = NULL;
7717 mod->brush.FatPVS = NULL;
7718 mod->brush.BoxTouchingPVS = NULL;
7719 mod->brush.BoxTouchingLeafPVS = NULL;
7720 mod->brush.BoxTouchingVisibleLeafs = NULL;
7721 mod->brush.FindBoxClusters = NULL;
7722 mod->brush.LightPoint = NULL;
7723 mod->brush.AmbientSoundLevelsForPoint = NULL;
7725 mod->brush.submodel = i;
7726 if (loadmodel->brush.submodels)
7727 loadmodel->brush.submodels[i] = mod;
7729 // make the model surface list (used by shadowing/lighting)
7730 mod->firstmodelsurface = submodelfirstsurface[i];
7731 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7732 mod->firstmodelbrush = 0;
7733 mod->nummodelbrushes = 0;
7734 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7735 Mod_MakeSortedSurfaces(mod);
7737 VectorClear(mod->normalmins);
7738 VectorClear(mod->normalmaxs);
7740 for (j = 0;j < mod->nummodelsurfaces;j++)
7742 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7743 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7745 if (!surface->num_vertices)
7750 VectorCopy(v, mod->normalmins);
7751 VectorCopy(v, mod->normalmaxs);
7753 for (k = 0;k < surface->num_vertices;k++, v += 3)
7755 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7756 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7757 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7758 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7759 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7760 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7763 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7764 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7765 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7766 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7767 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7768 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7769 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7770 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7771 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7772 mod->yawmins[2] = mod->normalmins[2];
7773 mod->yawmaxs[2] = mod->normalmaxs[2];
7774 mod->radius = modelradius;
7775 mod->radius2 = modelradius * modelradius;
7777 // this gets altered below if sky or water is used
7778 mod->DrawSky = NULL;
7779 mod->DrawAddWaterPlanes = NULL;
7781 for (j = 0;j < mod->nummodelsurfaces;j++)
7782 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7784 if (j < mod->nummodelsurfaces)
7785 mod->DrawSky = R_Q1BSP_DrawSky;
7787 for (j = 0;j < mod->nummodelsurfaces;j++)
7788 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7790 if (j < mod->nummodelsurfaces)
7791 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7793 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
7794 mod->render_bih = mod->collision_bih;
7796 // generate VBOs and other shared data before cloning submodels
7801 Mem_Free(submodelfirstsurface);
7803 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);
7806 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
7808 // we already have done PVS culling at this point...
7809 // so we don't need to do it again.
7812 vec3_t testorigin, mins, maxs;
7814 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
7815 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
7816 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
7818 if(model->brush.TraceLineOfSight(model, eye, testorigin))
7821 // expand the box a little
7822 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
7823 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
7824 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
7825 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
7826 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
7827 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
7829 for(i = 0; i != numsamples; ++i)
7831 testorigin[0] = lhrandom(mins[0], maxs[0]);
7832 testorigin[1] = lhrandom(mins[1], maxs[1]);
7833 testorigin[2] = lhrandom(mins[2], maxs[2]);
7835 if(model->brush.TraceLineOfSight(model, eye, testorigin))