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 r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
31 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)"};
32 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)"};
33 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)"};
34 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
35 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
36 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)"};
37 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)"};
38 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)"};
39 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
40 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
41 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)"};
42 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)"};
43 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
44 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
45 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, ..."};
46 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)"};
47 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
48 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces"};
49 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
50 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
52 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)"};
53 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"};
54 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"};
56 static texture_t mod_q1bsp_texture_solid;
57 static texture_t mod_q1bsp_texture_sky;
58 static texture_t mod_q1bsp_texture_lava;
59 static texture_t mod_q1bsp_texture_slime;
60 static texture_t mod_q1bsp_texture_water;
62 void Mod_BrushInit(void)
64 // Cvar_RegisterVariable(&r_subdivide_size);
65 Cvar_RegisterVariable(&r_novis);
66 Cvar_RegisterVariable(&r_nosurftextures);
67 Cvar_RegisterVariable(&r_subdivisions_tolerance);
68 Cvar_RegisterVariable(&r_subdivisions_mintess);
69 Cvar_RegisterVariable(&r_subdivisions_maxtess);
70 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
71 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
72 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
73 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
74 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
75 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
76 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
77 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
78 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
79 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
80 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
81 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
82 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
83 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
84 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
85 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
86 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
87 Cvar_RegisterVariable(&mod_collision_bih);
88 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
90 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
91 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
92 mod_q1bsp_texture_solid.surfaceflags = 0;
93 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
95 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
96 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
97 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
98 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
100 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
101 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
102 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
103 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
105 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
106 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
107 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
108 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
110 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
111 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
112 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
113 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
116 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
123 // LordHavoc: modified to start at first clip node,
124 // in other words: first node of the (sub)model
125 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
127 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
129 return (mleaf_t *)node;
132 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
136 leaf = Mod_Q1BSP_PointInLeaf(model, p);
139 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
142 memcpy(out, leaf->ambient_sound_level, i);
148 memset(out, 0, outsize);
151 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
154 int nodestackindex = 0;
155 mnode_t *node, *nodestack[1024];
156 if (!model->brush.num_pvsclusters)
158 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
164 // node - recurse down the BSP tree
165 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
169 return -1; // ERROR: NAN bounding box!
170 // box is on one side of plane, take that path
171 node = node->children[sides-1];
175 // box crosses plane, take one path and remember the other
176 if (nodestackindex < 1024)
177 nodestack[nodestackindex++] = node->children[0];
178 node = node->children[1];
184 // leaf - add clusterindex to list
185 if (numclusters < maxclusters)
186 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
190 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
194 if (nodestackindex < 1024)
195 nodestack[nodestackindex++] = node->children[0];
196 node = node->children[1];
201 // leaf - add clusterindex to list
202 if (numclusters < maxclusters)
203 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
208 // try another path we didn't take earlier
209 if (nodestackindex == 0)
211 node = nodestack[--nodestackindex];
213 // return number of clusters found (even if more than the maxclusters)
217 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
219 int nodestackindex = 0;
220 mnode_t *node, *nodestack[1024];
221 if (!model->brush.num_pvsclusters)
223 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
229 // node - recurse down the BSP tree
230 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
234 return -1; // ERROR: NAN bounding box!
235 // box is on one side of plane, take that path
236 node = node->children[sides-1];
240 // box crosses plane, take one path and remember the other
241 if (nodestackindex < 1024)
242 nodestack[nodestackindex++] = node->children[0];
243 node = node->children[1];
249 // leaf - check cluster bit
250 int clusterindex = ((mleaf_t *)node)->clusterindex;
251 if (CHECKPVSBIT(pvs, clusterindex))
253 // it is visible, return immediately with the news
258 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
262 if (nodestackindex < 1024)
263 nodestack[nodestackindex++] = node->children[0];
264 node = node->children[1];
269 // leaf - check cluster bit
270 int clusterindex = ((mleaf_t *)node)->clusterindex;
271 if (CHECKPVSBIT(pvs, clusterindex))
273 // it is visible, return immediately with the news
279 // nothing to see here, try another path we didn't take earlier
280 if (nodestackindex == 0)
282 node = nodestack[--nodestackindex];
288 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
290 int nodestackindex = 0;
291 mnode_t *node, *nodestack[1024];
292 if (!model->brush.num_leafs)
294 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
300 // node - recurse down the BSP tree
301 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
305 return -1; // ERROR: NAN bounding box!
306 // box is on one side of plane, take that path
307 node = node->children[sides-1];
311 // box crosses plane, take one path and remember the other
312 if (nodestackindex < 1024)
313 nodestack[nodestackindex++] = node->children[0];
314 node = node->children[1];
320 // leaf - check cluster bit
321 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
322 if (CHECKPVSBIT(pvs, clusterindex))
324 // it is visible, return immediately with the news
329 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
333 if (nodestackindex < 1024)
334 nodestack[nodestackindex++] = node->children[0];
335 node = node->children[1];
340 // leaf - check cluster bit
341 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
342 if (CHECKPVSBIT(pvs, clusterindex))
344 // it is visible, return immediately with the news
350 // nothing to see here, try another path we didn't take earlier
351 if (nodestackindex == 0)
353 node = nodestack[--nodestackindex];
359 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
361 int nodestackindex = 0;
362 mnode_t *node, *nodestack[1024];
363 if (!model->brush.num_leafs)
365 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
371 // node - recurse down the BSP tree
372 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
376 return -1; // ERROR: NAN bounding box!
377 // box is on one side of plane, take that path
378 node = node->children[sides-1];
382 // box crosses plane, take one path and remember the other
383 if (nodestackindex < 1024)
384 nodestack[nodestackindex++] = node->children[0];
385 node = node->children[1];
391 // leaf - check if it is visible
392 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
394 // it is visible, return immediately with the news
399 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
403 if (nodestackindex < 1024)
404 nodestack[nodestackindex++] = node->children[0];
405 node = node->children[1];
410 // leaf - check if it is visible
411 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
413 // it is visible, return immediately with the news
419 // nothing to see here, try another path we didn't take earlier
420 if (nodestackindex == 0)
422 node = nodestack[--nodestackindex];
428 typedef struct findnonsolidlocationinfo_s
431 vec3_t absmin, absmax;
437 findnonsolidlocationinfo_t;
439 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
442 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
444 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
445 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
446 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
447 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
448 VectorSubtract(vert[1], vert[0], edge[0]);
449 VectorSubtract(vert[2], vert[1], edge[1]);
450 CrossProduct(edge[1], edge[0], facenormal);
451 if (facenormal[0] || facenormal[1] || facenormal[2])
453 VectorNormalize(facenormal);
454 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
455 if (f <= info->bestdist && f >= -info->bestdist)
457 VectorSubtract(vert[0], vert[2], edge[2]);
458 VectorNormalize(edge[0]);
459 VectorNormalize(edge[1]);
460 VectorNormalize(edge[2]);
461 CrossProduct(facenormal, edge[0], edgenormal[0]);
462 CrossProduct(facenormal, edge[1], edgenormal[1]);
463 CrossProduct(facenormal, edge[2], edgenormal[2]);
465 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
466 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
467 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
469 // we got lucky, the center is within the face
470 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
474 if (info->bestdist > dist)
476 info->bestdist = dist;
477 VectorScale(facenormal, (info->radius - -dist), info->nudge);
482 if (info->bestdist > dist)
484 info->bestdist = dist;
485 VectorScale(facenormal, (info->radius - dist), info->nudge);
491 // check which edge or vertex the center is nearest
492 for (i = 0;i < 3;i++)
494 f = DotProduct(info->center, edge[i]);
495 if (f >= DotProduct(vert[0], edge[i])
496 && f <= DotProduct(vert[1], edge[i]))
499 VectorMA(info->center, -f, edge[i], point);
500 dist = sqrt(DotProduct(point, point));
501 if (info->bestdist > dist)
503 info->bestdist = dist;
504 VectorScale(point, (info->radius / dist), info->nudge);
506 // skip both vertex checks
507 // (both are further away than this edge)
512 // not on edge, check first vertex of edge
513 VectorSubtract(info->center, vert[i], point);
514 dist = sqrt(DotProduct(point, point));
515 if (info->bestdist > dist)
517 info->bestdist = dist;
518 VectorScale(point, (info->radius / dist), info->nudge);
527 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
529 int surfacenum, k, *mark;
531 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
533 surface = info->model->data_surfaces + *mark;
534 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
536 if(surface->deprecatedq3num_bboxstride > 0)
539 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
540 for(i = 0; i < cnt; ++i)
542 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
544 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
546 tri = i * surface->deprecatedq3num_bboxstride + k;
547 if(tri >= surface->num_triangles)
549 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
556 for (k = 0;k < surface->num_triangles;k++)
558 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
565 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
569 float f = PlaneDiff(info->center, node->plane);
570 if (f >= -info->bestdist)
571 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
572 if (f <= info->bestdist)
573 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
577 if (((mleaf_t *)node)->numleafsurfaces)
578 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
582 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
585 findnonsolidlocationinfo_t info;
591 VectorCopy(in, info.center);
592 info.radius = radius;
597 VectorClear(info.nudge);
598 info.bestdist = radius;
599 VectorCopy(info.center, info.absmin);
600 VectorCopy(info.center, info.absmax);
601 info.absmin[0] -= info.radius + 1;
602 info.absmin[1] -= info.radius + 1;
603 info.absmin[2] -= info.radius + 1;
604 info.absmax[0] += info.radius + 1;
605 info.absmax[1] += info.radius + 1;
606 info.absmax[2] += info.radius + 1;
607 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
608 VectorAdd(info.center, info.nudge, info.center);
610 while (info.bestdist < radius && ++i < 10);
611 VectorCopy(info.center, out);
614 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
616 switch(nativecontents)
621 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
623 return SUPERCONTENTS_WATER;
625 return SUPERCONTENTS_SLIME;
627 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
629 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
634 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
636 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
637 return CONTENTS_SOLID;
638 if (supercontents & SUPERCONTENTS_SKY)
640 if (supercontents & SUPERCONTENTS_LAVA)
641 return CONTENTS_LAVA;
642 if (supercontents & SUPERCONTENTS_SLIME)
643 return CONTENTS_SLIME;
644 if (supercontents & SUPERCONTENTS_WATER)
645 return CONTENTS_WATER;
646 return CONTENTS_EMPTY;
649 typedef struct RecursiveHullCheckTraceInfo_s
651 // the hull we're tracing through
654 // the trace structure to fill in
657 // start, end, and end - start (in model space)
662 RecursiveHullCheckTraceInfo_t;
664 // 1/32 epsilon to keep floating point happy
665 #define DIST_EPSILON (0.03125)
667 #define HULLCHECKSTATE_EMPTY 0
668 #define HULLCHECKSTATE_SOLID 1
669 #define HULLCHECKSTATE_DONE 2
671 extern cvar_t collision_prefernudgedfraction;
672 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
674 // status variables, these don't need to be saved on the stack when
675 // recursing... but are because this should be thread-safe
676 // (note: tracing against a bbox is not thread-safe, yet)
681 // variables that need to be stored on the stack when recursing
686 // LordHavoc: a goto! everyone flee in terror... :)
691 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
692 if (!t->trace->startfound)
694 t->trace->startfound = true;
695 t->trace->startsupercontents |= num;
697 if (num & SUPERCONTENTS_LIQUIDSMASK)
698 t->trace->inwater = true;
700 t->trace->inopen = true;
701 if (num & SUPERCONTENTS_SOLID)
702 t->trace->hittexture = &mod_q1bsp_texture_solid;
703 else if (num & SUPERCONTENTS_SKY)
704 t->trace->hittexture = &mod_q1bsp_texture_sky;
705 else if (num & SUPERCONTENTS_LAVA)
706 t->trace->hittexture = &mod_q1bsp_texture_lava;
707 else if (num & SUPERCONTENTS_SLIME)
708 t->trace->hittexture = &mod_q1bsp_texture_slime;
710 t->trace->hittexture = &mod_q1bsp_texture_water;
711 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
712 t->trace->hitsupercontents = num;
713 if (num & t->trace->hitsupercontentsmask)
715 // if the first leaf is solid, set startsolid
716 if (t->trace->allsolid)
717 t->trace->startsolid = true;
718 #if COLLISIONPARANOID >= 3
721 return HULLCHECKSTATE_SOLID;
725 t->trace->allsolid = false;
726 #if COLLISIONPARANOID >= 3
729 return HULLCHECKSTATE_EMPTY;
733 // find the point distances
734 node = t->hull->clipnodes + num;
736 plane = t->hull->planes + node->planenum;
739 t1 = p1[plane->type] - plane->dist;
740 t2 = p2[plane->type] - plane->dist;
744 t1 = DotProduct (plane->normal, p1) - plane->dist;
745 t2 = DotProduct (plane->normal, p2) - plane->dist;
752 #if COLLISIONPARANOID >= 3
755 num = node->children[1];
764 #if COLLISIONPARANOID >= 3
767 num = node->children[0];
773 // the line intersects, find intersection point
774 // LordHavoc: this uses the original trace for maximum accuracy
775 #if COLLISIONPARANOID >= 3
780 t1 = t->start[plane->type] - plane->dist;
781 t2 = t->end[plane->type] - plane->dist;
785 t1 = DotProduct (plane->normal, t->start) - plane->dist;
786 t2 = DotProduct (plane->normal, t->end) - plane->dist;
789 midf = t1 / (t1 - t2);
790 midf = bound(p1f, midf, p2f);
791 VectorMA(t->start, midf, t->dist, mid);
793 // recurse both sides, front side first
794 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
795 // if this side is not empty, return what it is (solid or done)
796 if (ret != HULLCHECKSTATE_EMPTY)
799 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
800 // if other side is not solid, return what it is (empty or done)
801 if (ret != HULLCHECKSTATE_SOLID)
804 // front is air and back is solid, this is the impact point...
807 t->trace->plane.dist = -plane->dist;
808 VectorNegate (plane->normal, t->trace->plane.normal);
812 t->trace->plane.dist = plane->dist;
813 VectorCopy (plane->normal, t->trace->plane.normal);
816 // calculate the true fraction
817 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
818 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
819 midf = t1 / (t1 - t2);
820 t->trace->realfraction = bound(0, midf, 1);
822 // calculate the return fraction which is nudged off the surface a bit
823 midf = (t1 - DIST_EPSILON) / (t1 - t2);
824 t->trace->fraction = bound(0, midf, 1);
826 if (collision_prefernudgedfraction.integer)
827 t->trace->realfraction = t->trace->fraction;
829 #if COLLISIONPARANOID >= 3
832 return HULLCHECKSTATE_DONE;
835 //#if COLLISIONPARANOID < 2
836 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
839 mclipnode_t *nodes = t->hull->clipnodes;
840 mplane_t *planes = t->hull->planes;
842 VectorCopy(t->start, point);
845 plane = planes + nodes[num].planenum;
846 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
848 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
849 t->trace->startsupercontents |= num;
850 if (num & SUPERCONTENTS_LIQUIDSMASK)
851 t->trace->inwater = true;
853 t->trace->inopen = true;
854 if (num & t->trace->hitsupercontentsmask)
856 t->trace->allsolid = t->trace->startsolid = true;
857 return HULLCHECKSTATE_SOLID;
861 t->trace->allsolid = t->trace->startsolid = false;
862 return HULLCHECKSTATE_EMPTY;
867 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)
869 RecursiveHullCheckTraceInfo_t rhc;
871 memset(&rhc, 0, sizeof(rhc));
872 memset(trace, 0, sizeof(trace_t));
874 rhc.trace->fraction = 1;
875 rhc.trace->realfraction = 1;
876 rhc.trace->allsolid = true;
877 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
878 VectorCopy(start, rhc.start);
879 VectorCopy(start, rhc.end);
880 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
883 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)
885 RecursiveHullCheckTraceInfo_t rhc;
887 if (VectorCompare(start, end))
889 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
893 memset(&rhc, 0, sizeof(rhc));
894 memset(trace, 0, sizeof(trace_t));
896 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
897 rhc.trace->fraction = 1;
898 rhc.trace->realfraction = 1;
899 rhc.trace->allsolid = true;
900 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
901 VectorCopy(start, rhc.start);
902 VectorCopy(end, rhc.end);
903 VectorSubtract(rhc.end, rhc.start, rhc.dist);
904 #if COLLISIONPARANOID >= 2
905 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]);
906 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
911 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
912 memset(&testtrace, 0, sizeof(trace_t));
913 rhc.trace = &testtrace;
914 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
915 rhc.trace->fraction = 1;
916 rhc.trace->realfraction = 1;
917 rhc.trace->allsolid = true;
918 VectorCopy(test, rhc.start);
919 VectorCopy(test, rhc.end);
920 VectorClear(rhc.dist);
921 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
922 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
923 if (!trace->startsolid && testtrace.startsolid)
924 Con_Printf(" - ended in solid!\n");
928 if (VectorLength2(rhc.dist))
929 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
931 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
935 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)
937 // this function currently only supports same size start and end
939 RecursiveHullCheckTraceInfo_t rhc;
941 if (VectorCompare(boxmins, boxmaxs))
943 if (VectorCompare(start, end))
944 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
946 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
950 memset(&rhc, 0, sizeof(rhc));
951 memset(trace, 0, sizeof(trace_t));
953 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
954 rhc.trace->fraction = 1;
955 rhc.trace->realfraction = 1;
956 rhc.trace->allsolid = true;
957 VectorSubtract(boxmaxs, boxmins, boxsize);
959 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
960 else if (model->brush.ishlbsp)
962 // LordHavoc: this has to have a minor tolerance (the .1) because of
963 // minor float precision errors from the box being transformed around
964 if (boxsize[0] < 32.1)
966 if (boxsize[2] < 54) // pick the nearest of 36 or 72
967 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
969 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
972 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
976 // LordHavoc: this has to have a minor tolerance (the .1) because of
977 // minor float precision errors from the box being transformed around
978 if (boxsize[0] < 32.1)
979 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
981 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
983 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
984 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
985 VectorSubtract(rhc.end, rhc.start, rhc.dist);
986 #if COLLISIONPARANOID >= 2
987 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]);
988 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
993 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
994 memset(&testtrace, 0, sizeof(trace_t));
995 rhc.trace = &testtrace;
996 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
997 rhc.trace->fraction = 1;
998 rhc.trace->realfraction = 1;
999 rhc.trace->allsolid = true;
1000 VectorCopy(test, rhc.start);
1001 VectorCopy(test, rhc.end);
1002 VectorClear(rhc.dist);
1003 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1004 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1005 if (!trace->startsolid && testtrace.startsolid)
1006 Con_Printf(" - ended in solid!\n");
1010 if (VectorLength2(rhc.dist))
1011 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1013 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1017 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1019 int num = model->brushq1.hulls[0].firstclipnode;
1021 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1022 mplane_t *planes = model->brushq1.hulls[0].planes;
1025 plane = planes + nodes[num].planenum;
1026 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1028 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1031 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)
1035 colplanef_t cbox_planes[6];
1037 cbox.hasaabbplanes = true;
1038 cbox.supercontents = boxsupercontents;
1041 cbox.numtriangles = 0;
1042 cbox.planes = cbox_planes;
1044 cbox.elements = NULL;
1052 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];
1053 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];
1054 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];
1055 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];
1056 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];
1057 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];
1058 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1059 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1060 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1061 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1062 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1063 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1064 memset(trace, 0, sizeof(trace_t));
1065 trace->hitsupercontentsmask = hitsupercontentsmask;
1066 trace->fraction = 1;
1067 trace->realfraction = 1;
1068 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1070 RecursiveHullCheckTraceInfo_t rhc;
1071 static hull_t box_hull;
1072 static mclipnode_t box_clipnodes[6];
1073 static mplane_t box_planes[6];
1074 // fill in a default trace
1075 memset(&rhc, 0, sizeof(rhc));
1076 memset(trace, 0, sizeof(trace_t));
1077 //To keep everything totally uniform, bounding boxes are turned into small
1078 //BSP trees instead of being compared directly.
1079 // create a temp hull from bounding box sizes
1080 box_planes[0].dist = cmaxs[0] - mins[0];
1081 box_planes[1].dist = cmins[0] - maxs[0];
1082 box_planes[2].dist = cmaxs[1] - mins[1];
1083 box_planes[3].dist = cmins[1] - maxs[1];
1084 box_planes[4].dist = cmaxs[2] - mins[2];
1085 box_planes[5].dist = cmins[2] - maxs[2];
1086 #if COLLISIONPARANOID >= 3
1087 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]);
1090 if (box_hull.clipnodes == NULL)
1094 //Set up the planes and clipnodes so that the six floats of a bounding box
1095 //can just be stored out and get a proper hull_t structure.
1097 box_hull.clipnodes = box_clipnodes;
1098 box_hull.planes = box_planes;
1099 box_hull.firstclipnode = 0;
1100 box_hull.lastclipnode = 5;
1102 for (i = 0;i < 6;i++)
1104 box_clipnodes[i].planenum = i;
1108 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1110 box_clipnodes[i].children[side^1] = i + 1;
1112 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1114 box_planes[i].type = i>>1;
1115 box_planes[i].normal[i>>1] = 1;
1119 // trace a line through the generated clipping hull
1120 //rhc.boxsupercontents = boxsupercontents;
1121 rhc.hull = &box_hull;
1123 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1124 rhc.trace->fraction = 1;
1125 rhc.trace->realfraction = 1;
1126 rhc.trace->allsolid = true;
1127 VectorCopy(start, rhc.start);
1128 VectorCopy(end, rhc.end);
1129 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1130 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1131 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1132 if (rhc.trace->startsupercontents)
1133 rhc.trace->startsupercontents = boxsupercontents;
1137 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)
1139 memset(trace, 0, sizeof(trace_t));
1140 trace->fraction = 1;
1141 trace->realfraction = 1;
1142 if (BoxesOverlap(start, start, cmins, cmaxs))
1144 trace->startsupercontents |= boxsupercontents;
1145 if (hitsupercontentsmask & boxsupercontents)
1147 trace->startsolid = true;
1148 trace->allsolid = true;
1153 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1156 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1157 return trace.fraction == 1;
1160 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)
1164 float mid, distz = endz - startz;
1168 return false; // didn't hit anything
1170 switch (node->plane->type)
1173 node = node->children[x < node->plane->dist];
1176 node = node->children[y < node->plane->dist];
1179 side = startz < node->plane->dist;
1180 if ((endz < node->plane->dist) == side)
1182 node = node->children[side];
1185 // found an intersection
1186 mid = node->plane->dist;
1189 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1190 front += startz * node->plane->normal[2];
1191 back += endz * node->plane->normal[2];
1192 side = front < node->plane->dist;
1193 if ((back < node->plane->dist) == side)
1195 node = node->children[side];
1198 // found an intersection
1199 mid = startz + distz * (front - node->plane->dist) / (front - back);
1203 // go down front side
1204 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1205 return true; // hit something
1208 // check for impact on this node
1209 if (node->numsurfaces)
1211 int i, dsi, dti, lmwidth, lmheight;
1213 msurface_t *surface;
1214 unsigned char *lightmap;
1215 int maps, line3, size3;
1218 float scale, w, w00, w01, w10, w11;
1220 surface = model->data_surfaces + node->firstsurface;
1221 for (i = 0;i < node->numsurfaces;i++, surface++)
1223 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1224 continue; // no lightmaps
1226 // location we want to sample in the lightmap
1227 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;
1228 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;
1233 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1234 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1237 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1239 // calculate bilinear interpolation factors
1240 // and also multiply by fixedpoint conversion factors
1243 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1244 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1245 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1246 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1248 // values for pointer math
1249 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1250 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1252 // look up the pixel
1253 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1255 // bilinear filter each lightmap style, and sum them
1256 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1258 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1259 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1260 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1261 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1262 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1266 return true; // success
1271 // go down back side
1272 node = node->children[side ^ 1];
1274 distz = endz - startz;
1279 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1281 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1282 VectorSet(diffusenormal, 0, 0, 1);
1284 if (!model->brushq1.lightdata)
1286 VectorSet(ambientcolor, 1, 1, 1);
1287 VectorSet(diffusecolor, 0, 0, 0);
1291 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);
1294 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1297 unsigned char *outstart = out;
1298 while (out < outend)
1302 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));
1312 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));
1315 for (c = *in++;c > 0;c--)
1319 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));
1330 R_Q1BSP_LoadSplitSky
1332 A sky texture is 256*128, with the right side being a masked overlay
1335 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1340 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1341 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1343 // allocate a texture pool if we need it
1344 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1345 loadmodel->texturepool = R_AllocTexturePool();
1347 if (bytesperpixel == 4)
1349 for (y = 0;y < h;y++)
1351 for (x = 0;x < w;x++)
1353 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1354 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1360 // make an average value for the back to avoid
1361 // a fringe on the top level
1370 for (y = 0;y < h;y++)
1372 for (x = 0;x < w;x++)
1374 p = src[x*width+y+w];
1375 r += palette_rgb[p][0];
1376 g += palette_rgb[p][1];
1377 b += palette_rgb[p][2];
1380 bgra.b[2] = r/(w*h);
1381 bgra.b[1] = g/(w*h);
1382 bgra.b[0] = b/(w*h);
1384 for (y = 0;y < h;y++)
1386 for (x = 0;x < w;x++)
1388 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1390 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1395 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h);
1396 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1397 Mem_Free(solidpixels);
1398 Mem_Free(alphapixels);
1401 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1403 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1404 skinframe_t *skinframe;
1406 texture_t *tx, *tx2, *anims[10], *altanims[10];
1408 unsigned char *data, *mtdata;
1410 char mapname[MAX_QPATH], name[MAX_QPATH];
1411 unsigned char zero[4];
1413 memset(zero, 0, sizeof(zero));
1415 loadmodel->data_textures = NULL;
1417 // add two slots for notexture walls and notexture liquids
1420 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1421 m->nummiptex = LittleLong (m->nummiptex);
1422 loadmodel->num_textures = m->nummiptex + 2;
1423 loadmodel->num_texturesperskin = loadmodel->num_textures;
1428 loadmodel->num_textures = 2;
1429 loadmodel->num_texturesperskin = loadmodel->num_textures;
1432 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1434 // fill out all slots with notexture
1435 if (cls.state != ca_dedicated)
1436 skinframe = R_SkinFrame_LoadMissing();
1439 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1441 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1444 if (cls.state != ca_dedicated)
1446 tx->numskinframes = 1;
1447 tx->skinframerate = 1;
1448 tx->skinframes[0] = skinframe;
1449 tx->currentskinframe = tx->skinframes[0];
1451 tx->basematerialflags = MATERIALFLAG_WALL;
1452 if (i == loadmodel->num_textures - 1)
1454 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1455 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1456 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1460 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1461 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1463 tx->currentframe = tx;
1465 // clear water settings
1468 tx->refractfactor = 1;
1469 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1470 tx->reflectfactor = 1;
1471 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1472 tx->r_water_wateralpha = 1;
1473 tx->offsetmapping = OFFSETMAPPING_OFF;
1474 tx->offsetscale = 1;
1475 tx->specularscalemod = 1;
1476 tx->specularpowermod = 1;
1481 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1485 s = loadmodel->name;
1486 if (!strncasecmp(s, "maps/", 5))
1488 FS_StripExtension(s, mapname, sizeof(mapname));
1490 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1492 // LordHavoc: mostly rewritten map texture loader
1493 for (i = 0;i < m->nummiptex;i++)
1495 dofs[i] = LittleLong(dofs[i]);
1496 if (r_nosurftextures.integer)
1500 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1503 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1505 // copy name, but only up to 16 characters
1506 // (the output buffer can hold more than this, but the input buffer is
1508 for (j = 0;j < 16 && dmiptex->name[j];j++)
1509 name[j] = dmiptex->name[j];
1514 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1515 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1518 mtwidth = LittleLong(dmiptex->width);
1519 mtheight = LittleLong(dmiptex->height);
1521 j = LittleLong(dmiptex->offsets[0]);
1525 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1527 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1530 mtdata = (unsigned char *)dmiptex + j;
1533 if ((mtwidth & 15) || (mtheight & 15))
1534 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1536 // LordHavoc: force all names to lowercase
1537 for (j = 0;name[j];j++)
1538 if (name[j] >= 'A' && name[j] <= 'Z')
1539 name[j] += 'a' - 'A';
1541 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1544 tx = loadmodel->data_textures + i;
1545 strlcpy(tx->name, name, sizeof(tx->name));
1546 tx->width = mtwidth;
1547 tx->height = mtheight;
1549 if (tx->name[0] == '*')
1551 if (!strncmp(tx->name, "*lava", 5))
1553 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1554 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1556 else if (!strncmp(tx->name, "*slime", 6))
1558 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1559 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1563 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1564 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1567 else if (!strncmp(tx->name, "sky", 3))
1569 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1570 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1574 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1575 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1578 if (cls.state != ca_dedicated)
1580 // LordHavoc: HL sky textures are entirely different than quake
1581 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1583 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), false, false, r_texture_convertsRGB_skin.integer != 0, NULL);
1585 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, r_texture_convertsRGB_skin.integer != 0, NULL);
1586 if (data && image_width == image_height * 2)
1588 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1591 else if (mtdata != NULL)
1592 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1596 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);
1598 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);
1601 // did not find external texture, load it from the bsp or wad3
1602 if (loadmodel->brush.ishlbsp)
1604 // internal texture overrides wad
1605 unsigned char *pixels, *freepixels;
1606 pixels = freepixels = NULL;
1608 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1610 pixels = freepixels = W_GetTextureBGRA(tx->name);
1613 tx->width = image_width;
1614 tx->height = image_height;
1615 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height);
1618 Mem_Free(freepixels);
1620 else if (mtdata) // texture included
1621 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1623 // if skinframe is still NULL the "missing" texture will be used
1625 tx->skinframes[0] = skinframe;
1628 tx->basematerialflags = MATERIALFLAG_WALL;
1629 if (tx->name[0] == '*')
1631 // LordHavoc: some turbulent textures should not be affected by wateralpha
1632 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1634 // replace the texture with transparent black
1635 Vector4Set(zero, 128, 128, 128, 128);
1636 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1637 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1639 else if (!strncmp(tx->name,"*lava",5)
1640 || !strncmp(tx->name,"*teleport",9)
1641 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1642 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1644 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1645 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1646 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1648 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1650 // replace the texture with black
1651 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1652 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1654 else if (!strncmp(tx->name, "sky", 3))
1655 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1656 else if (!strcmp(tx->name, "caulk"))
1657 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1658 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1659 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1661 // start out with no animation
1662 tx->currentframe = tx;
1663 tx->currentskinframe = tx->skinframes[0];
1667 // sequence the animations
1668 for (i = 0;i < m->nummiptex;i++)
1670 tx = loadmodel->data_textures + i;
1671 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1673 if (tx->anim_total[0] || tx->anim_total[1])
1674 continue; // already sequenced
1676 // find the number of frames in the animation
1677 memset(anims, 0, sizeof(anims));
1678 memset(altanims, 0, sizeof(altanims));
1680 for (j = i;j < m->nummiptex;j++)
1682 tx2 = loadmodel->data_textures + j;
1683 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1687 if (num >= '0' && num <= '9')
1688 anims[num - '0'] = tx2;
1689 else if (num >= 'a' && num <= 'j')
1690 altanims[num - 'a'] = tx2;
1692 Con_Printf("Bad animating texture %s\n", tx->name);
1696 for (j = 0;j < 10;j++)
1703 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1706 for (j = 0;j < max;j++)
1710 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1714 for (j = 0;j < altmax;j++)
1718 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1727 // if there is no alternate animation, duplicate the primary
1728 // animation into the alternate
1730 for (k = 0;k < 10;k++)
1731 altanims[k] = anims[k];
1734 // link together the primary animation
1735 for (j = 0;j < max;j++)
1738 tx2->animated = true;
1739 tx2->anim_total[0] = max;
1740 tx2->anim_total[1] = altmax;
1741 for (k = 0;k < 10;k++)
1743 tx2->anim_frames[0][k] = anims[k];
1744 tx2->anim_frames[1][k] = altanims[k];
1748 // if there really is an alternate anim...
1749 if (anims[0] != altanims[0])
1751 // link together the alternate animation
1752 for (j = 0;j < altmax;j++)
1755 tx2->animated = true;
1756 // the primary/alternate are reversed here
1757 tx2->anim_total[0] = altmax;
1758 tx2->anim_total[1] = max;
1759 for (k = 0;k < 10;k++)
1761 tx2->anim_frames[0][k] = altanims[k];
1762 tx2->anim_frames[1][k] = anims[k];
1769 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1772 unsigned char *in, *out, *data, d;
1773 char litfilename[MAX_QPATH];
1774 char dlitfilename[MAX_QPATH];
1775 fs_offset_t filesize;
1776 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1778 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1779 for (i=0; i<l->filelen; i++)
1780 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1782 else // LordHavoc: bsp version 29 (normal white lighting)
1784 // LordHavoc: hope is not lost yet, check for a .lit file to load
1785 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1786 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1787 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1788 strlcat (litfilename, ".lit", sizeof (litfilename));
1789 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1790 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1793 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1795 i = LittleLong(((int *)data)[1]);
1798 if (developer_loading.integer)
1799 Con_Printf("loaded %s\n", litfilename);
1800 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1801 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1803 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1806 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1808 i = LittleLong(((int *)data)[1]);
1811 if (developer_loading.integer)
1812 Con_Printf("loaded %s\n", dlitfilename);
1813 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1814 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1815 loadmodel->brushq3.deluxemapping_modelspace = false;
1816 loadmodel->brushq3.deluxemapping = true;
1825 Con_Printf("Unknown .lit file version (%d)\n", i);
1827 else if (filesize == 8)
1828 Con_Print("Empty .lit file, ignoring\n");
1830 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
1837 // LordHavoc: oh well, expand the white lighting data
1840 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1841 in = mod_base + l->fileofs;
1842 out = loadmodel->brushq1.lightdata;
1843 for (i = 0;i < l->filelen;i++)
1853 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1855 loadmodel->brushq1.num_compressedpvs = 0;
1856 loadmodel->brushq1.data_compressedpvs = NULL;
1859 loadmodel->brushq1.num_compressedpvs = l->filelen;
1860 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1861 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1864 // used only for HalfLife maps
1865 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1867 char key[128], value[4096];
1871 if (!COM_ParseToken_Simple(&data, false, false))
1873 if (com_token[0] != '{')
1877 if (!COM_ParseToken_Simple(&data, false, false))
1879 if (com_token[0] == '}')
1880 break; // end of worldspawn
1881 if (com_token[0] == '_')
1882 strlcpy(key, com_token + 1, sizeof(key));
1884 strlcpy(key, com_token, sizeof(key));
1885 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1886 key[strlen(key)-1] = 0;
1887 if (!COM_ParseToken_Simple(&data, false, false))
1889 dpsnprintf(value, sizeof(value), "%s", com_token);
1890 if (!strcmp("wad", key)) // for HalfLife maps
1892 if (loadmodel->brush.ishlbsp)
1895 for (i = 0;i < (int)sizeof(value);i++)
1896 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1900 for (;i < (int)sizeof(value);i++)
1902 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1903 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1905 else if (value[i] == ';' || value[i] == 0)
1909 W_LoadTextureWadFile(&value[j], false);
1921 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1923 loadmodel->brush.entities = NULL;
1926 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
1927 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1928 loadmodel->brush.entities[l->filelen] = 0;
1929 if (loadmodel->brush.ishlbsp)
1930 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1934 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1940 in = (dvertex_t *)(mod_base + l->fileofs);
1941 if (l->filelen % sizeof(*in))
1942 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1943 count = l->filelen / sizeof(*in);
1944 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1946 loadmodel->brushq1.vertexes = out;
1947 loadmodel->brushq1.numvertexes = count;
1949 for ( i=0 ; i<count ; i++, in++, out++)
1951 out->position[0] = LittleFloat(in->point[0]);
1952 out->position[1] = LittleFloat(in->point[1]);
1953 out->position[2] = LittleFloat(in->point[2]);
1957 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1958 // can be used for this
1960 int SB_ReadInt (unsigned char **buffer)
1963 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1969 float SB_ReadFloat (unsigned char **buffer)
1977 u.i = SB_ReadInt (buffer);
1981 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1983 unsigned char *index;
1987 index = (unsigned char *)(mod_base + l->fileofs);
1988 if (l->filelen % (48+4*hullinfo->filehulls))
1989 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1991 count = l->filelen / (48+4*hullinfo->filehulls);
1992 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1994 loadmodel->brushq1.submodels = out;
1995 loadmodel->brush.numsubmodels = count;
1997 for (i = 0; i < count; i++, out++)
1999 // spread out the mins / maxs by a pixel
2000 out->mins[0] = SB_ReadFloat (&index) - 1;
2001 out->mins[1] = SB_ReadFloat (&index) - 1;
2002 out->mins[2] = SB_ReadFloat (&index) - 1;
2003 out->maxs[0] = SB_ReadFloat (&index) + 1;
2004 out->maxs[1] = SB_ReadFloat (&index) + 1;
2005 out->maxs[2] = SB_ReadFloat (&index) + 1;
2006 out->origin[0] = SB_ReadFloat (&index);
2007 out->origin[1] = SB_ReadFloat (&index);
2008 out->origin[2] = SB_ReadFloat (&index);
2009 for (j = 0; j < hullinfo->filehulls; j++)
2010 out->headnode[j] = SB_ReadInt (&index);
2011 out->visleafs = SB_ReadInt (&index);
2012 out->firstface = SB_ReadInt (&index);
2013 out->numfaces = SB_ReadInt (&index);
2017 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2023 in = (dedge_t *)(mod_base + l->fileofs);
2024 if (l->filelen % sizeof(*in))
2025 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2026 count = l->filelen / sizeof(*in);
2027 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2029 loadmodel->brushq1.edges = out;
2030 loadmodel->brushq1.numedges = count;
2032 for ( i=0 ; i<count ; i++, in++, out++)
2034 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2035 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2036 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2038 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);
2039 if(!loadmodel->brushq1.numvertexes)
2040 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2048 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2052 int i, j, k, count, miptex;
2054 in = (texinfo_t *)(mod_base + l->fileofs);
2055 if (l->filelen % sizeof(*in))
2056 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2057 count = l->filelen / sizeof(*in);
2058 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2060 loadmodel->brushq1.texinfo = out;
2061 loadmodel->brushq1.numtexinfo = count;
2063 for (i = 0;i < count;i++, in++, out++)
2065 for (k = 0;k < 2;k++)
2066 for (j = 0;j < 4;j++)
2067 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2069 miptex = LittleLong(in->miptex);
2070 out->flags = LittleLong(in->flags);
2072 out->texture = NULL;
2073 if (loadmodel->data_textures)
2075 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2076 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2078 out->texture = loadmodel->data_textures + miptex;
2080 if (out->flags & TEX_SPECIAL)
2082 // if texture chosen is NULL or the shader needs a lightmap,
2083 // force to notexture water shader
2084 if (out->texture == NULL)
2085 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2089 // if texture chosen is NULL, force to notexture
2090 if (out->texture == NULL)
2091 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2097 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2102 mins[0] = mins[1] = mins[2] = 9999;
2103 maxs[0] = maxs[1] = maxs[2] = -9999;
2105 for (i = 0;i < numverts;i++)
2107 for (j = 0;j < 3;j++, v++)
2117 #define MAX_SUBDIVPOLYTRIANGLES 4096
2118 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2120 static int subdivpolyverts, subdivpolytriangles;
2121 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2122 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2124 static int subdivpolylookupvert(vec3_t v)
2127 for (i = 0;i < subdivpolyverts;i++)
2128 if (subdivpolyvert[i][0] == v[0]
2129 && subdivpolyvert[i][1] == v[1]
2130 && subdivpolyvert[i][2] == v[2])
2132 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2133 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2134 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2135 return subdivpolyverts++;
2138 static void SubdividePolygon(int numverts, float *verts)
2140 int i, i1, i2, i3, f, b, c, p;
2141 vec3_t mins, maxs, front[256], back[256];
2142 float m, *pv, *cv, dist[256], frac;
2145 Host_Error("SubdividePolygon: ran out of verts in buffer");
2147 BoundPoly(numverts, verts, mins, maxs);
2149 for (i = 0;i < 3;i++)
2151 m = (mins[i] + maxs[i]) * 0.5;
2152 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2153 if (maxs[i] - m < 8)
2155 if (m - mins[i] < 8)
2159 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2160 dist[c] = cv[i] - m;
2163 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2167 VectorCopy(pv, front[f]);
2172 VectorCopy(pv, back[b]);
2175 if (dist[p] == 0 || dist[c] == 0)
2177 if ((dist[p] > 0) != (dist[c] > 0) )
2180 frac = dist[p] / (dist[p] - dist[c]);
2181 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2182 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2183 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2189 SubdividePolygon(f, front[0]);
2190 SubdividePolygon(b, back[0]);
2194 i1 = subdivpolylookupvert(verts);
2195 i2 = subdivpolylookupvert(verts + 3);
2196 for (i = 2;i < numverts;i++)
2198 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2200 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2204 i3 = subdivpolylookupvert(verts + i * 3);
2205 subdivpolyindex[subdivpolytriangles][0] = i1;
2206 subdivpolyindex[subdivpolytriangles][1] = i2;
2207 subdivpolyindex[subdivpolytriangles][2] = i3;
2209 subdivpolytriangles++;
2213 //Breaks a polygon up along axial 64 unit
2214 //boundaries so that turbulent and sky warps
2215 //can be done reasonably.
2216 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2222 subdivpolytriangles = 0;
2223 subdivpolyverts = 0;
2224 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2225 if (subdivpolytriangles < 1)
2226 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2228 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2229 mesh->num_vertices = subdivpolyverts;
2230 mesh->num_triangles = subdivpolytriangles;
2231 mesh->vertex = (surfvertex_t *)(mesh + 1);
2232 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2233 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2235 for (i = 0;i < mesh->num_triangles;i++)
2236 for (j = 0;j < 3;j++)
2237 mesh->index[i*3+j] = subdivpolyindex[i][j];
2239 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2241 VectorCopy(subdivpolyvert[i], v->v);
2242 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2243 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2248 extern cvar_t gl_max_lightmapsize;
2249 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2252 msurface_t *surface;
2253 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2254 float texmins[2], texmaxs[2], val;
2255 rtexture_t *lightmaptexture, *deluxemaptexture;
2257 in = (dface_t *)(mod_base + l->fileofs);
2258 if (l->filelen % sizeof(*in))
2259 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2260 count = l->filelen / sizeof(*in);
2261 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2262 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2264 loadmodel->num_surfaces = count;
2266 loadmodel->brushq1.firstrender = true;
2267 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2271 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2273 numedges = (unsigned short)LittleShort(in->numedges);
2274 totalverts += numedges;
2275 totaltris += numedges - 2;
2278 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2280 lightmaptexture = NULL;
2281 deluxemaptexture = r_texture_blanknormalmap;
2283 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2284 totallightmapsamples = 0;
2288 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2290 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2292 // FIXME: validate edges, texinfo, etc?
2293 firstedge = LittleLong(in->firstedge);
2294 numedges = (unsigned short)LittleShort(in->numedges);
2295 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)
2296 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2297 i = (unsigned short)LittleShort(in->texinfo);
2298 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2299 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2300 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2301 surface->texture = surface->lightmapinfo->texinfo->texture;
2303 planenum = (unsigned short)LittleShort(in->planenum);
2304 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2305 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2307 //surface->flags = surface->texture->flags;
2308 //if (LittleShort(in->side))
2309 // surface->flags |= SURF_PLANEBACK;
2310 //surface->plane = loadmodel->brush.data_planes + planenum;
2312 surface->num_firstvertex = totalverts;
2313 surface->num_vertices = numedges;
2314 surface->num_firsttriangle = totaltris;
2315 surface->num_triangles = numedges - 2;
2316 totalverts += numedges;
2317 totaltris += numedges - 2;
2319 // convert edges back to a normal polygon
2320 for (i = 0;i < surface->num_vertices;i++)
2322 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2324 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2326 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2328 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2329 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2330 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2331 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2332 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2333 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2334 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2335 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2338 for (i = 0;i < surface->num_triangles;i++)
2340 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2341 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2342 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2345 // compile additional data about the surface geometry
2346 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, true);
2347 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, true);
2348 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2350 // generate surface extents information
2351 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2352 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2353 for (i = 1;i < surface->num_vertices;i++)
2355 for (j = 0;j < 2;j++)
2357 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2358 texmins[j] = min(texmins[j], val);
2359 texmaxs[j] = max(texmaxs[j], val);
2362 for (i = 0;i < 2;i++)
2364 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2365 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2368 smax = surface->lightmapinfo->extents[0] >> 4;
2369 tmax = surface->lightmapinfo->extents[1] >> 4;
2370 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2371 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2374 for (i = 0;i < MAXLIGHTMAPS;i++)
2375 surface->lightmapinfo->styles[i] = in->styles[i];
2376 surface->lightmaptexture = NULL;
2377 surface->deluxemaptexture = r_texture_blanknormalmap;
2378 i = LittleLong(in->lightofs);
2381 surface->lightmapinfo->samples = NULL;
2383 // give non-lightmapped water a 1x white lightmap
2384 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2386 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2387 surface->lightmapinfo->styles[0] = 0;
2388 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2392 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2393 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2394 else // LordHavoc: white lighting (bsp version 29)
2396 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2397 if (loadmodel->brushq1.nmaplightdata)
2398 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2401 // check if we should apply a lightmap to this
2402 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2404 if (ssize > 256 || tsize > 256)
2405 Host_Error("Bad surface extents");
2407 if (lightmapsize < ssize)
2408 lightmapsize = ssize;
2409 if (lightmapsize < tsize)
2410 lightmapsize = tsize;
2412 totallightmapsamples += ssize*tsize;
2414 // force lightmap upload on first time seeing the surface
2416 // additionally this is used by the later code to see if a
2417 // lightmap is needed on this surface (rather than duplicating the
2419 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2420 loadmodel->lit = true;
2424 // small maps (such as ammo boxes especially) don't need big lightmap
2425 // textures, so this code tries to guess a good size based on
2426 // totallightmapsamples (size of the lightmaps lump basically), as well as
2427 // trying to max out the size if there is a lot of lightmap data to store
2428 // additionally, never choose a lightmapsize that is smaller than the
2429 // largest surface encountered (as it would fail)
2431 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2434 // now that we've decided the lightmap texture size, we can do the rest
2435 if (cls.state != ca_dedicated)
2437 int stainmapsize = 0;
2438 mod_alloclightmap_state_t allocState;
2440 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2441 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2443 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2444 float u, v, ubase, vbase, uscale, vscale;
2446 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2449 smax = surface->lightmapinfo->extents[0] >> 4;
2450 tmax = surface->lightmapinfo->extents[1] >> 4;
2451 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2452 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2453 stainmapsize += ssize * tsize * 3;
2455 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2457 // allocate a texture pool if we need it
2458 if (loadmodel->texturepool == NULL)
2459 loadmodel->texturepool = R_AllocTexturePool();
2460 // could not find room, make a new lightmap
2461 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2462 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2463 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2464 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);
2465 if (loadmodel->brushq1.nmaplightdata)
2466 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);
2468 Mod_AllocLightmap_Reset(&allocState);
2469 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2471 surface->lightmaptexture = lightmaptexture;
2472 surface->deluxemaptexture = deluxemaptexture;
2473 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2474 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2476 uscale = 1.0f / (float)lightmapsize;
2477 vscale = 1.0f / (float)lightmapsize;
2478 ubase = lightmapx * uscale;
2479 vbase = lightmapy * vscale;
2481 for (i = 0;i < surface->num_vertices;i++)
2483 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);
2484 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);
2485 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2486 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2487 // LordHavoc: calc lightmap data offset for vertex lighting to use
2490 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2494 if (cl_stainmaps.integer)
2496 // allocate stainmaps for permanent marks on walls and clear white
2497 unsigned char *stainsamples = NULL;
2498 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2499 memset(stainsamples, 255, stainmapsize);
2501 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2503 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2505 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2506 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2507 surface->lightmapinfo->stainsamples = stainsamples;
2508 stainsamples += ssize * tsize * 3;
2513 // generate ushort elements array if possible
2514 if (loadmodel->surfmesh.data_element3s)
2515 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2516 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2519 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2522 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2523 node->parent = parent;
2526 // this is a node, recurse to children
2527 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2528 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2529 // combine supercontents of children
2530 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2535 mleaf_t *leaf = (mleaf_t *)node;
2536 // if this is a leaf, calculate supercontents mask from all collidable
2537 // primitives in the leaf (brushes and collision surfaces)
2538 // also flag if the leaf contains any collision surfaces
2539 leaf->combinedsupercontents = 0;
2540 // combine the supercontents values of all brushes in this leaf
2541 for (j = 0;j < leaf->numleafbrushes;j++)
2542 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2543 // check if this leaf contains any collision surfaces (q3 patches)
2544 for (j = 0;j < leaf->numleafsurfaces;j++)
2546 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2547 if (surface->num_collisiontriangles)
2549 leaf->containscollisionsurfaces = true;
2550 leaf->combinedsupercontents |= surface->texture->supercontents;
2556 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2562 in = (dnode_t *)(mod_base + l->fileofs);
2563 if (l->filelen % sizeof(*in))
2564 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2565 count = l->filelen / sizeof(*in);
2566 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2568 loadmodel->brush.data_nodes = out;
2569 loadmodel->brush.num_nodes = count;
2571 for ( i=0 ; i<count ; i++, in++, out++)
2573 for (j=0 ; j<3 ; j++)
2575 out->mins[j] = LittleShort(in->mins[j]);
2576 out->maxs[j] = LittleShort(in->maxs[j]);
2579 p = LittleLong(in->planenum);
2580 out->plane = loadmodel->brush.data_planes + p;
2582 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2583 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2585 for (j=0 ; j<2 ; j++)
2587 // LordHavoc: this code supports broken bsp files produced by
2588 // arguire qbsp which can produce more than 32768 nodes, any value
2589 // below count is assumed to be a node number, any other value is
2590 // assumed to be a leaf number
2591 p = (unsigned short)LittleShort(in->children[j]);
2594 if (p < loadmodel->brush.num_nodes)
2595 out->children[j] = loadmodel->brush.data_nodes + p;
2598 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2599 // map it to the solid leaf
2600 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2605 // note this uses 65535 intentionally, -1 is leaf 0
2607 if (p < loadmodel->brush.num_leafs)
2608 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2611 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2612 // map it to the solid leaf
2613 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2619 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2622 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2628 in = (dleaf_t *)(mod_base + l->fileofs);
2629 if (l->filelen % sizeof(*in))
2630 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2631 count = l->filelen / sizeof(*in);
2632 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2634 loadmodel->brush.data_leafs = out;
2635 loadmodel->brush.num_leafs = count;
2636 // get visleafs from the submodel data
2637 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2638 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2639 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2640 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2642 for ( i=0 ; i<count ; i++, in++, out++)
2644 for (j=0 ; j<3 ; j++)
2646 out->mins[j] = LittleShort(in->mins[j]);
2647 out->maxs[j] = LittleShort(in->maxs[j]);
2650 // FIXME: this function could really benefit from some error checking
2652 out->contents = LittleLong(in->contents);
2654 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2655 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2656 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2658 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);
2659 out->firstleafsurface = NULL;
2660 out->numleafsurfaces = 0;
2663 out->clusterindex = i - 1;
2664 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2665 out->clusterindex = -1;
2667 p = LittleLong(in->visofs);
2668 // ignore visofs errors on leaf 0 (solid)
2669 if (p >= 0 && out->clusterindex >= 0)
2671 if (p >= loadmodel->brushq1.num_compressedpvs)
2672 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2674 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);
2677 for (j = 0;j < 4;j++)
2678 out->ambient_sound_level[j] = in->ambient_level[j];
2680 // FIXME: Insert caustics here
2684 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2688 const unsigned char *pvs;
2689 // if there's no vis data, assume supported (because everything is visible all the time)
2690 if (!loadmodel->brush.data_pvsclusters)
2692 // check all liquid leafs to see if they can see into empty leafs, if any
2693 // can we can assume this map supports r_wateralpha
2694 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2696 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2698 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2699 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2700 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2707 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2714 in = (dclipnode_t *)(mod_base + l->fileofs);
2715 if (l->filelen % sizeof(*in))
2716 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2717 count = l->filelen / sizeof(*in);
2718 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2720 loadmodel->brushq1.clipnodes = out;
2721 loadmodel->brushq1.numclipnodes = count;
2723 for (i = 1; i < MAX_MAP_HULLS; i++)
2725 hull = &loadmodel->brushq1.hulls[i];
2726 hull->clipnodes = out;
2727 hull->firstclipnode = 0;
2728 hull->lastclipnode = count-1;
2729 hull->planes = loadmodel->brush.data_planes;
2730 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2731 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2732 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2733 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2734 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2735 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2736 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2739 for (i=0 ; i<count ; i++, out++, in++)
2741 out->planenum = LittleLong(in->planenum);
2742 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2743 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2744 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2745 if (out->children[0] >= count)
2746 out->children[0] -= 65536;
2747 if (out->children[1] >= count)
2748 out->children[1] -= 65536;
2749 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2750 Host_Error("Corrupt clipping hull(out of range planenum)");
2754 //Duplicate the drawing hull structure as a clipping hull
2755 static void Mod_Q1BSP_MakeHull0(void)
2762 hull = &loadmodel->brushq1.hulls[0];
2764 in = loadmodel->brush.data_nodes;
2765 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2767 hull->clipnodes = out;
2768 hull->firstclipnode = 0;
2769 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2770 hull->planes = loadmodel->brush.data_planes;
2772 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2774 out->planenum = in->plane - loadmodel->brush.data_planes;
2775 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2776 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2780 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2785 in = (short *)(mod_base + l->fileofs);
2786 if (l->filelen % sizeof(*in))
2787 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2788 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2789 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2791 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2793 j = (unsigned short) LittleShort(in[i]);
2794 if (j >= loadmodel->num_surfaces)
2795 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2796 loadmodel->brush.data_leafsurfaces[i] = j;
2800 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2805 in = (int *)(mod_base + l->fileofs);
2806 if (l->filelen % sizeof(*in))
2807 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2808 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2809 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2811 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2812 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2816 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2822 in = (dplane_t *)(mod_base + l->fileofs);
2823 if (l->filelen % sizeof(*in))
2824 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2826 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2827 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2829 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2831 out->normal[0] = LittleFloat(in->normal[0]);
2832 out->normal[1] = LittleFloat(in->normal[1]);
2833 out->normal[2] = LittleFloat(in->normal[2]);
2834 out->dist = LittleFloat(in->dist);
2840 static void Mod_Q1BSP_LoadMapBrushes(void)
2844 int submodel, numbrushes;
2845 qboolean firstbrush;
2846 char *text, *maptext;
2847 char mapfilename[MAX_QPATH];
2848 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2849 strlcat (mapfilename, ".map", sizeof (mapfilename));
2850 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
2854 if (!COM_ParseToken_Simple(&data, false, false))
2859 if (!COM_ParseToken_Simple(&data, false, false))
2861 if (com_token[0] != '{')
2867 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2870 if (!COM_ParseToken_Simple(&data, false, false))
2872 if (com_token[0] == '}')
2873 break; // end of entity
2874 if (com_token[0] == '{')
2881 if (submodel > loadmodel->brush.numsubmodels)
2883 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2887 model = loadmodel->brush.submodels[submodel];
2894 if (!COM_ParseToken_Simple(&data, false, false))
2896 if (com_token[0] == '}')
2897 break; // end of brush
2898 // each brush face should be this format:
2899 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2900 // FIXME: support hl .map format
2901 for (pointnum = 0;pointnum < 3;pointnum++)
2903 COM_ParseToken_Simple(&data, false, false);
2904 for (componentnum = 0;componentnum < 3;componentnum++)
2906 COM_ParseToken_Simple(&data, false, false);
2907 point[pointnum][componentnum] = atof(com_token);
2909 COM_ParseToken_Simple(&data, false, false);
2911 COM_ParseToken_Simple(&data, false, false);
2912 strlcpy(facetexture, com_token, sizeof(facetexture));
2913 COM_ParseToken_Simple(&data, false, false);
2914 //scroll_s = atof(com_token);
2915 COM_ParseToken_Simple(&data, false, false);
2916 //scroll_t = atof(com_token);
2917 COM_ParseToken_Simple(&data, false, false);
2918 //rotate = atof(com_token);
2919 COM_ParseToken_Simple(&data, false, false);
2920 //scale_s = atof(com_token);
2921 COM_ParseToken_Simple(&data, false, false);
2922 //scale_t = atof(com_token);
2923 TriangleNormal(point[0], point[1], point[2], planenormal);
2924 VectorNormalizeDouble(planenormal);
2925 planedist = DotProduct(point[0], planenormal);
2926 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2936 #define MAX_PORTALPOINTS 64
2938 typedef struct portal_s
2941 mnode_t *nodes[2]; // [0] = front side of plane
2942 struct portal_s *next[2];
2944 double points[3*MAX_PORTALPOINTS];
2945 struct portal_s *chain; // all portals are linked into a list
2949 static memexpandablearray_t portalarray;
2951 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2953 // process only nodes (leafs already had their box calculated)
2957 // calculate children first
2958 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2959 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2961 // make combined bounding box from children
2962 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2963 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2964 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2965 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2966 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2967 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2970 static void Mod_Q1BSP_FinalizePortals(void)
2972 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
2976 mleaf_t *leaf, *endleaf;
2978 // tally up portal and point counts and recalculate bounding boxes for all
2979 // leafs (because qbsp is very sloppy)
2980 leaf = loadmodel->brush.data_leafs;
2981 endleaf = leaf + loadmodel->brush.num_leafs;
2982 if (mod_recalculatenodeboxes.integer)
2984 for (;leaf < endleaf;leaf++)
2986 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2987 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2992 for (portalindex = 0;portalindex < portalrange;portalindex++)
2994 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
2997 // note: this check must match the one below or it will usually corrupt memory
2998 // 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
2999 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3002 numpoints += p->numpoints * 2;
3005 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3006 loadmodel->brush.num_portals = numportals;
3007 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3008 loadmodel->brush.num_portalpoints = numpoints;
3009 // clear all leaf portal chains
3010 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3011 loadmodel->brush.data_leafs[i].portals = NULL;
3012 // process all portals in the global portal chain, while freeing them
3013 portal = loadmodel->brush.data_portals;
3014 point = loadmodel->brush.data_portalpoints;
3015 for (portalindex = 0;portalindex < portalrange;portalindex++)
3017 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3020 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3022 // note: this check must match the one above or it will usually corrupt memory
3023 // 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
3024 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3026 // first make the back to front portal(forward portal)
3027 portal->points = point;
3028 portal->numpoints = p->numpoints;
3029 portal->plane.dist = p->plane.dist;
3030 VectorCopy(p->plane.normal, portal->plane.normal);
3031 portal->here = (mleaf_t *)p->nodes[1];
3032 portal->past = (mleaf_t *)p->nodes[0];
3034 for (j = 0;j < portal->numpoints;j++)
3036 VectorCopy(p->points + j*3, point->position);
3039 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3040 PlaneClassify(&portal->plane);
3042 // link into leaf's portal chain
3043 portal->next = portal->here->portals;
3044 portal->here->portals = portal;
3046 // advance to next portal
3049 // then make the front to back portal(backward portal)
3050 portal->points = point;
3051 portal->numpoints = p->numpoints;
3052 portal->plane.dist = -p->plane.dist;
3053 VectorNegate(p->plane.normal, portal->plane.normal);
3054 portal->here = (mleaf_t *)p->nodes[0];
3055 portal->past = (mleaf_t *)p->nodes[1];
3057 for (j = portal->numpoints - 1;j >= 0;j--)
3059 VectorCopy(p->points + j*3, point->position);
3062 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3063 PlaneClassify(&portal->plane);
3065 // link into leaf's portal chain
3066 portal->next = portal->here->portals;
3067 portal->here->portals = portal;
3069 // advance to next portal
3072 // add the portal's polygon points to the leaf bounding boxes
3073 if (mod_recalculatenodeboxes.integer)
3075 for (i = 0;i < 2;i++)
3077 leaf = (mleaf_t *)p->nodes[i];
3078 for (j = 0;j < p->numpoints;j++)
3080 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3081 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3082 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3083 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3084 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3085 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3091 // now recalculate the node bounding boxes from the leafs
3092 if (mod_recalculatenodeboxes.integer)
3093 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3101 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3104 Host_Error("AddPortalToNodes: NULL front node");
3106 Host_Error("AddPortalToNodes: NULL back node");
3107 if (p->nodes[0] || p->nodes[1])
3108 Host_Error("AddPortalToNodes: already included");
3109 // 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
3111 p->nodes[0] = front;
3112 p->next[0] = (portal_t *)front->portals;
3113 front->portals = (mportal_t *)p;
3116 p->next[1] = (portal_t *)back->portals;
3117 back->portals = (mportal_t *)p;
3122 RemovePortalFromNode
3125 static void RemovePortalFromNodes(portal_t *portal)
3129 void **portalpointer;
3131 for (i = 0;i < 2;i++)
3133 node = portal->nodes[i];
3135 portalpointer = (void **) &node->portals;
3138 t = (portal_t *)*portalpointer;
3140 Host_Error("RemovePortalFromNodes: portal not in leaf");
3144 if (portal->nodes[0] == node)
3146 *portalpointer = portal->next[0];
3147 portal->nodes[0] = NULL;
3149 else if (portal->nodes[1] == node)
3151 *portalpointer = portal->next[1];
3152 portal->nodes[1] = NULL;
3155 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3159 if (t->nodes[0] == node)
3160 portalpointer = (void **) &t->next[0];
3161 else if (t->nodes[1] == node)
3162 portalpointer = (void **) &t->next[1];
3164 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3169 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3170 static double *portalpointsbuffer;
3171 static int portalpointsbufferoffset;
3172 static int portalpointsbuffersize;
3173 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3176 mnode_t *front, *back, *other_node;
3177 mplane_t clipplane, *plane;
3178 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3179 int numfrontpoints, numbackpoints;
3180 double *frontpoints, *backpoints;
3182 // if a leaf, we're done
3186 // get some space for our clipping operations to use
3187 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3189 portalpointsbuffersize = portalpointsbufferoffset * 2;
3190 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3192 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3193 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3194 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3195 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3197 plane = node->plane;
3199 front = node->children[0];
3200 back = node->children[1];
3202 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3204 // create the new portal by generating a polygon for the node plane,
3205 // and clipping it by all of the other portals(which came from nodes above this one)
3206 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3207 nodeportal->plane = *plane;
3209 // 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)
3210 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);
3211 nodeportal->numpoints = 4;
3212 side = 0; // shut up compiler warning
3213 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3215 clipplane = portal->plane;
3216 if (portal->nodes[0] == portal->nodes[1])
3217 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3218 if (portal->nodes[0] == node)
3220 else if (portal->nodes[1] == node)
3222 clipplane.dist = -clipplane.dist;
3223 VectorNegate(clipplane.normal, clipplane.normal);
3227 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3229 for (i = 0;i < nodeportal->numpoints*3;i++)
3230 frontpoints[i] = nodeportal->points[i];
3231 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);
3232 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3236 if (nodeportal->numpoints < 3)
3238 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3239 nodeportal->numpoints = 0;
3241 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3243 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3244 nodeportal->numpoints = 0;
3247 AddPortalToNodes(nodeportal, front, back);
3249 // split the portals of this node along this node's plane and assign them to the children of this node
3250 // (migrating the portals downward through the tree)
3251 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3253 if (portal->nodes[0] == portal->nodes[1])
3254 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3255 if (portal->nodes[0] == node)
3257 else if (portal->nodes[1] == node)
3260 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3261 nextportal = portal->next[side];
3262 if (!portal->numpoints)
3265 other_node = portal->nodes[!side];
3266 RemovePortalFromNodes(portal);
3268 // cut the portal into two portals, one on each side of the node plane
3269 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);
3271 if (!numfrontpoints)
3274 AddPortalToNodes(portal, back, other_node);
3276 AddPortalToNodes(portal, other_node, back);
3282 AddPortalToNodes(portal, front, other_node);
3284 AddPortalToNodes(portal, other_node, front);
3288 // the portal is split
3289 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3290 temp = splitportal->chain;
3291 *splitportal = *portal;
3292 splitportal->chain = temp;
3293 for (i = 0;i < numbackpoints*3;i++)
3294 splitportal->points[i] = backpoints[i];
3295 splitportal->numpoints = numbackpoints;
3296 for (i = 0;i < numfrontpoints*3;i++)
3297 portal->points[i] = frontpoints[i];
3298 portal->numpoints = numfrontpoints;
3302 AddPortalToNodes(portal, front, other_node);
3303 AddPortalToNodes(splitportal, back, other_node);
3307 AddPortalToNodes(portal, other_node, front);
3308 AddPortalToNodes(splitportal, other_node, back);
3312 Mod_Q1BSP_RecursiveNodePortals(front);
3313 Mod_Q1BSP_RecursiveNodePortals(back);
3315 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3318 static void Mod_Q1BSP_MakePortals(void)
3320 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3321 portalpointsbufferoffset = 0;
3322 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3323 portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3324 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3325 Mem_Free(portalpointsbuffer);
3326 portalpointsbuffer = NULL;
3327 portalpointsbufferoffset = 0;
3328 portalpointsbuffersize = 0;
3329 Mod_Q1BSP_FinalizePortals();
3330 Mem_ExpandableArray_FreeArray(&portalarray);
3333 //Returns PVS data for a given point
3334 //(note: can return NULL)
3335 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3338 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3340 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3341 if (((mleaf_t *)node)->clusterindex >= 0)
3342 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3347 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)
3351 float d = PlaneDiff(org, node->plane);
3353 node = node->children[0];
3354 else if (d < -radius)
3355 node = node->children[1];
3358 // go down both sides
3359 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3360 node = node->children[1];
3363 // if this leaf is in a cluster, accumulate the pvs bits
3364 if (((mleaf_t *)node)->clusterindex >= 0)
3367 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3368 for (i = 0;i < pvsbytes;i++)
3369 pvsbuffer[i] |= pvs[i];
3373 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3374 //of the given point.
3375 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3377 int bytes = model->brush.num_pvsclusterbytes;
3378 bytes = min(bytes, pvsbufferlength);
3379 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3381 memset(pvsbuffer, 0xFF, bytes);
3385 memset(pvsbuffer, 0, bytes);
3386 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3390 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3395 VectorSubtract(inmaxs, inmins, size);
3396 if (cmodel->brush.ishlbsp)
3399 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3400 else if (size[0] <= 32)
3402 if (size[2] < 54) // pick the nearest of 36 or 72
3403 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3405 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3408 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3413 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3414 else if (size[0] <= 32)
3415 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3417 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3419 VectorCopy(inmins, outmins);
3420 VectorAdd(inmins, hull->clip_size, outmaxs);
3423 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3426 int numshadowmeshtriangles = 0;
3427 msurface_t *surface;
3428 if (cls.state == ca_dedicated)
3430 // make a single combined shadow mesh to allow optimized shadow volume creation
3432 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3434 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3435 numshadowmeshtriangles += surface->num_triangles;
3437 mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3438 for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3439 if (surface->num_triangles > 0)
3440 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));
3441 mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, true, false);
3442 if (mod->brush.shadowmesh)
3443 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3445 return numshadowmeshtriangles;
3448 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3453 float dist, modelyawradius, modelradius;
3454 msurface_t *surface;
3455 hullinfo_t hullinfo;
3456 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3457 model_brush_lightstyleinfo_t styleinfo[256];
3458 unsigned char *datapointer;
3460 mod->modeldatatypestring = "Q1BSP";
3462 mod->type = mod_brushq1;
3464 header = (dheader_t *)buffer;
3466 i = LittleLong(header->version);
3467 if (i != BSPVERSION && i != 30)
3468 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3469 mod->brush.ishlbsp = i == 30;
3471 // fill in hull info
3472 VectorClear (hullinfo.hullsizes[0][0]);
3473 VectorClear (hullinfo.hullsizes[0][1]);
3474 if (mod->brush.ishlbsp)
3476 mod->modeldatatypestring = "HLBSP";
3478 hullinfo.filehulls = 4;
3479 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3480 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3481 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3482 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3483 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3484 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3488 hullinfo.filehulls = 4;
3489 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3490 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3491 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3492 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3496 mod_base = (unsigned char*)buffer;
3497 for (i = 0; i < HEADER_LUMPS; i++)
3499 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3500 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3503 mod->soundfromcenter = true;
3504 mod->TraceBox = Mod_Q1BSP_TraceBox;
3505 mod->TraceLine = Mod_Q1BSP_TraceLine;
3506 mod->TracePoint = Mod_Q1BSP_TracePoint;
3507 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3508 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3509 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3510 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3511 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3512 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3513 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3514 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3515 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3516 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3517 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3518 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3519 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3520 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3521 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3522 mod->Draw = R_Q1BSP_Draw;
3523 mod->DrawDepth = R_Q1BSP_DrawDepth;
3524 mod->DrawDebug = R_Q1BSP_DrawDebug;
3525 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3526 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3527 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3528 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3529 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3530 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3531 mod->DrawLight = R_Q1BSP_DrawLight;
3535 mod->brush.qw_md4sum = 0;
3536 mod->brush.qw_md4sum2 = 0;
3537 for (i = 0;i < HEADER_LUMPS;i++)
3540 if (i == LUMP_ENTITIES)
3542 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3543 mod->brush.qw_md4sum ^= LittleLong(temp);
3544 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3546 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3547 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3550 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3551 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3552 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3553 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3554 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3555 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3556 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3557 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3558 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3559 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3560 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3561 // load submodels before leafs because they contain the number of vis leafs
3562 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3563 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3564 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3565 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3567 // check if the map supports transparent water rendering
3568 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3570 if (mod->brushq1.data_compressedpvs)
3571 Mem_Free(mod->brushq1.data_compressedpvs);
3572 mod->brushq1.data_compressedpvs = NULL;
3573 mod->brushq1.num_compressedpvs = 0;
3575 Mod_Q1BSP_MakeHull0();
3576 Mod_Q1BSP_MakePortals();
3578 mod->numframes = 2; // regular and alternate animation
3581 // make a single combined shadow mesh to allow optimized shadow volume creation
3582 Mod_Q1BSP_CreateShadowMesh(loadmodel);
3584 if (loadmodel->brush.numsubmodels)
3585 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3587 // LordHavoc: to clear the fog around the original quake submodel code, I
3589 // first of all, some background info on the submodels:
3590 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3591 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3592 // now the weird for loop itself:
3593 // the loop functions in an odd way, on each iteration it sets up the
3594 // current 'mod' model (which despite the confusing code IS the model of
3595 // the number i), at the end of the loop it duplicates the model to become
3596 // the next submodel, and loops back to set up the new submodel.
3598 // LordHavoc: now the explanation of my sane way (which works identically):
3599 // set up the world model, then on each submodel copy from the world model
3600 // and set up the submodel with the respective model info.
3601 totalstylesurfaces = 0;
3603 for (i = 0;i < mod->brush.numsubmodels;i++)
3605 memset(stylecounts, 0, sizeof(stylecounts));
3606 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3608 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3609 for (j = 0;j < MAXLIGHTMAPS;j++)
3610 stylecounts[surface->lightmapinfo->styles[j]]++;
3612 for (k = 0;k < 255;k++)
3616 totalstylesurfaces += stylecounts[k];
3619 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3620 for (i = 0;i < mod->brush.numsubmodels;i++)
3622 // LordHavoc: this code was originally at the end of this loop, but
3623 // has been transformed to something more readable at the start here.
3628 // duplicate the basic information
3629 dpsnprintf(name, sizeof(name), "*%i", i);
3630 mod = Mod_FindName(name, loadmodel->name);
3631 // copy the base model to this one
3633 // rename the clone back to its proper name
3634 strlcpy(mod->name, name, sizeof(mod->name));
3635 mod->brush.parentmodel = loadmodel;
3636 // textures and memory belong to the main model
3637 mod->texturepool = NULL;
3638 mod->mempool = NULL;
3639 mod->brush.GetPVS = NULL;
3640 mod->brush.FatPVS = NULL;
3641 mod->brush.BoxTouchingPVS = NULL;
3642 mod->brush.BoxTouchingLeafPVS = NULL;
3643 mod->brush.BoxTouchingVisibleLeafs = NULL;
3644 mod->brush.FindBoxClusters = NULL;
3645 mod->brush.LightPoint = NULL;
3646 mod->brush.AmbientSoundLevelsForPoint = NULL;
3649 mod->brush.submodel = i;
3651 if (loadmodel->brush.submodels)
3652 loadmodel->brush.submodels[i] = mod;
3654 bm = &mod->brushq1.submodels[i];
3656 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3657 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3659 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3660 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3663 mod->firstmodelsurface = bm->firstface;
3664 mod->nummodelsurfaces = bm->numfaces;
3666 // set node/leaf parents for this submodel
3667 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3669 // make the model surface list (used by shadowing/lighting)
3670 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3671 Mod_MakeSortedSurfaces(mod);
3673 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3674 // (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)
3675 VectorCopy(bm->mins, mod->normalmins);
3676 VectorCopy(bm->maxs, mod->normalmaxs);
3677 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3678 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3679 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3680 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3681 modelradius = modelyawradius + modelradius * modelradius;
3682 modelyawradius = sqrt(modelyawradius);
3683 modelradius = sqrt(modelradius);
3684 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3685 mod->yawmins[2] = mod->normalmins[2];
3686 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3687 mod->yawmaxs[2] = mod->normalmaxs[2];
3688 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3689 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3690 mod->radius = modelradius;
3691 mod->radius2 = modelradius * modelradius;
3693 // this gets altered below if sky or water is used
3694 mod->DrawSky = NULL;
3695 mod->DrawAddWaterPlanes = NULL;
3697 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3698 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3699 if (mod->nummodelsurfaces)
3701 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3702 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3704 if (j < mod->nummodelsurfaces)
3705 mod->DrawSky = R_Q1BSP_DrawSky;
3707 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3708 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
3710 if (j < mod->nummodelsurfaces)
3711 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3713 // build lightstyle update chains
3714 // (used to rapidly mark lightmapupdateflags on many surfaces
3715 // when d_lightstylevalue changes)
3716 memset(stylecounts, 0, sizeof(stylecounts));
3717 for (k = 0;k < mod->nummodelsurfaces;k++)
3719 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3720 for (j = 0;j < MAXLIGHTMAPS;j++)
3721 stylecounts[surface->lightmapinfo->styles[j]]++;
3723 mod->brushq1.num_lightstyles = 0;
3724 for (k = 0;k < 255;k++)
3728 styleinfo[mod->brushq1.num_lightstyles].style = k;
3729 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3730 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3731 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3732 remapstyles[k] = mod->brushq1.num_lightstyles;
3733 mod->brushq1.num_lightstyles++;
3736 for (k = 0;k < mod->nummodelsurfaces;k++)
3738 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3739 for (j = 0;j < MAXLIGHTMAPS;j++)
3741 if (surface->lightmapinfo->styles[j] != 255)
3743 int r = remapstyles[surface->lightmapinfo->styles[j]];
3744 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3748 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3749 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3753 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3754 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3756 //mod->brushq1.num_visleafs = bm->visleafs;
3758 if (mod_q1bsp_polygoncollisions.integer)
3760 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
3761 // point traces and contents checks still use the bsp tree
3762 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3763 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3764 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
3767 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
3769 // generate VBOs and other shared data before cloning submodels
3773 Mod_Q1BSP_LoadMapBrushes();
3774 //Mod_Q1BSP_ProcessLightList();
3778 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);
3781 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3785 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3792 in = (void *)(mod_base + l->fileofs);
3793 if (l->filelen % sizeof(*in))
3794 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3795 count = l->filelen / sizeof(*in);
3796 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3799 loadmodel->num = count;
3801 for (i = 0;i < count;i++, in++, out++)
3807 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3814 in = (void *)(mod_base + l->fileofs);
3815 if (l->filelen % sizeof(*in))
3816 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3817 count = l->filelen / sizeof(*in);
3818 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3821 loadmodel->num = count;
3823 for (i = 0;i < count;i++, in++, out++)
3829 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3836 in = (void *)(mod_base + l->fileofs);
3837 if (l->filelen % sizeof(*in))
3838 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3839 count = l->filelen / sizeof(*in);
3840 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3843 loadmodel->num = count;
3845 for (i = 0;i < count;i++, in++, out++)
3851 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3858 in = (void *)(mod_base + l->fileofs);
3859 if (l->filelen % sizeof(*in))
3860 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3861 count = l->filelen / sizeof(*in);
3862 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3865 loadmodel->num = count;
3867 for (i = 0;i < count;i++, in++, out++)
3873 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3880 in = (void *)(mod_base + l->fileofs);
3881 if (l->filelen % sizeof(*in))
3882 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3883 count = l->filelen / sizeof(*in);
3884 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3887 loadmodel->num = count;
3889 for (i = 0;i < count;i++, in++, out++)
3895 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3902 in = (void *)(mod_base + l->fileofs);
3903 if (l->filelen % sizeof(*in))
3904 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3905 count = l->filelen / sizeof(*in);
3906 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3909 loadmodel->num = count;
3911 for (i = 0;i < count;i++, in++, out++)
3917 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3924 in = (void *)(mod_base + l->fileofs);
3925 if (l->filelen % sizeof(*in))
3926 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3927 count = l->filelen / sizeof(*in);
3928 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3931 loadmodel->num = count;
3933 for (i = 0;i < count;i++, in++, out++)
3939 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3946 in = (void *)(mod_base + l->fileofs);
3947 if (l->filelen % sizeof(*in))
3948 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3949 count = l->filelen / sizeof(*in);
3950 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3953 loadmodel->num = count;
3955 for (i = 0;i < count;i++, in++, out++)
3961 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3968 in = (void *)(mod_base + l->fileofs);
3969 if (l->filelen % sizeof(*in))
3970 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3971 count = l->filelen / sizeof(*in);
3972 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3975 loadmodel->num = count;
3977 for (i = 0;i < count;i++, in++, out++)
3983 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3990 in = (void *)(mod_base + l->fileofs);
3991 if (l->filelen % sizeof(*in))
3992 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3993 count = l->filelen / sizeof(*in);
3994 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3997 loadmodel->num = count;
3999 for (i = 0;i < count;i++, in++, out++)
4005 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4012 in = (void *)(mod_base + l->fileofs);
4013 if (l->filelen % sizeof(*in))
4014 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4015 count = l->filelen / sizeof(*in);
4016 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4019 loadmodel->num = count;
4021 for (i = 0;i < count;i++, in++, out++)
4027 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4034 in = (void *)(mod_base + l->fileofs);
4035 if (l->filelen % sizeof(*in))
4036 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4037 count = l->filelen / sizeof(*in);
4038 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4041 loadmodel->num = count;
4043 for (i = 0;i < count;i++, in++, out++)
4049 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4056 in = (void *)(mod_base + l->fileofs);
4057 if (l->filelen % sizeof(*in))
4058 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4059 count = l->filelen / sizeof(*in);
4060 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4063 loadmodel->num = count;
4065 for (i = 0;i < count;i++, in++, out++)
4071 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4078 in = (void *)(mod_base + l->fileofs);
4079 if (l->filelen % sizeof(*in))
4080 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4081 count = l->filelen / sizeof(*in);
4082 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4085 loadmodel->num = count;
4087 for (i = 0;i < count;i++, in++, out++)
4093 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4100 in = (void *)(mod_base + l->fileofs);
4101 if (l->filelen % sizeof(*in))
4102 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4103 count = l->filelen / sizeof(*in);
4104 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4107 loadmodel->num = count;
4109 for (i = 0;i < count;i++, in++, out++)
4115 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4122 in = (void *)(mod_base + l->fileofs);
4123 if (l->filelen % sizeof(*in))
4124 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4125 count = l->filelen / sizeof(*in);
4126 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4129 loadmodel->num = count;
4131 for (i = 0;i < count;i++, in++, out++)
4137 static void Mod_Q2BSP_LoadModels(lump_t *l)
4144 in = (void *)(mod_base + l->fileofs);
4145 if (l->filelen % sizeof(*in))
4146 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4147 count = l->filelen / sizeof(*in);
4148 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4151 loadmodel->num = count;
4153 for (i = 0;i < count;i++, in++, out++)
4159 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4162 q2dheader_t *header;
4164 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4166 mod->modeldatatypestring = "Q2BSP";
4168 mod->type = mod_brushq2;
4170 header = (q2dheader_t *)buffer;
4172 i = LittleLong(header->version);
4173 if (i != Q2BSPVERSION)
4174 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4176 mod_base = (unsigned char *)header;
4178 // swap all the lumps
4179 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4180 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4182 mod->brush.qw_md4sum = 0;
4183 mod->brush.qw_md4sum2 = 0;
4184 for (i = 0;i < Q2HEADER_LUMPS;i++)
4186 if (i == Q2LUMP_ENTITIES)
4188 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4189 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4191 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4194 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4195 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4196 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4197 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4198 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4199 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4200 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4201 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4202 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4203 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4204 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4205 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4206 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4207 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4208 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4209 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4210 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4211 // LordHavoc: must go last because this makes the submodels
4212 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4215 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4216 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4218 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4221 char key[128], value[MAX_INPUTLINE];
4223 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4224 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4225 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4228 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4229 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4230 loadmodel->brush.entities[l->filelen] = 0;
4231 data = loadmodel->brush.entities;
4232 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4233 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4234 loadmodel->brushq3.deluxemapping = false;
4235 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4239 if (!COM_ParseToken_Simple(&data, false, false))
4241 if (com_token[0] == '}')
4242 break; // end of worldspawn
4243 if (com_token[0] == '_')
4244 strlcpy(key, com_token + 1, sizeof(key));
4246 strlcpy(key, com_token, sizeof(key));
4247 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4248 key[strlen(key)-1] = 0;
4249 if (!COM_ParseToken_Simple(&data, false, false))
4251 strlcpy(value, com_token, sizeof(value));
4252 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4254 #if _MSC_VER >= 1400
4255 #define sscanf sscanf_s
4258 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4259 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4261 VectorSet(v, 64, 64, 128);
4262 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4263 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]);
4264 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4265 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4268 else if (!strcmp("deluxeMaps", key))
4270 if (!strcmp(com_token, "1"))
4272 loadmodel->brushq3.deluxemapping = true;
4273 loadmodel->brushq3.deluxemapping_modelspace = true;
4275 else if (!strcmp(com_token, "2"))
4277 loadmodel->brushq3.deluxemapping = true;
4278 loadmodel->brushq3.deluxemapping_modelspace = false;
4285 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4291 in = (q3dtexture_t *)(mod_base + l->fileofs);
4292 if (l->filelen % sizeof(*in))
4293 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4294 count = l->filelen / sizeof(*in);
4295 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4297 loadmodel->data_textures = out;
4298 loadmodel->num_textures = count;
4299 loadmodel->num_texturesperskin = loadmodel->num_textures;
4301 for (i = 0;i < count;i++)
4303 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4304 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4305 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4306 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4307 // restore the surfaceflags and supercontents
4308 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4309 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4313 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4319 in = (q3dplane_t *)(mod_base + l->fileofs);
4320 if (l->filelen % sizeof(*in))
4321 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4322 count = l->filelen / sizeof(*in);
4323 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4325 loadmodel->brush.data_planes = out;
4326 loadmodel->brush.num_planes = count;
4328 for (i = 0;i < count;i++, in++, out++)
4330 out->normal[0] = LittleFloat(in->normal[0]);
4331 out->normal[1] = LittleFloat(in->normal[1]);
4332 out->normal[2] = LittleFloat(in->normal[2]);
4333 out->dist = LittleFloat(in->dist);
4338 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4341 q3mbrushside_t *out;
4344 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4345 if (l->filelen % sizeof(*in))
4346 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4347 count = l->filelen / sizeof(*in);
4348 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4350 loadmodel->brush.data_brushsides = out;
4351 loadmodel->brush.num_brushsides = count;
4353 for (i = 0;i < count;i++, in++, out++)
4355 n = LittleLong(in->planeindex);
4356 if (n < 0 || n >= loadmodel->brush.num_planes)
4357 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4358 out->plane = loadmodel->brush.data_planes + n;
4359 n = LittleLong(in->textureindex);
4360 if (n < 0 || n >= loadmodel->num_textures)
4361 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4362 out->texture = loadmodel->data_textures + n;
4366 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4368 q3dbrushside_ig_t *in;
4369 q3mbrushside_t *out;
4372 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4373 if (l->filelen % sizeof(*in))
4374 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4375 count = l->filelen / sizeof(*in);
4376 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4378 loadmodel->brush.data_brushsides = out;
4379 loadmodel->brush.num_brushsides = count;
4381 for (i = 0;i < count;i++, in++, out++)
4383 n = LittleLong(in->planeindex);
4384 if (n < 0 || n >= loadmodel->brush.num_planes)
4385 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4386 out->plane = loadmodel->brush.data_planes + n;
4387 n = LittleLong(in->textureindex);
4388 if (n < 0 || n >= loadmodel->num_textures)
4389 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4390 out->texture = loadmodel->data_textures + n;
4394 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4398 int i, j, n, c, count, maxplanes, q3surfaceflags;
4399 colplanef_t *planes;
4401 in = (q3dbrush_t *)(mod_base + l->fileofs);
4402 if (l->filelen % sizeof(*in))
4403 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4404 count = l->filelen / sizeof(*in);
4405 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4407 loadmodel->brush.data_brushes = out;
4408 loadmodel->brush.num_brushes = count;
4413 for (i = 0;i < count;i++, in++, out++)
4415 n = LittleLong(in->firstbrushside);
4416 c = LittleLong(in->numbrushsides);
4417 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4418 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4419 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4420 out->numbrushsides = c;
4421 n = LittleLong(in->textureindex);
4422 if (n < 0 || n >= loadmodel->num_textures)
4423 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4424 out->texture = loadmodel->data_textures + n;
4426 // make a list of mplane_t structs to construct a colbrush from
4427 if (maxplanes < out->numbrushsides)
4429 maxplanes = out->numbrushsides;
4432 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4435 for (j = 0;j < out->numbrushsides;j++)
4437 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4438 planes[j].dist = out->firstbrushside[j].plane->dist;
4439 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4440 planes[j].texture = out->firstbrushside[j].texture;
4441 q3surfaceflags |= planes[j].q3surfaceflags;
4443 // make the colbrush from the planes
4444 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4446 // this whole loop can take a while (e.g. on redstarrepublic4)
4447 CL_KeepaliveMessage(false);
4453 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4459 in = (q3deffect_t *)(mod_base + l->fileofs);
4460 if (l->filelen % sizeof(*in))
4461 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4462 count = l->filelen / sizeof(*in);
4463 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4465 loadmodel->brushq3.data_effects = out;
4466 loadmodel->brushq3.num_effects = count;
4468 for (i = 0;i < count;i++, in++, out++)
4470 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4471 n = LittleLong(in->brushindex);
4472 if (n >= loadmodel->brush.num_brushes)
4474 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4477 out->brushindex = n;
4478 out->unknown = LittleLong(in->unknown);
4482 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4487 in = (q3dvertex_t *)(mod_base + l->fileofs);
4488 if (l->filelen % sizeof(*in))
4489 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4490 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4491 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4492 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4493 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4494 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4495 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4497 for (i = 0;i < count;i++, in++)
4499 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4500 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4501 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4502 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4503 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4504 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4505 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4506 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4507 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4508 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4509 // svector/tvector are calculated later in face loading
4510 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4511 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4512 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4513 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4514 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4515 loadmodel->lit = true;
4519 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4525 in = (int *)(mod_base + l->fileofs);
4526 if (l->filelen % sizeof(int[3]))
4527 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4528 count = l->filelen / sizeof(*in);
4530 if(!loadmodel->brushq3.num_vertices)
4533 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4534 loadmodel->brushq3.num_triangles = 0;
4538 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4539 loadmodel->brushq3.num_triangles = count / 3;
4540 loadmodel->brushq3.data_element3i = out;
4542 for (i = 0;i < count;i++, in++, out++)
4544 *out = LittleLong(*in);
4545 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4547 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4553 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4555 q3dlightmap_t *input_pointer;
4573 int mergedrowsxcolumns;
4578 unsigned char *mergedpixels;
4579 unsigned char *mergeddeluxepixels;
4580 unsigned char *mergebuf;
4581 char mapname[MAX_QPATH];
4583 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4585 // defaults for q3bsp
4592 loadmodel->brushq3.lightmapsize = 128;
4594 if (cls.state == ca_dedicated)
4597 if(mod_q3bsp_nolightmaps.integer)
4603 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4604 if (developer_loading.integer)
4605 Con_Printf("Using internal lightmaps\n");
4606 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4607 if (l->filelen % sizeof(*input_pointer))
4608 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4609 count = l->filelen / sizeof(*input_pointer);
4610 for(i = 0; i < count; ++i)
4611 inpixels[i] = input_pointer[i].rgb;
4615 // no internal lightmaps
4616 // try external lightmaps
4617 if (developer_loading.integer)
4618 Con_Printf("Using external lightmaps\n");
4619 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4620 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false, NULL);
4624 // using EXTERNAL lightmaps instead
4625 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4627 Mem_Free(inpixels[0]);
4628 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4638 for(count = 1; ; ++count)
4640 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false, NULL);
4641 if(!inpixels[count])
4642 break; // we got all of them
4643 if(image_width != size || image_height != size)
4645 Mem_Free(inpixels[count]);
4646 inpixels[count] = NULL;
4647 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);
4653 loadmodel->brushq3.lightmapsize = size;
4654 loadmodel->brushq3.num_originallightmaps = count;
4656 // now check the surfaces to see if any of them index an odd numbered
4657 // lightmap, if so this is not a deluxemapped bsp file
4659 // also check what lightmaps are actually used, because q3map2 sometimes
4660 // (always?) makes an unused one at the end, which
4661 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4662 // reason when only one lightmap is used, which can throw off the
4663 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4664 // to see if the second lightmap is blank, if so it is not deluxemapped.
4665 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4666 // in Mod_Q3BSP_LoadEntities was failed
4667 if (!loadmodel->brushq3.deluxemapping)
4669 loadmodel->brushq3.deluxemapping = !(count & 1);
4670 loadmodel->brushq3.deluxemapping_modelspace = true;
4672 if (loadmodel->brushq3.deluxemapping)
4674 int facecount = faceslump->filelen / sizeof(q3dface_t);
4675 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4676 for (i = 0;i < facecount;i++)
4678 j = LittleLong(faces[i].lightmapindex);
4681 endlightmap = max(endlightmap, j + 1);
4682 if ((j & 1) || j + 1 >= count)
4684 loadmodel->brushq3.deluxemapping = false;
4691 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4692 // reason when only one lightmap is used, which can throw off the
4693 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4694 // to see if the second lightmap is blank, if so it is not deluxemapped.
4696 // further research has shown q3map2 sometimes creates a deluxemap and two
4697 // blank lightmaps, which must be handled properly as well
4698 if (endlightmap == 1 && count > 1)
4701 for (i = 0;i < size*size;i++)
4703 if (c[bytesperpixel*i + rgbmap[0]])
4705 if (c[bytesperpixel*i + rgbmap[1]])
4707 if (c[bytesperpixel*i + rgbmap[2]])
4712 // all pixels in the unused lightmap were black...
4713 loadmodel->brushq3.deluxemapping = false;
4718 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4720 // figure out what the most reasonable merge power is within limits
4722 // find the appropriate NxN dimensions to merge to, to avoid wasted space
4723 realcount = count >> (int)loadmodel->brushq3.deluxemapping;
4725 // figure out how big the merged texture has to be
4726 mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
4727 mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
4728 while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
4730 mergedwidth = mergegoal;
4731 mergedheight = mergegoal;
4732 // choose non-square size (2x1 aspect) if only half the space is used;
4733 // this really only happens when the entire set fits in one texture, if
4734 // there are multiple textures, we don't worry about shrinking the last
4735 // one to fit, because the driver prefers the same texture size on
4736 // consecutive draw calls...
4737 if (mergedwidth * mergedheight / 2 >= size*size*realcount)
4740 loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
4741 loadmodel->brushq3.num_lightmapmergedheightpower = 0;
4742 while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
4743 loadmodel->brushq3.num_lightmapmergedwidthpower++;
4744 while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
4745 loadmodel->brushq3.num_lightmapmergedheightpower++;
4746 loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
4748 powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
4749 powery = loadmodel->brushq3.num_lightmapmergedheightpower;
4750 powerxy = powerx+powery;
4751 powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
4753 mergedcolumns = 1 << powerx;
4754 mergedrows = 1 << powery;
4755 mergedrowsxcolumns = 1 << powerxy;
4757 loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
4758 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4759 if (loadmodel->brushq3.deluxemapping)
4760 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4762 // allocate a texture pool if we need it
4763 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4764 loadmodel->texturepool = R_AllocTexturePool();
4766 mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
4767 mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
4768 for (i = 0;i < count;i++)
4770 // figure out which merged lightmap texture this fits into
4771 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
4772 lightmapindex = i >> powerdxy;
4774 // choose the destination address
4775 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
4776 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
4777 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
4778 Con_Printf("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);
4780 // convert pixels from RGB or BGRA while copying them into the destination rectangle
4781 for (j = 0;j < size;j++)
4782 for (k = 0;k < size;k++)
4784 mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
4785 mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
4786 mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
4787 mergebuf[(j*mergedwidth+k)*4+3] = 255;
4790 // upload texture if this was the last tile being written to the texture
4791 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
4793 if (loadmodel->brushq3.deluxemapping && (i & 1))
4794 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);
4796 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);
4800 if (mergeddeluxepixels)
4801 Mem_Free(mergeddeluxepixels);
4802 Mem_Free(mergedpixels);
4805 for(i = 0; i < count; ++i)
4806 Mem_Free(inpixels[i]);
4810 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
4815 *collisionstride = stride;
4818 cnt = (num_triangles + stride - 1) / stride;
4819 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
4820 for(j = 0; j < cnt; ++j)
4822 mins = &((*collisionbbox6f)[6 * j + 0]);
4823 maxs = &((*collisionbbox6f)[6 * j + 3]);
4824 for(k = 0; k < stride; ++k)
4826 tri = j * stride + k;
4827 if(tri >= num_triangles)
4829 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
4830 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
4831 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
4832 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
4833 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
4834 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
4835 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
4836 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
4837 if(vert[0] < mins[0]) mins[0] = vert[0];
4838 if(vert[1] < mins[1]) mins[1] = vert[1];
4839 if(vert[2] < mins[2]) mins[2] = vert[2];
4840 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4841 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4842 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4843 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
4844 if(vert[0] < mins[0]) mins[0] = vert[0];
4845 if(vert[1] < mins[1]) mins[1] = vert[1];
4846 if(vert[2] < mins[2]) mins[2] = vert[2];
4847 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4848 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4849 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4854 *collisionbbox6f = NULL;
4857 typedef struct patchtess_s
4861 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
4864 float *originalvertex3f;
4867 #define PATCHTESS_SAME_LODGROUP(a,b) \
4869 (a).lodgroup[0] == (b).lodgroup[0] && \
4870 (a).lodgroup[1] == (b).lodgroup[1] && \
4871 (a).lodgroup[2] == (b).lodgroup[2] && \
4872 (a).lodgroup[3] == (b).lodgroup[3] && \
4873 (a).lodgroup[4] == (b).lodgroup[4] && \
4874 (a).lodgroup[5] == (b).lodgroup[5] \
4877 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4879 q3dface_t *in, *oldin;
4880 msurface_t *out, *oldout;
4881 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;
4882 float lightmaptcbase[2], lightmaptcscale[2];
4883 //int *originalelement3i;
4884 //int *originalneighbor3i;
4885 float *originalvertex3f;
4886 //float *originalsvector3f;
4887 //float *originaltvector3f;
4888 float *originalnormal3f;
4889 float *originalcolor4f;
4890 float *originaltexcoordtexture2f;
4891 float *originaltexcoordlightmap2f;
4892 float *surfacecollisionvertex3f;
4893 int *surfacecollisionelement3i;
4895 patchtess_t *patchtess = NULL;
4896 int patchtesscount = 0;
4899 in = (q3dface_t *)(mod_base + l->fileofs);
4900 if (l->filelen % sizeof(*in))
4901 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4902 count = l->filelen / sizeof(*in);
4903 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4905 loadmodel->data_surfaces = out;
4906 loadmodel->num_surfaces = count;
4909 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
4917 for (;i < count;i++, in++, out++)
4919 // check face type first
4920 type = LittleLong(in->type);
4921 if (type != Q3FACETYPE_FLAT
4922 && type != Q3FACETYPE_PATCH
4923 && type != Q3FACETYPE_MESH
4924 && type != Q3FACETYPE_FLARE)
4926 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4930 n = LittleLong(in->textureindex);
4931 if (n < 0 || n >= loadmodel->num_textures)
4933 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4936 out->texture = loadmodel->data_textures + n;
4937 n = LittleLong(in->effectindex);
4938 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4940 if (developer_extra.integer)
4941 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4947 out->effect = loadmodel->brushq3.data_effects + n;
4949 if (cls.state != ca_dedicated)
4951 out->lightmaptexture = NULL;
4952 out->deluxemaptexture = r_texture_blanknormalmap;
4953 n = LittleLong(in->lightmapindex);
4956 else if (n >= loadmodel->brushq3.num_originallightmaps)
4958 if(loadmodel->brushq3.num_originallightmaps != 0)
4959 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
4964 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
4965 if (loadmodel->brushq3.deluxemapping)
4966 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
4967 loadmodel->lit = true;
4971 firstvertex = LittleLong(in->firstvertex);
4972 numvertices = LittleLong(in->numvertices);
4973 firstelement = LittleLong(in->firstelement);
4974 numtriangles = LittleLong(in->numelements) / 3;
4975 if (numtriangles * 3 != LittleLong(in->numelements))
4977 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));
4980 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4982 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);
4985 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4987 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);
4992 case Q3FACETYPE_FLAT:
4993 case Q3FACETYPE_MESH:
4994 // no processing necessary
4996 case Q3FACETYPE_PATCH:
4997 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4998 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4999 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))
5001 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5004 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5006 // convert patch to Q3FACETYPE_MESH
5007 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5008 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5009 // bound to user settings
5010 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5011 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5012 // bound to sanity settings
5013 xtess = bound(0, xtess, 1024);
5014 ytess = bound(0, ytess, 1024);
5016 // lower quality collision patches! Same procedure as before, but different cvars
5017 // convert patch to Q3FACETYPE_MESH
5018 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5019 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5020 // bound to user settings
5021 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5022 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5023 // bound to sanity settings
5024 cxtess = bound(0, cxtess, 1024);
5025 cytess = bound(0, cytess, 1024);
5027 // store it for the LOD grouping step
5028 patchtess[patchtesscount].info.xsize = patchsize[0];
5029 patchtess[patchtesscount].info.ysize = patchsize[1];
5030 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5031 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5032 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5033 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5035 patchtess[patchtesscount].surface_id = i;
5036 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5037 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5038 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5039 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5040 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5041 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5042 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5045 case Q3FACETYPE_FLARE:
5046 if (developer_extra.integer)
5047 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5051 out->num_vertices = numvertices;
5052 out->num_triangles = numtriangles;
5053 meshvertices += out->num_vertices;
5054 meshtriangles += out->num_triangles;
5057 // Fix patches tesselations so that they make no seams
5061 for(i = 0; i < patchtesscount; ++i)
5063 for(j = i+1; j < patchtesscount; ++j)
5065 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5068 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5075 // Calculate resulting number of triangles
5076 collisionvertices = 0;
5077 collisiontriangles = 0;
5078 for(i = 0; i < patchtesscount; ++i)
5080 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5081 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5082 numvertices = finalwidth * finalheight;
5083 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5085 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5086 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5087 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5088 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5090 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5091 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5092 numvertices = finalwidth * finalheight;
5093 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5095 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5096 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5097 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5098 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5104 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5105 if (collisiontriangles)
5107 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5108 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5112 collisionvertices = 0;
5113 collisiontriangles = 0;
5114 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5116 if (out->num_vertices < 3 || out->num_triangles < 1)
5119 type = LittleLong(in->type);
5120 firstvertex = LittleLong(in->firstvertex);
5121 firstelement = LittleLong(in->firstelement);
5122 out->num_firstvertex = meshvertices;
5123 out->num_firsttriangle = meshtriangles;
5124 out->num_firstcollisiontriangle = collisiontriangles;
5127 case Q3FACETYPE_FLAT:
5128 case Q3FACETYPE_MESH:
5129 // no processing necessary, except for lightmap merging
5130 for (j = 0;j < out->num_vertices;j++)
5132 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5133 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5134 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5135 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5136 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5137 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5138 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5139 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5140 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5141 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5142 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5143 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5144 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5145 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5147 for (j = 0;j < out->num_triangles*3;j++)
5148 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5150 case Q3FACETYPE_PATCH:
5151 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5152 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5153 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5154 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5155 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5156 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5157 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5159 xtess = ytess = cxtess = cytess = -1;
5160 for(j = 0; j < patchtesscount; ++j)
5161 if(patchtess[j].surface_id == i)
5163 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5164 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5165 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5166 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5171 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5172 xtess = ytess = cxtess = cytess = 0;
5175 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5176 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5177 finalvertices = finalwidth * finalheight;
5178 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5179 type = Q3FACETYPE_MESH;
5180 // generate geometry
5181 // (note: normals are skipped because they get recalculated)
5182 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5183 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5184 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5185 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5186 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5187 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5189 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);
5191 if (developer_extra.integer)
5193 if (out->num_triangles < finaltriangles)
5194 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);
5196 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);
5198 // q3map does not put in collision brushes for curves... ugh
5199 // build the lower quality collision geometry
5200 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5201 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5202 finalvertices = finalwidth * finalheight;
5203 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5205 // legacy collision geometry implementation
5206 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5207 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5208 out->num_collisionvertices = finalvertices;
5209 out->num_collisiontriangles = finaltriangles;
5210 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5211 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5213 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5214 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5216 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5218 // now optimize the collision mesh by finding triangle bboxes...
5219 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5220 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);
5222 // store collision geometry for BIH collision tree
5223 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5224 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5225 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5226 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5227 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5229 // remove this once the legacy code is removed
5231 int nc = out->num_collisiontriangles;
5233 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5235 if(nc != out->num_collisiontriangles)
5237 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5242 if (developer_extra.integer)
5243 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);
5245 collisionvertices += finalvertices;
5246 collisiontriangles += out->num_collisiontriangles;
5251 meshvertices += out->num_vertices;
5252 meshtriangles += out->num_triangles;
5253 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5254 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)
5256 if (invalidelements)
5258 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);
5259 for (j = 0;j < out->num_triangles * 3;j++)
5261 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5262 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)
5263 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5267 // calculate a bounding box
5268 VectorClear(out->mins);
5269 VectorClear(out->maxs);
5270 if (out->num_vertices)
5272 if (cls.state != ca_dedicated && out->lightmaptexture)
5274 // figure out which part of the merged lightmap this fits into
5275 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5276 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5277 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5278 lightmapindex &= mergewidth * mergeheight - 1;
5279 lightmaptcscale[0] = 1.0f / mergewidth;
5280 lightmaptcscale[1] = 1.0f / mergeheight;
5281 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5282 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5283 // modify the lightmap texcoords to match this region of the merged lightmap
5284 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5286 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5287 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5290 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5291 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5292 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5294 out->mins[0] = min(out->mins[0], v[0]);
5295 out->maxs[0] = max(out->maxs[0], v[0]);
5296 out->mins[1] = min(out->mins[1], v[1]);
5297 out->maxs[1] = max(out->maxs[1], v[1]);
5298 out->mins[2] = min(out->mins[2], v[2]);
5299 out->maxs[2] = max(out->maxs[2], v[2]);
5301 out->mins[0] -= 1.0f;
5302 out->mins[1] -= 1.0f;
5303 out->mins[2] -= 1.0f;
5304 out->maxs[0] += 1.0f;
5305 out->maxs[1] += 1.0f;
5306 out->maxs[2] += 1.0f;
5308 // set lightmap styles for consistency with q1bsp
5309 //out->lightmapinfo->styles[0] = 0;
5310 //out->lightmapinfo->styles[1] = 255;
5311 //out->lightmapinfo->styles[2] = 255;
5312 //out->lightmapinfo->styles[3] = 255;
5317 for (;i < count;i++, out++)
5319 if(out->num_vertices && out->num_triangles)
5321 if(out->num_vertices == 0)
5323 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5324 if(out->num_triangles == 0)
5325 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5327 else if(out->num_triangles == 0)
5328 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)",
5329 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5330 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5331 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5334 // for per pixel lighting
5335 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, true);
5337 // generate ushort elements array if possible
5338 if (loadmodel->surfmesh.data_element3s)
5339 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5340 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5342 // free the no longer needed vertex data
5343 loadmodel->brushq3.num_vertices = 0;
5344 if (loadmodel->brushq3.data_vertex3f)
5345 Mem_Free(loadmodel->brushq3.data_vertex3f);
5346 loadmodel->brushq3.data_vertex3f = NULL;
5347 loadmodel->brushq3.data_normal3f = NULL;
5348 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5349 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5350 loadmodel->brushq3.data_color4f = NULL;
5351 // free the no longer needed triangle data
5352 loadmodel->brushq3.num_triangles = 0;
5353 if (loadmodel->brushq3.data_element3i)
5354 Mem_Free(loadmodel->brushq3.data_element3i);
5355 loadmodel->brushq3.data_element3i = NULL;
5358 Mem_Free(patchtess);
5361 static void Mod_Q3BSP_LoadModels(lump_t *l)
5365 int i, j, n, c, count;
5367 in = (q3dmodel_t *)(mod_base + l->fileofs);
5368 if (l->filelen % sizeof(*in))
5369 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5370 count = l->filelen / sizeof(*in);
5371 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5373 loadmodel->brushq3.data_models = out;
5374 loadmodel->brushq3.num_models = count;
5376 for (i = 0;i < count;i++, in++, out++)
5378 for (j = 0;j < 3;j++)
5380 out->mins[j] = LittleFloat(in->mins[j]);
5381 out->maxs[j] = LittleFloat(in->maxs[j]);
5383 n = LittleLong(in->firstface);
5384 c = LittleLong(in->numfaces);
5385 if (n < 0 || n + c > loadmodel->num_surfaces)
5386 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5389 n = LittleLong(in->firstbrush);
5390 c = LittleLong(in->numbrushes);
5391 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5392 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5393 out->firstbrush = n;
5394 out->numbrushes = c;
5398 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5404 in = (int *)(mod_base + l->fileofs);
5405 if (l->filelen % sizeof(*in))
5406 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5407 count = l->filelen / sizeof(*in);
5408 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5410 loadmodel->brush.data_leafbrushes = out;
5411 loadmodel->brush.num_leafbrushes = count;
5413 for (i = 0;i < count;i++, in++, out++)
5415 n = LittleLong(*in);
5416 if (n < 0 || n >= loadmodel->brush.num_brushes)
5417 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5422 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5428 in = (int *)(mod_base + l->fileofs);
5429 if (l->filelen % sizeof(*in))
5430 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5431 count = l->filelen / sizeof(*in);
5432 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5434 loadmodel->brush.data_leafsurfaces = out;
5435 loadmodel->brush.num_leafsurfaces = count;
5437 for (i = 0;i < count;i++, in++, out++)
5439 n = LittleLong(*in);
5440 if (n < 0 || n >= loadmodel->num_surfaces)
5441 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5446 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5450 int i, j, n, c, count;
5452 in = (q3dleaf_t *)(mod_base + l->fileofs);
5453 if (l->filelen % sizeof(*in))
5454 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5455 count = l->filelen / sizeof(*in);
5456 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5458 loadmodel->brush.data_leafs = out;
5459 loadmodel->brush.num_leafs = count;
5461 for (i = 0;i < count;i++, in++, out++)
5465 out->clusterindex = LittleLong(in->clusterindex);
5466 out->areaindex = LittleLong(in->areaindex);
5467 for (j = 0;j < 3;j++)
5469 // yes the mins/maxs are ints
5470 out->mins[j] = LittleLong(in->mins[j]) - 1;
5471 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5473 n = LittleLong(in->firstleafface);
5474 c = LittleLong(in->numleaffaces);
5475 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5476 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5477 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5478 out->numleafsurfaces = c;
5479 n = LittleLong(in->firstleafbrush);
5480 c = LittleLong(in->numleafbrushes);
5481 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5482 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5483 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5484 out->numleafbrushes = c;
5488 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5494 in = (q3dnode_t *)(mod_base + l->fileofs);
5495 if (l->filelen % sizeof(*in))
5496 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5497 count = l->filelen / sizeof(*in);
5498 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5500 loadmodel->brush.data_nodes = out;
5501 loadmodel->brush.num_nodes = count;
5503 for (i = 0;i < count;i++, in++, out++)
5506 n = LittleLong(in->planeindex);
5507 if (n < 0 || n >= loadmodel->brush.num_planes)
5508 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5509 out->plane = loadmodel->brush.data_planes + n;
5510 for (j = 0;j < 2;j++)
5512 n = LittleLong(in->childrenindex[j]);
5515 if (n >= loadmodel->brush.num_nodes)
5516 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5517 out->children[j] = loadmodel->brush.data_nodes + n;
5522 if (n >= loadmodel->brush.num_leafs)
5523 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5524 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5527 for (j = 0;j < 3;j++)
5529 // yes the mins/maxs are ints
5530 out->mins[j] = LittleLong(in->mins[j]) - 1;
5531 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5535 // set the parent pointers
5536 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5539 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5542 q3dlightgrid_t *out;
5545 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5546 if (l->filelen % sizeof(*in))
5547 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5548 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5549 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5550 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5551 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5552 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5553 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5554 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5555 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5556 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5557 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5558 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5559 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5560 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5561 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]);
5562 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]);
5564 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5567 if (l->filelen < count * (int)sizeof(*in))
5569 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]);
5570 return; // ignore the grid if we cannot understand it
5572 if (l->filelen != count * (int)sizeof(*in))
5573 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5574 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5575 loadmodel->brushq3.data_lightgrid = out;
5576 loadmodel->brushq3.num_lightgrid = count;
5577 // no swapping or validation necessary
5578 memcpy(out, in, count * (int)sizeof(*out));
5582 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5587 if (l->filelen == 0)
5590 // unvised maps often have cluster indices even without pvs, so check
5591 // leafs to find real number of clusters
5592 loadmodel->brush.num_pvsclusters = 1;
5593 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5594 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5597 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5598 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5599 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5600 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5604 in = (q3dpvs_t *)(mod_base + l->fileofs);
5606 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5608 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5609 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5610 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5611 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5612 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5613 if (l->filelen < totalchains + (int)sizeof(*in))
5614 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);
5616 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5617 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5620 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5622 int i, j, k, index[3];
5623 float transformed[3], blend1, blend2, blend, stylescale;
5624 q3dlightgrid_t *a, *s;
5626 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5627 if (vid.renderpath == RENDERPATH_GL20)
5628 stylescale = 1; // added while render
5630 stylescale = r_refdef.scene.rtlightstylevalue[0];
5632 if (!model->brushq3.num_lightgrid)
5634 ambientcolor[0] = stylescale;
5635 ambientcolor[1] = stylescale;
5636 ambientcolor[2] = stylescale;
5640 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5641 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5642 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5643 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5644 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5645 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5646 index[0] = (int)floor(transformed[0]);
5647 index[1] = (int)floor(transformed[1]);
5648 index[2] = (int)floor(transformed[2]);
5649 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5651 // now lerp the values
5652 VectorClear(diffusenormal);
5653 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5654 for (k = 0;k < 2;k++)
5656 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5657 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5659 for (j = 0;j < 2;j++)
5661 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5662 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5664 for (i = 0;i < 2;i++)
5666 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5667 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5669 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5670 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5671 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5672 // this uses the mod_md3_sin table because the values are
5673 // already in the 0-255 range, the 64+ bias fetches a cosine
5674 // instead of a sine value
5675 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5676 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5677 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5678 //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)));
5683 // normalize the light direction before turning
5684 VectorNormalize(diffusenormal);
5685 //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]);
5688 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5691 double midf, mid[3];
5697 // find the point distances
5698 mplane_t *plane = node->plane;
5699 if (plane->type < 3)
5701 t1 = p1[plane->type] - plane->dist;
5702 t2 = p2[plane->type] - plane->dist;
5706 t1 = DotProduct (plane->normal, p1) - plane->dist;
5707 t2 = DotProduct (plane->normal, p2) - plane->dist;
5714 node = node->children[1];
5723 node = node->children[0];
5729 midf = t1 / (t1 - t2);
5730 VectorLerp(p1, midf, p2, mid);
5732 // recurse both sides, front side first
5733 // return 2 if empty is followed by solid (hit something)
5734 // do not return 2 if both are solid or both empty,
5735 // or if start is solid and end is empty
5736 // as these degenerate cases usually indicate the eye is in solid and
5737 // should see the target point anyway
5738 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5741 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5746 return ((mleaf_t *)node)->clusterindex < 0;
5749 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5751 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5754 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5755 return trace.fraction == 1;
5759 double tracestart[3], traceend[3];
5760 VectorCopy(start, tracestart);
5761 VectorCopy(end, traceend);
5762 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5766 static void Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t point)
5768 const bih_leaf_t *leaf;
5769 const bih_node_t *node;
5770 const colbrushf_t *brush;
5772 while (nodenum >= 0)
5774 node = model->collision_bih.nodes + nodenum;
5775 axis = node->type - BIH_SPLITX;
5776 if (point[axis] <= node->backmax)
5778 if (point[axis] >= node->frontmin)
5779 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, node->front, point);
5780 nodenum = node->back;
5782 else if (point[axis] >= node->frontmin)
5783 nodenum = node->front;
5784 else // no overlap with either child? just return
5787 if (!model->collision_bih.leafs)
5789 leaf = model->collision_bih.leafs + (-1-nodenum);
5793 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5794 Collision_TracePointBrushFloat(trace, point, brush);
5796 case BIH_COLLISIONTRIANGLE:
5797 // collision triangle - skipped because they have no volume
5799 case BIH_RENDERTRIANGLE:
5800 // render triangle - skipped because they have no volume
5805 static void Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t start, const vec3_t end, const vec3_t linestart, const vec3_t lineend)
5807 const bih_leaf_t *leaf;
5808 const bih_node_t *node;
5809 const colbrushf_t *brush;
5811 const texture_t *texture;
5822 vec3_t clipped, newstart, newend;
5826 segmentmins[0] = min(start[0], end[0]);
5827 segmentmins[1] = min(start[1], end[1]);
5828 segmentmins[2] = min(start[2], end[2]);
5829 segmentmaxs[0] = max(start[0], end[0]);
5830 segmentmaxs[1] = max(start[1], end[1]);
5831 segmentmaxs[2] = max(start[2], end[2]);
5832 while (nodenum >= 0)
5834 node = model->collision_bih.nodes + nodenum;
5836 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
5839 axis = node->type - BIH_SPLITX;
5841 if (segmentmins[axis] <= node->backmax)
5843 if (segmentmaxs[axis] >= node->frontmin)
5844 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5845 nodenum = node->back;
5847 else if (segmentmaxs[axis] >= node->frontmin)
5848 nodenum = node->front;
5850 return; // trace falls between children
5852 frontdist1 = start[axis] - node->frontmin;
5853 frontdist2 = end[axis] - node->frontmin;
5854 backdist1 = start[axis] - node->backmax;
5855 backdist2 = end[axis] - node->backmax;
5868 if ((sideflags & 3) != 3)
5869 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5870 nodenum = node->back;
5872 else if ((sideflags & 3) != 3)
5873 nodenum = node->front;
5875 return; // trace falls between children
5880 // start end START END
5881 nodenum = node->front;
5884 // START end START END
5886 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5887 VectorLerp(start, frontfrac, end, newstart); start = newstart;
5888 segmentmins[0] = min(start[0], end[0]);
5889 segmentmins[1] = min(start[1], end[1]);
5890 segmentmins[2] = min(start[2], end[2]);
5891 segmentmaxs[0] = max(start[0], end[0]);
5892 segmentmaxs[1] = max(start[1], end[1]);
5893 segmentmaxs[2] = max(start[2], end[2]);
5895 nodenum = node->front;
5899 // start END START END
5900 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5901 VectorLerp(start, frontfrac, end, newend); end = newend;
5902 segmentmins[0] = min(start[0], end[0]);
5903 segmentmins[1] = min(start[1], end[1]);
5904 segmentmins[2] = min(start[2], end[2]);
5905 segmentmaxs[0] = max(start[0], end[0]);
5906 segmentmaxs[1] = max(start[1], end[1]);
5907 segmentmaxs[2] = max(start[2], end[2]);
5909 nodenum = node->front;
5912 // START END START END
5913 return; // line falls in gap between children
5915 // start end start END
5916 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5918 backfrac = backdist1 / (backdist1 - backdist2);
5919 VectorLerp(start, backfrac, end, newend); end = newend;
5920 segmentmins[0] = min(start[0], end[0]);
5921 segmentmins[1] = min(start[1], end[1]);
5922 segmentmins[2] = min(start[2], end[2]);
5923 segmentmaxs[0] = max(start[0], end[0]);
5924 segmentmaxs[1] = max(start[1], end[1]);
5925 segmentmaxs[2] = max(start[2], end[2]);
5927 nodenum = node->back;
5930 // START end start END
5932 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5933 VectorLerp(start, frontfrac, end, clipped);
5934 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
5935 backfrac = backdist1 / (backdist1 - backdist2);
5936 VectorLerp(start, backfrac, end, newend); end = newend;
5937 segmentmins[0] = min(start[0], end[0]);
5938 segmentmins[1] = min(start[1], end[1]);
5939 segmentmins[2] = min(start[2], end[2]);
5940 segmentmaxs[0] = max(start[0], end[0]);
5941 segmentmaxs[1] = max(start[1], end[1]);
5942 segmentmaxs[2] = max(start[2], end[2]);
5944 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5946 nodenum = node->back;
5949 // start END start END
5951 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5952 VectorLerp(start, frontfrac, end, clipped);
5953 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
5954 backfrac = backdist1 / (backdist1 - backdist2);
5955 VectorLerp(start, backfrac, end, newend); end = newend;
5956 segmentmins[0] = min(start[0], end[0]);
5957 segmentmins[1] = min(start[1], end[1]);
5958 segmentmins[2] = min(start[2], end[2]);
5959 segmentmaxs[0] = max(start[0], end[0]);
5960 segmentmaxs[1] = max(start[1], end[1]);
5961 segmentmaxs[2] = max(start[2], end[2]);
5963 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5965 nodenum = node->back;
5968 // START END start END
5970 backfrac = backdist1 / (backdist1 - backdist2);
5971 VectorLerp(start, backfrac, end, newend); end = newend;
5972 segmentmins[0] = min(start[0], end[0]);
5973 segmentmins[1] = min(start[1], end[1]);
5974 segmentmins[2] = min(start[2], end[2]);
5975 segmentmaxs[0] = max(start[0], end[0]);
5976 segmentmaxs[1] = max(start[1], end[1]);
5977 segmentmaxs[2] = max(start[2], end[2]);
5979 nodenum = node->back;
5982 // start end START end
5983 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5985 backfrac = backdist1 / (backdist1 - backdist2);
5986 VectorLerp(start, backfrac, end, newstart); start = newstart;
5987 segmentmins[0] = min(start[0], end[0]);
5988 segmentmins[1] = min(start[1], end[1]);
5989 segmentmins[2] = min(start[2], end[2]);
5990 segmentmaxs[0] = max(start[0], end[0]);
5991 segmentmaxs[1] = max(start[1], end[1]);
5992 segmentmaxs[2] = max(start[2], end[2]);
5994 nodenum = node->back;
5997 // START end START end
5999 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6000 VectorLerp(start, frontfrac, end, clipped);
6001 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
6002 backfrac = backdist1 / (backdist1 - backdist2);
6003 VectorLerp(start, backfrac, end, newstart); start = newstart;
6004 segmentmins[0] = min(start[0], end[0]);
6005 segmentmins[1] = min(start[1], end[1]);
6006 segmentmins[2] = min(start[2], end[2]);
6007 segmentmaxs[0] = max(start[0], end[0]);
6008 segmentmaxs[1] = max(start[1], end[1]);
6009 segmentmaxs[2] = max(start[2], end[2]);
6011 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6013 nodenum = node->back;
6016 // start END START end
6018 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6019 VectorLerp(start, frontfrac, end, clipped);
6020 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
6021 backfrac = backdist1 / (backdist1 - backdist2);
6022 VectorLerp(start, backfrac, end, newstart); start = newstart;
6023 segmentmins[0] = min(start[0], end[0]);
6024 segmentmins[1] = min(start[1], end[1]);
6025 segmentmins[2] = min(start[2], end[2]);
6026 segmentmaxs[0] = max(start[0], end[0]);
6027 segmentmaxs[1] = max(start[1], end[1]);
6028 segmentmaxs[2] = max(start[2], end[2]);
6030 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6032 nodenum = node->back;
6035 // START END START end
6037 backfrac = backdist1 / (backdist1 - backdist2);
6038 VectorLerp(start, backfrac, end, newstart); start = newstart;
6039 segmentmins[0] = min(start[0], end[0]);
6040 segmentmins[1] = min(start[1], end[1]);
6041 segmentmins[2] = min(start[2], end[2]);
6042 segmentmaxs[0] = max(start[0], end[0]);
6043 segmentmaxs[1] = max(start[1], end[1]);
6044 segmentmaxs[2] = max(start[2], end[2]);
6046 nodenum = node->back;
6049 // start end start end
6050 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6051 nodenum = node->back;
6054 // START end start end
6056 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6057 VectorLerp(start, frontfrac, end, clipped);
6058 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped, end, linestart, lineend);
6060 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6062 nodenum = node->back;
6065 // start END start end
6067 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6068 VectorLerp(start, frontfrac, end, clipped);
6069 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped, linestart, lineend);
6071 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6073 nodenum = node->back;
6076 // START END start end
6077 nodenum = node->back;
6083 if (!model->collision_bih.leafs)
6085 leaf = model->collision_bih.leafs + (-1-nodenum);
6087 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6093 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6094 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6096 case BIH_COLLISIONTRIANGLE:
6097 if (!mod_q3bsp_curves_collisions.integer)
6099 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6100 texture = model->data_textures + leaf->textureindex;
6101 Collision_TraceLineTriangleFloat(trace, linestart, lineend, 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);
6103 case BIH_RENDERTRIANGLE:
6104 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6105 texture = model->data_textures + leaf->textureindex;
6106 Collision_TraceLineTriangleFloat(trace, linestart, lineend, 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);
6111 static void Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, const vec3_t segmentmins, const vec3_t segmentmaxs)
6113 const bih_leaf_t *leaf;
6114 const bih_node_t *node;
6115 const colbrushf_t *brush;
6117 const texture_t *texture;
6119 while (nodenum >= 0)
6121 node = model->collision_bih.nodes + nodenum;
6122 axis = node->type - BIH_SPLITX;
6124 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6128 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6129 nodenum = node->back;
6132 if (segmentmins[axis] <= node->backmax)
6134 if (segmentmaxs[axis] >= node->frontmin)
6135 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6136 nodenum = node->back;
6138 else if (segmentmaxs[axis] >= node->frontmin)
6139 nodenum = node->front;
6141 return; // trace falls between children
6143 if (!model->collision_bih.leafs)
6145 leaf = model->collision_bih.leafs + (-1-nodenum);
6147 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6153 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6154 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6156 case BIH_COLLISIONTRIANGLE:
6157 if (!mod_q3bsp_curves_collisions.integer)
6159 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6160 texture = model->data_textures + leaf->textureindex;
6161 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);
6163 case BIH_RENDERTRIANGLE:
6164 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6165 texture = model->data_textures + leaf->textureindex;
6166 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);
6171 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)
6173 memset(trace, 0, sizeof(*trace));
6174 trace->fraction = 1;
6175 trace->realfraction = 1;
6176 trace->hitsupercontentsmask = hitsupercontentsmask;
6177 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6180 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)
6182 if (VectorCompare(start, end))
6184 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6188 memset(trace, 0, sizeof(*trace));
6189 trace->fraction = 1;
6190 trace->realfraction = 1;
6191 trace->hitsupercontentsmask = hitsupercontentsmask;
6192 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6195 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)
6197 float segmentmins[3], segmentmaxs[3];
6198 colboxbrushf_t thisbrush_start, thisbrush_end;
6199 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6201 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6203 vec3_t shiftstart, shiftend;
6204 VectorAdd(start, boxmins, shiftstart);
6205 VectorAdd(end, boxmins, shiftend);
6206 if (VectorCompare(start, end))
6207 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6209 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6213 // box trace, performed as brush trace
6214 memset(trace, 0, sizeof(*trace));
6215 trace->fraction = 1;
6216 trace->realfraction = 1;
6217 trace->hitsupercontentsmask = hitsupercontentsmask;
6218 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6219 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6220 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6221 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6222 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6223 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6224 VectorAdd(start, boxmins, boxstartmins);
6225 VectorAdd(start, boxmaxs, boxstartmaxs);
6226 VectorAdd(end, boxmins, boxendmins);
6227 VectorAdd(end, boxmaxs, boxendmaxs);
6228 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6229 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6230 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6233 void Mod_CollisionBIH_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *start, colbrushf_t *end, int hitsupercontentsmask)
6235 float segmentmins[3], segmentmaxs[3];
6237 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6239 if (VectorCompare(start->mins, end->mins))
6240 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6242 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6246 // box trace, performed as brush trace
6247 memset(trace, 0, sizeof(*trace));
6248 trace->fraction = 1;
6249 trace->realfraction = 1;
6250 trace->hitsupercontentsmask = hitsupercontentsmask;
6251 segmentmins[0] = min(start->mins[0], end->mins[0]);
6252 segmentmins[1] = min(start->mins[1], end->mins[1]);
6253 segmentmins[2] = min(start->mins[2], end->mins[2]);
6254 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6255 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6256 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6257 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, segmentmins, segmentmaxs);
6260 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6263 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6264 return trace.startsupercontents;
6267 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)
6270 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6272 int hitsupercontents;
6273 VectorSet(end, start[0], start[1], model->normalmins[2]);
6275 memset(trace, 0, sizeof(*trace));
6276 trace->fraction = 1;
6277 trace->realfraction = 1;
6278 trace->hitsupercontentsmask = hitsupercontentsmask;
6280 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6281 hitsupercontents = trace->hitsupercontents;
6282 memset(trace, 0, sizeof(*trace));
6283 trace->fraction = 1;
6284 trace->realfraction = 1;
6285 trace->hitsupercontentsmask = hitsupercontentsmask;
6286 trace->startsupercontents = hitsupercontents;
6290 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6293 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6296 VectorSet(end, start[0], start[1], model->normalmins[2]);
6297 memset(&trace, 0, sizeof(trace));
6299 trace.realfraction = 1;
6300 trace.hitsupercontentsmask = 0;
6301 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(&trace, model, model->collision_bih.rootnode, start, end, start, end);
6302 return trace.hitsupercontents;
6308 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6313 // find which leaf the point is in
6315 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6316 // point trace the brushes
6317 leaf = (mleaf_t *)node;
6318 for (i = 0;i < leaf->numleafbrushes;i++)
6320 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6321 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6323 brush->markframe = markframe;
6324 Collision_TracePointBrushFloat(trace, point, brush);
6327 // can't do point traces on curves (they have no thickness)
6330 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)
6332 int i, startside, endside;
6333 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6335 msurface_t *surface;
6338 // walk the tree until we hit a leaf, recursing for any split cases
6342 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6344 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6345 node = node->children[1];
6347 // abort if this part of the bsp tree can not be hit by this trace
6348 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6350 plane = node->plane;
6351 // axial planes are much more common than non-axial, so an optimized
6352 // axial case pays off here
6353 if (plane->type < 3)
6355 dist1 = start[plane->type] - plane->dist;
6356 dist2 = end[plane->type] - plane->dist;
6360 dist1 = DotProduct(start, plane->normal) - plane->dist;
6361 dist2 = DotProduct(end, plane->normal) - plane->dist;
6363 startside = dist1 < 0;
6364 endside = dist2 < 0;
6365 if (startside == endside)
6367 // most of the time the line fragment is on one side of the plane
6368 node = node->children[startside];
6372 // line crosses node plane, split the line
6373 dist1 = PlaneDiff(linestart, plane);
6374 dist2 = PlaneDiff(lineend, plane);
6375 midfrac = dist1 / (dist1 - dist2);
6376 VectorLerp(linestart, midfrac, lineend, mid);
6377 // take the near side first
6378 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6379 // if we found an impact on the front side, don't waste time
6380 // exploring the far side
6381 if (midfrac <= trace->realfraction)
6382 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6387 // abort if this part of the bsp tree can not be hit by this trace
6388 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6391 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6392 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6393 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6394 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6395 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6396 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6397 // line trace the brushes
6398 leaf = (mleaf_t *)node;
6400 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6403 for (i = 0;i < leaf->numleafbrushes;i++)
6405 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6406 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6408 brush->markframe = markframe;
6409 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6412 // can't do point traces on curves (they have no thickness)
6413 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6415 // line trace the curves
6416 for (i = 0;i < leaf->numleafsurfaces;i++)
6418 surface = model->data_surfaces + leaf->firstleafsurface[i];
6419 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6421 surface->deprecatedq3collisionmarkframe = markframe;
6422 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);
6428 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)
6434 msurface_t *surface;
6436 float nodesegmentmins[3], nodesegmentmaxs[3];
6437 // walk the tree until we hit a leaf, recursing for any split cases
6441 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6443 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6444 node = node->children[1];
6446 // abort if this part of the bsp tree can not be hit by this trace
6447 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6449 plane = node->plane;
6450 // axial planes are much more common than non-axial, so an optimized
6451 // axial case pays off here
6452 if (plane->type < 3)
6454 // this is an axial plane, compare bounding box directly to it and
6455 // recurse sides accordingly
6456 // recurse down node sides
6457 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6458 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6459 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6460 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6464 // this is a non-axial plane, so check if the start and end boxes
6465 // are both on one side of the plane to handle 'diagonal' cases
6466 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6470 // segment crosses plane
6471 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6474 // if sides == 0 then the trace itself is bogus (Not A Number values),
6475 // in this case we simply pretend the trace hit nothing
6477 return; // ERROR: NAN bounding box!
6478 // take whichever side the segment box is on
6479 node = node->children[sides - 1];
6482 // abort if this part of the bsp tree can not be hit by this trace
6483 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6485 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6486 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6487 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6488 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6489 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6490 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6492 leaf = (mleaf_t *)node;
6494 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6497 for (i = 0;i < leaf->numleafbrushes;i++)
6499 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6500 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6502 brush->markframe = markframe;
6503 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6506 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6508 for (i = 0;i < leaf->numleafsurfaces;i++)
6510 surface = model->data_surfaces + leaf->firstleafsurface[i];
6511 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6513 surface->deprecatedq3collisionmarkframe = markframe;
6514 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);
6521 static int markframe = 0;
6523 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)
6527 memset(trace, 0, sizeof(*trace));
6528 trace->fraction = 1;
6529 trace->realfraction = 1;
6530 trace->hitsupercontentsmask = hitsupercontentsmask;
6531 if (mod_collision_bih.integer)
6532 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6533 else if (model->brush.submodel)
6535 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6536 if (brush->colbrushf)
6537 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6540 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6543 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)
6546 float segmentmins[3], segmentmaxs[3];
6547 msurface_t *surface;
6550 if (VectorCompare(start, end))
6552 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6556 memset(trace, 0, sizeof(*trace));
6557 trace->fraction = 1;
6558 trace->realfraction = 1;
6559 trace->hitsupercontentsmask = hitsupercontentsmask;
6560 segmentmins[0] = min(start[0], end[0]) - 1;
6561 segmentmins[1] = min(start[1], end[1]) - 1;
6562 segmentmins[2] = min(start[2], end[2]) - 1;
6563 segmentmaxs[0] = max(start[0], end[0]) + 1;
6564 segmentmaxs[1] = max(start[1], end[1]) + 1;
6565 segmentmaxs[2] = max(start[2], end[2]) + 1;
6566 if (mod_collision_bih.integer)
6567 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6568 else if (model->brush.submodel)
6570 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6571 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6572 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6573 if (mod_q3bsp_curves_collisions.integer)
6574 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6575 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6576 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);
6579 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6582 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)
6585 float segmentmins[3], segmentmaxs[3];
6586 msurface_t *surface;
6588 colboxbrushf_t thisbrush_start, thisbrush_end;
6589 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6591 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6593 vec3_t shiftstart, shiftend;
6594 VectorAdd(start, boxmins, shiftstart);
6595 VectorAdd(end, boxmins, shiftend);
6596 if (VectorCompare(start, end))
6597 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6599 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6603 // box trace, performed as brush trace
6604 memset(trace, 0, sizeof(*trace));
6605 trace->fraction = 1;
6606 trace->realfraction = 1;
6607 trace->hitsupercontentsmask = hitsupercontentsmask;
6608 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6609 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6610 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6611 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6612 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6613 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6614 VectorAdd(start, boxmins, boxstartmins);
6615 VectorAdd(start, boxmaxs, boxstartmaxs);
6616 VectorAdd(end, boxmins, boxendmins);
6617 VectorAdd(end, boxmaxs, boxendmaxs);
6618 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6619 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6620 if (mod_collision_bih.integer)
6621 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6622 else if (model->brush.submodel)
6624 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6625 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6626 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, brush->colbrushf, brush->colbrushf);
6627 if (mod_q3bsp_curves_collisions.integer)
6628 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6629 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6630 Collision_TraceBrushTriangleMeshFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, 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);
6633 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, &thisbrush_start.brush, &thisbrush_end.brush, ++markframe, segmentmins, segmentmaxs);
6636 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)
6638 float segmentmins[3], segmentmaxs[3];
6640 msurface_t *surface;
6643 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6645 if (VectorCompare(start->mins, end->mins))
6646 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6648 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6652 // box trace, performed as brush trace
6653 memset(trace, 0, sizeof(*trace));
6654 trace->fraction = 1;
6655 trace->realfraction = 1;
6656 trace->hitsupercontentsmask = hitsupercontentsmask;
6657 segmentmins[0] = min(start->mins[0], end->mins[0]);
6658 segmentmins[1] = min(start->mins[1], end->mins[1]);
6659 segmentmins[2] = min(start->mins[2], end->mins[2]);
6660 segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6661 segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6662 segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6663 if (mod_collision_bih.integer)
6664 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, segmentmins, segmentmaxs);
6665 else if (model->brush.submodel)
6667 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6668 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6669 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6670 if (mod_q3bsp_curves_collisions.integer)
6671 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6672 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6673 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);
6676 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6679 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6682 int supercontents = 0;
6684 if (mod_collision_bih.integer)
6687 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6688 supercontents = trace.startsupercontents;
6690 // test if the point is inside each brush
6691 else if (model->brush.submodel)
6693 // submodels are effectively one leaf
6694 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6695 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6696 supercontents |= brush->colbrushf->supercontents;
6700 mnode_t *node = model->brush.data_nodes;
6702 // find which leaf the point is in
6704 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6705 leaf = (mleaf_t *)node;
6706 // now check the brushes in the leaf
6707 for (i = 0;i < leaf->numleafbrushes;i++)
6709 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6710 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6711 supercontents |= brush->colbrushf->supercontents;
6714 return supercontents;
6717 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6725 int nummodelbrushes = model->nummodelbrushes;
6726 int nummodelsurfaces = model->nummodelsurfaces;
6728 const int *collisionelement3i;
6729 const float *collisionvertex3f;
6730 const int *renderelement3i;
6731 const float *rendervertex3f;
6732 bih_leaf_t *bihleafs;
6733 bih_node_t *bihnodes;
6735 int *temp_leafsortscratch;
6736 const msurface_t *surface;
6737 const q3mbrush_t *brush;
6739 // find out how many BIH leaf nodes we need
6741 if (userendersurfaces)
6743 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6744 bihnumleafs += surface->num_triangles;
6748 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6749 if (brush->colbrushf)
6751 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6753 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6754 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
6756 bihnumleafs += surface->num_collisiontriangles;
6763 // allocate the memory for the BIH leaf nodes
6764 bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6766 // now populate the BIH leaf nodes
6769 // add render surfaces
6770 renderelement3i = model->surfmesh.data_element3i;
6771 rendervertex3f = model->surfmesh.data_vertex3f;
6772 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6774 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6776 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6778 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6779 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6780 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6781 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6782 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6783 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6784 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6785 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6786 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6787 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6792 if (!userendersurfaces)
6794 // add collision brushes
6795 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6797 if (!brush->colbrushf)
6799 bihleafs[bihleafindex].type = BIH_BRUSH;
6800 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6801 bihleafs[bihleafindex].surfaceindex = -1;
6802 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6803 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6804 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6808 // add collision surfaces
6809 collisionelement3i = model->brush.data_collisionelement3i;
6810 collisionvertex3f = model->brush.data_collisionvertex3f;
6811 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6813 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6815 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6816 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6817 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
6818 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6819 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6820 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6821 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6822 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6823 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6824 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6830 // allocate buffers for the produced and temporary data
6831 bihmaxnodes = bihnumleafs - 1;
6832 bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6833 temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6834 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6837 BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6839 // we're done with the temporary data
6840 Mem_Free(temp_leafsort);
6842 // resize the BIH nodes array if it over-allocated
6843 if (out->maxnodes > out->numnodes)
6845 out->maxnodes = out->numnodes;
6846 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
6852 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6854 int supercontents = 0;
6855 if (nativecontents & CONTENTSQ3_SOLID)
6856 supercontents |= SUPERCONTENTS_SOLID;
6857 if (nativecontents & CONTENTSQ3_WATER)
6858 supercontents |= SUPERCONTENTS_WATER;
6859 if (nativecontents & CONTENTSQ3_SLIME)
6860 supercontents |= SUPERCONTENTS_SLIME;
6861 if (nativecontents & CONTENTSQ3_LAVA)
6862 supercontents |= SUPERCONTENTS_LAVA;
6863 if (nativecontents & CONTENTSQ3_BODY)
6864 supercontents |= SUPERCONTENTS_BODY;
6865 if (nativecontents & CONTENTSQ3_CORPSE)
6866 supercontents |= SUPERCONTENTS_CORPSE;
6867 if (nativecontents & CONTENTSQ3_NODROP)
6868 supercontents |= SUPERCONTENTS_NODROP;
6869 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6870 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6871 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6872 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6873 if (nativecontents & CONTENTSQ3_DONOTENTER)
6874 supercontents |= SUPERCONTENTS_DONOTENTER;
6875 if (nativecontents & CONTENTSQ3_BOTCLIP)
6876 supercontents |= SUPERCONTENTS_BOTCLIP;
6877 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6878 supercontents |= SUPERCONTENTS_OPAQUE;
6879 return supercontents;
6882 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6884 int nativecontents = 0;
6885 if (supercontents & SUPERCONTENTS_SOLID)
6886 nativecontents |= CONTENTSQ3_SOLID;
6887 if (supercontents & SUPERCONTENTS_WATER)
6888 nativecontents |= CONTENTSQ3_WATER;
6889 if (supercontents & SUPERCONTENTS_SLIME)
6890 nativecontents |= CONTENTSQ3_SLIME;
6891 if (supercontents & SUPERCONTENTS_LAVA)
6892 nativecontents |= CONTENTSQ3_LAVA;
6893 if (supercontents & SUPERCONTENTS_BODY)
6894 nativecontents |= CONTENTSQ3_BODY;
6895 if (supercontents & SUPERCONTENTS_CORPSE)
6896 nativecontents |= CONTENTSQ3_CORPSE;
6897 if (supercontents & SUPERCONTENTS_NODROP)
6898 nativecontents |= CONTENTSQ3_NODROP;
6899 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6900 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6901 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6902 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6903 if (supercontents & SUPERCONTENTS_DONOTENTER)
6904 nativecontents |= CONTENTSQ3_DONOTENTER;
6905 if (supercontents & SUPERCONTENTS_BOTCLIP)
6906 nativecontents |= CONTENTSQ3_BOTCLIP;
6907 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6908 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6909 return nativecontents;
6912 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6917 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6918 node = node->children[1];
6920 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6921 if (loadmodel->brush.num_leafs < numleafs)
6922 loadmodel->brush.num_leafs = numleafs;
6925 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6928 q3dheader_t *header;
6929 float corner[3], yawradius, modelradius;
6931 mod->modeldatatypestring = "Q3BSP";
6933 mod->type = mod_brushq3;
6934 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6937 header = (q3dheader_t *)buffer;
6938 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6939 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6941 i = LittleLong(header->version);
6942 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6943 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6945 mod->soundfromcenter = true;
6946 mod->TraceBox = Mod_Q3BSP_TraceBox;
6947 mod->TraceBrush = Mod_Q3BSP_TraceBrush;
6948 mod->TraceLine = Mod_Q3BSP_TraceLine;
6949 mod->TracePoint = Mod_Q3BSP_TracePoint;
6950 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6951 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6952 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6953 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6954 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6955 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6956 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6957 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6958 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6959 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6960 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6961 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6962 mod->brush.AmbientSoundLevelsForPoint = NULL;
6963 mod->brush.RoundUpToHullSize = NULL;
6964 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6965 mod->Draw = R_Q1BSP_Draw;
6966 mod->DrawDepth = R_Q1BSP_DrawDepth;
6967 mod->DrawDebug = R_Q1BSP_DrawDebug;
6968 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
6969 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
6970 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
6971 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
6972 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
6973 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
6974 mod->DrawLight = R_Q1BSP_DrawLight;
6976 mod_base = (unsigned char *)header;
6978 // swap all the lumps
6979 header->ident = LittleLong(header->ident);
6980 header->version = LittleLong(header->version);
6981 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
6982 for (i = 0;i < lumps;i++)
6984 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
6985 if((char *) bufferend < (char *) buffer + j)
6986 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
6987 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
6988 if((char *) bufferend < (char *) buffer + j)
6989 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
6992 * NO, do NOT clear them!
6993 * they contain actual data referenced by other stuff.
6994 * Instead, before using the advertisements lump, check header->versio
6996 * Sorry, but otherwise it breaks memory of the first lump.
6997 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
6999 header->lumps[i].fileofs = 0;
7000 header->lumps[i].filelen = 0;
7004 mod->brush.qw_md4sum = 0;
7005 mod->brush.qw_md4sum2 = 0;
7006 for (i = 0;i < lumps;i++)
7008 if (i == Q3LUMP_ENTITIES)
7010 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7011 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7013 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7015 // all this checksumming can take a while, so let's send keepalives here too
7016 CL_KeepaliveMessage(false);
7019 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7020 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7021 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7022 if (header->version == Q3BSPVERSION_IG)
7023 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7025 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7026 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7027 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7028 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7029 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7030 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7031 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7032 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7033 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7034 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7035 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7036 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7037 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7038 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7039 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7041 // the MakePortals code works fine on the q3bsp data as well
7042 Mod_Q1BSP_MakePortals();
7044 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7045 loadmodel->brush.supportwateralpha = true;
7047 // make a single combined shadow mesh to allow optimized shadow volume creation
7048 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7050 loadmodel->brush.num_leafs = 0;
7051 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7053 if (loadmodel->brush.numsubmodels)
7054 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7057 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7062 // duplicate the basic information
7063 dpsnprintf(name, sizeof(name), "*%i", i);
7064 mod = Mod_FindName(name, loadmodel->name);
7065 // copy the base model to this one
7067 // rename the clone back to its proper name
7068 strlcpy(mod->name, name, sizeof(mod->name));
7069 mod->brush.parentmodel = loadmodel;
7070 // textures and memory belong to the main model
7071 mod->texturepool = NULL;
7072 mod->mempool = NULL;
7073 mod->brush.GetPVS = NULL;
7074 mod->brush.FatPVS = NULL;
7075 mod->brush.BoxTouchingPVS = NULL;
7076 mod->brush.BoxTouchingLeafPVS = NULL;
7077 mod->brush.BoxTouchingVisibleLeafs = NULL;
7078 mod->brush.FindBoxClusters = NULL;
7079 mod->brush.LightPoint = NULL;
7080 mod->brush.AmbientSoundLevelsForPoint = NULL;
7082 mod->brush.submodel = i;
7083 if (loadmodel->brush.submodels)
7084 loadmodel->brush.submodels[i] = mod;
7086 // make the model surface list (used by shadowing/lighting)
7087 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7088 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7089 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7090 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7091 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7092 Mod_MakeSortedSurfaces(mod);
7094 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7095 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7096 // enlarge the bounding box to enclose all geometry of this model,
7097 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7098 // which can in turn mess up the farclip (as well as culling when
7099 // outside the level - an unimportant concern)
7101 //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]);
7102 for (j = 0;j < mod->nummodelsurfaces;j++)
7104 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7105 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7107 if (!surface->num_vertices)
7109 for (k = 0;k < surface->num_vertices;k++, v += 3)
7111 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7112 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7113 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7114 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7115 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7116 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7119 //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]);
7120 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7121 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7122 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7123 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7124 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7125 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7126 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7127 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7128 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7129 mod->yawmins[2] = mod->normalmins[2];
7130 mod->yawmaxs[2] = mod->normalmaxs[2];
7131 mod->radius = modelradius;
7132 mod->radius2 = modelradius * modelradius;
7134 // this gets altered below if sky or water is used
7135 mod->DrawSky = NULL;
7136 mod->DrawAddWaterPlanes = NULL;
7138 for (j = 0;j < mod->nummodelsurfaces;j++)
7139 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7141 if (j < mod->nummodelsurfaces)
7142 mod->DrawSky = R_Q1BSP_DrawSky;
7144 for (j = 0;j < mod->nummodelsurfaces;j++)
7145 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7147 if (j < mod->nummodelsurfaces)
7148 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7150 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7151 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7153 // generate VBOs and other shared data before cloning submodels
7158 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);
7161 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7163 int i = LittleLong(((int *)buffer)[1]);
7164 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7165 Mod_Q3BSP_Load(mod,buffer, bufferend);
7166 else if (i == Q2BSPVERSION)
7167 Mod_Q2BSP_Load(mod,buffer, bufferend);
7169 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7172 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7174 Host_Error("Mod_MAP_Load: not yet implemented");
7180 typedef struct objvertex_s
7191 static unsigned char nobsp_pvs[1] = {1};
7193 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7195 const char *textbase = (char *)buffer, *text = textbase;
7199 char materialname[MAX_QPATH];
7200 int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7201 int index1, index2, index3;
7202 objvertex_t vfirst, vprev, vcurrent;
7205 int numtriangles = 0;
7206 int maxtriangles = 0;
7207 objvertex_t *vertices = NULL;
7209 int maxtextures = 0, numtextures = 0, textureindex = 0;
7210 int maxv = 0, numv = 1;
7211 int maxvt = 0, numvt = 1;
7212 int maxvn = 0, numvn = 1;
7213 char *texturenames = NULL;
7214 float dist, modelradius, modelyawradius, yawradius;
7221 objvertex_t *thisvertex = NULL;
7222 int vertexhashindex;
7223 int *vertexhashtable = NULL;
7224 objvertex_t *vertexhashdata = NULL;
7225 objvertex_t *vdata = NULL;
7226 int vertexhashsize = 0;
7227 int vertexhashcount = 0;
7228 skinfile_t *skinfiles = NULL;
7229 unsigned char *data = NULL;
7230 int *submodelfirstsurface;
7231 msurface_t *surface;
7232 msurface_t *tempsurfaces;
7234 memset(&vfirst, 0, sizeof(vfirst));
7235 memset(&vprev, 0, sizeof(vprev));
7236 memset(&vcurrent, 0, sizeof(vcurrent));
7238 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7240 loadmodel->modeldatatypestring = "OBJ";
7242 loadmodel->type = mod_obj;
7243 loadmodel->soundfromcenter = true;
7244 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7245 loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7246 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7247 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7248 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7249 loadmodel->brush.TraceLineOfSight = NULL;
7250 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7251 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7252 loadmodel->brush.GetPVS = NULL;
7253 loadmodel->brush.FatPVS = NULL;
7254 loadmodel->brush.BoxTouchingPVS = NULL;
7255 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7256 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7257 loadmodel->brush.FindBoxClusters = NULL;
7258 loadmodel->brush.LightPoint = NULL;
7259 loadmodel->brush.FindNonSolidLocation = NULL;
7260 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7261 loadmodel->brush.RoundUpToHullSize = NULL;
7262 loadmodel->brush.PointInLeaf = NULL;
7263 loadmodel->Draw = R_Q1BSP_Draw;
7264 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7265 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7266 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7267 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7268 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7269 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7270 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7271 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7272 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7274 skinfiles = Mod_LoadSkinFiles();
7275 if (loadmodel->numskins < 1)
7276 loadmodel->numskins = 1;
7278 // make skinscenes for the skins (no groups)
7279 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7280 for (i = 0;i < loadmodel->numskins;i++)
7282 loadmodel->skinscenes[i].firstframe = i;
7283 loadmodel->skinscenes[i].framecount = 1;
7284 loadmodel->skinscenes[i].loop = true;
7285 loadmodel->skinscenes[i].framerate = 10;
7291 // parse the OBJ text now
7294 static char emptyarg[1] = "";
7299 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7300 line[linelen] = text[linelen];
7302 for (argc = 0;argc < 4;argc++)
7303 argv[argc] = emptyarg;
7306 while (*s == ' ' || *s == '\t')
7316 while (*s == ' ' || *s == '\t')
7326 if (argv[0][0] == '#')
7328 if (!strcmp(argv[0], "v"))
7332 maxv = max(maxv * 2, 1024);
7333 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7335 v[numv*3+0] = atof(argv[1]);
7336 v[numv*3+2] = atof(argv[2]);
7337 v[numv*3+1] = atof(argv[3]);
7340 else if (!strcmp(argv[0], "vt"))
7344 maxvt = max(maxvt * 2, 1024);
7345 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7347 vt[numvt*2+0] = atof(argv[1]);
7348 vt[numvt*2+1] = 1-atof(argv[2]);
7351 else if (!strcmp(argv[0], "vn"))
7355 maxvn = max(maxvn * 2, 1024);
7356 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7358 vn[numvn*3+0] = atof(argv[1]);
7359 vn[numvn*3+2] = atof(argv[2]);
7360 vn[numvn*3+1] = atof(argv[3]);
7363 else if (!strcmp(argv[0], "f"))
7367 if (maxtextures <= numtextures)
7369 maxtextures = max(maxtextures * 2, 256);
7370 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7372 textureindex = numtextures++;
7373 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7375 for (j = 1;j < argc;j++)
7377 index1 = atoi(argv[j]);
7378 while(argv[j][0] && argv[j][0] != '/')
7382 index2 = atoi(argv[j]);
7383 while(argv[j][0] && argv[j][0] != '/')
7387 index3 = atoi(argv[j]);
7388 // negative refers to a recent vertex
7389 // zero means not specified
7390 // positive means an absolute vertex index
7392 index1 = numv - index1;
7394 index2 = numvt - index2;
7396 index3 = numvn - index3;
7397 vcurrent.nextindex = -1;
7398 vcurrent.textureindex = textureindex;
7399 vcurrent.submodelindex = submodelindex;
7400 if (v && index1 >= 0 && index1 < numv)
7401 VectorCopy(v + 3*index1, vcurrent.v);
7402 if (vt && index2 >= 0 && index2 < numvt)
7403 Vector2Copy(vt + 2*index2, vcurrent.vt);
7404 if (vn && index3 >= 0 && index3 < numvn)
7405 VectorCopy(vn + 3*index3, vcurrent.vn);
7406 if (numtriangles == 0)
7408 VectorCopy(vcurrent.v, mins);
7409 VectorCopy(vcurrent.v, maxs);
7413 mins[0] = min(mins[0], vcurrent.v[0]);
7414 mins[1] = min(mins[1], vcurrent.v[1]);
7415 mins[2] = min(mins[2], vcurrent.v[2]);
7416 maxs[0] = max(maxs[0], vcurrent.v[0]);
7417 maxs[1] = max(maxs[1], vcurrent.v[1]);
7418 maxs[2] = max(maxs[2], vcurrent.v[2]);
7424 if (maxtriangles <= numtriangles)
7426 maxtriangles = max(maxtriangles * 2, 32768);
7427 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7429 vertices[numtriangles*3+0] = vfirst;
7430 vertices[numtriangles*3+1] = vprev;
7431 vertices[numtriangles*3+2] = vcurrent;
7437 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7439 submodelindex = atof(argv[1]);
7440 loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7442 else if (!strcmp(argv[0], "usemtl"))
7444 for (i = 0;i < numtextures;i++)
7445 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7447 if (i < numtextures)
7451 if (maxtextures <= numtextures)
7453 maxtextures = max(maxtextures * 2, 256);
7454 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7456 textureindex = numtextures++;
7457 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7462 // now that we have the OBJ data loaded as-is, we can convert it
7464 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7465 VectorCopy(mins, loadmodel->normalmins);
7466 VectorCopy(maxs, loadmodel->normalmaxs);
7467 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7468 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7469 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7470 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7471 modelradius = modelyawradius + modelradius * modelradius;
7472 modelyawradius = sqrt(modelyawradius);
7473 modelradius = sqrt(modelradius);
7474 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7475 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7476 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7477 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7478 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7479 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7480 loadmodel->radius = modelradius;
7481 loadmodel->radius2 = modelradius * modelradius;
7483 // allocate storage for triangles
7484 loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7485 // allocate vertex hash structures to build an optimal vertex subset
7486 vertexhashsize = numtriangles*2;
7487 vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7488 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7489 vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7490 vertexhashcount = 0;
7492 // gather surface stats for assigning vertex/triangle ranges
7496 loadmodel->num_surfaces = 0;
7497 // allocate storage for the worst case number of surfaces, later we resize
7498 tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7499 submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7500 surface = tempsurfaces;
7501 for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7503 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7504 for (textureindex = 0;textureindex < numtextures;textureindex++)
7506 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7508 thisvertex = vertices + vertexindex;
7509 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7512 // skip the surface creation if there are no triangles for it
7513 if (vertexindex == numtriangles*3)
7515 // create a surface for these vertices
7516 surfacevertices = 0;
7517 surfaceelements = 0;
7518 // we hack in a texture index in the surface to be fixed up later...
7519 surface->texture = (texture_t *)((size_t)textureindex);
7520 // calculate bounds as we go
7521 VectorCopy(thisvertex->v, surface->mins);
7522 VectorCopy(thisvertex->v, surface->maxs);
7523 for (;vertexindex < numtriangles*3;vertexindex++)
7525 thisvertex = vertices + vertexindex;
7526 if (thisvertex->submodelindex != submodelindex)
7528 if (thisvertex->textureindex != textureindex)
7530 // add vertex to surface bounds
7531 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7532 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7533 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7534 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7535 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7536 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7537 // add the vertex if it is not found in the merged set, and
7538 // get its index (triangle element) for the surface
7539 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7540 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7542 vdata = vertexhashdata + i;
7543 if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7548 i = vertexhashcount++;
7549 vdata = vertexhashdata + i;
7550 *vdata = *thisvertex;
7551 vdata->nextindex = vertexhashtable[vertexhashindex];
7552 vertexhashtable[vertexhashindex] = i;
7555 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7558 surfacetriangles = surfaceelements / 3;
7559 surface->num_vertices = surfacevertices;
7560 surface->num_triangles = surfacetriangles;
7561 surface->num_firstvertex = firstvertex;
7562 surface->num_firsttriangle = firsttriangle;
7563 firstvertex += surface->num_vertices;
7564 firsttriangle += surface->num_triangles;
7566 loadmodel->num_surfaces++;
7569 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7570 numvertices = firstvertex;
7571 loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7572 tempsurfaces = NULL;
7574 // allocate storage for final mesh data
7575 loadmodel->num_textures = numtextures * loadmodel->numskins;
7576 loadmodel->num_texturesperskin = numtextures;
7577 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) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7578 loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7579 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7580 loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7581 loadmodel->surfmesh.num_vertices = numvertices;
7582 loadmodel->surfmesh.num_triangles = numtriangles;
7583 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7584 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7585 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7586 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7587 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7588 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7589 if (loadmodel->surfmesh.num_vertices <= 65536)
7590 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7592 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7594 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7595 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7596 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7599 // load the textures
7600 for (textureindex = 0;textureindex < numtextures;textureindex++)
7601 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7602 Mod_FreeSkinFiles(skinfiles);
7604 // set the surface textures to their real values now that we loaded them...
7605 for (i = 0;i < loadmodel->num_surfaces;i++)
7606 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7610 Mem_Free(texturenames);
7614 Mem_Free(vertexhashtable);
7615 Mem_Free(vertexhashdata);
7617 // make a single combined shadow mesh to allow optimized shadow volume creation
7618 Mod_Q1BSP_CreateShadowMesh(loadmodel);
7620 // compute all the mesh information that was not loaded from the file
7621 if (loadmodel->surfmesh.data_element3s)
7622 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7623 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7624 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7625 // generate normals if the file did not have them
7626 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7627 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
7628 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, true);
7629 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7631 // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7632 loadmodel->brush.num_visleafs = 1;
7633 loadmodel->brush.num_leafs = 1;
7634 loadmodel->brush.num_nodes = 0;
7635 loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7636 loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7637 loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7638 loadmodel->brush.num_pvsclusters = 1;
7639 loadmodel->brush.num_pvsclusterbytes = 1;
7640 loadmodel->brush.data_pvsclusters = nobsp_pvs;
7641 //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7642 //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7643 loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7644 VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7645 VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7646 loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7647 loadmodel->brush.data_leafs->clusterindex = 0;
7648 loadmodel->brush.data_leafs->areaindex = 0;
7649 loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7650 loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7651 loadmodel->brush.data_leafs->numleafbrushes = 0;
7652 loadmodel->brush.data_leafs->firstleafbrush = NULL;
7653 loadmodel->brush.supportwateralpha = true;
7655 if (loadmodel->brush.numsubmodels)
7656 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7659 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7664 // duplicate the basic information
7665 dpsnprintf(name, sizeof(name), "*%i", i);
7666 mod = Mod_FindName(name, loadmodel->name);
7667 // copy the base model to this one
7669 // rename the clone back to its proper name
7670 strlcpy(mod->name, name, sizeof(mod->name));
7671 mod->brush.parentmodel = loadmodel;
7672 // textures and memory belong to the main model
7673 mod->texturepool = NULL;
7674 mod->mempool = NULL;
7675 mod->brush.GetPVS = NULL;
7676 mod->brush.FatPVS = NULL;
7677 mod->brush.BoxTouchingPVS = NULL;
7678 mod->brush.BoxTouchingLeafPVS = NULL;
7679 mod->brush.BoxTouchingVisibleLeafs = NULL;
7680 mod->brush.FindBoxClusters = NULL;
7681 mod->brush.LightPoint = NULL;
7682 mod->brush.AmbientSoundLevelsForPoint = NULL;
7684 mod->brush.submodel = i;
7685 if (loadmodel->brush.submodels)
7686 loadmodel->brush.submodels[i] = mod;
7688 // make the model surface list (used by shadowing/lighting)
7689 mod->firstmodelsurface = submodelfirstsurface[i];
7690 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7691 mod->firstmodelbrush = 0;
7692 mod->nummodelbrushes = 0;
7693 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
7694 Mod_MakeSortedSurfaces(mod);
7696 VectorClear(mod->normalmins);
7697 VectorClear(mod->normalmaxs);
7699 for (j = 0;j < mod->nummodelsurfaces;j++)
7701 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7702 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7704 if (!surface->num_vertices)
7709 VectorCopy(v, mod->normalmins);
7710 VectorCopy(v, mod->normalmaxs);
7712 for (k = 0;k < surface->num_vertices;k++, v += 3)
7714 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7715 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7716 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7717 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7718 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7719 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7722 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7723 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7724 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7725 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7726 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7727 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7728 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7729 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7730 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7731 mod->yawmins[2] = mod->normalmins[2];
7732 mod->yawmaxs[2] = mod->normalmaxs[2];
7733 mod->radius = modelradius;
7734 mod->radius2 = modelradius * modelradius;
7736 // this gets altered below if sky or water is used
7737 mod->DrawSky = NULL;
7738 mod->DrawAddWaterPlanes = NULL;
7740 for (j = 0;j < mod->nummodelsurfaces;j++)
7741 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7743 if (j < mod->nummodelsurfaces)
7744 mod->DrawSky = R_Q1BSP_DrawSky;
7746 for (j = 0;j < mod->nummodelsurfaces;j++)
7747 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7749 if (j < mod->nummodelsurfaces)
7750 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7752 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
7753 mod->render_bih = mod->collision_bih;
7755 // generate VBOs and other shared data before cloning submodels
7760 Mem_Free(submodelfirstsurface);
7762 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);
7777 typedef struct objvertex_s
7785 typedef struct objtriangle_s
7787 objvertex_t vertex[3];
7789 // these fields are used only in conversion to surfaces
7792 int surfacevertexindex[3];
7793 float edgeplane[3][4];
7799 struct objnode_s *children[2];
7800 struct objnode_s *parent;
7801 objtriangle_t *triangles;
7810 objnode_t *Mod_OBJ_BSPNodeForTriangles(objnode_t *parent, objtriangle_t *triangles, int numtriangles, const float *mins, const float *maxs, mem_expandablearray_t *nodesarray, int maxclippedtriangles, objtriangle_t *clippedfronttriangles, objtriangle_t *clippedbacktriangles)
7816 float bestnormal[3];
7821 int numfronttriangles;
7822 int numbacktriangles;
7827 float outfrontpoints[5][3];
7828 float outbackpoints[5][3];
7829 int neededfrontpoints;
7830 int neededbackpoints;
7834 node = (objnode_t *)Mem_ExpandableArray_AllocRecord(array);
7835 node->parent = parent;
7838 VectorCopy(triangles[0].vertex[0].v, mins);
7839 VectorCopy(triangles[0].vertex[0].v, maxs);
7841 else if (parent && parent->children[0] == node)
7843 VectorCopy(parent->mins, mins);
7844 Vectorcopy(parent->maxs, maxs);
7846 else if (parent && parent->children[1] == node)
7848 VectorCopy(parent->mins, mins);
7849 Vectorcopy(parent->maxs, maxs);
7856 for (i = 0;i < numtriangles;i++)
7858 for (j = 0;j < 3;j++)
7860 mins[0] = min(mins[0], triangles[i].vertex[j].v[0]);
7861 mins[1] = min(mins[1], triangles[i].vertex[j].v[1]);
7862 mins[2] = min(mins[2], triangles[i].vertex[j].v[2]);
7863 maxs[0] = max(maxs[0], triangles[i].vertex[j].v[0]);
7864 maxs[1] = max(maxs[1], triangles[i].vertex[j].v[1]);
7865 maxs[2] = max(maxs[2], triangles[i].vertex[j].v[2]);
7868 VectorCopy(mins, node->mins);
7869 VectorCopy(maxs, node->maxs);
7870 if (numtriangles <= mod_obj_leaftriangles.integer)
7873 loadmodel->brush.num_leafs++;
7874 node->triangles = triangles;
7875 node->numtriangles = numtriangles;
7880 loadmodel->brush.num_nodes++;
7881 // pick a splitting plane from the various choices available to us...
7882 // early splits simply halve the interval
7884 VectorClear(bestnormal);
7886 if (numtriangles <= mod_obj_splitterlimit.integer)
7887 limit = numtriangles;
7890 for (i = -3;i < limit;i++)
7894 // first we try 3 axial splits (kdtree-like)
7896 VectorClear(normal);
7898 dist = (mins[j] + maxs[j]) * 0.5f;
7902 // then we try each triangle plane
7903 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7904 VectorNormalize(normal);
7905 dist = DotProduct(normal, triangles[i].vertex[0].v);
7906 // use positive axial values whenever possible
7907 if (normal[0] == -1)
7909 if (normal[1] == -1)
7911 if (normal[2] == -1)
7913 // skip planes that match the current best
7914 if (VectorCompare(normal, bestnormal) && dist == bestdist)
7921 for (j = 0;j < numtriangles;j++)
7923 dists[0] = DotProduct(normal, triangles[j].vertex[0].v) - dist;
7924 dists[1] = DotProduct(normal, triangles[j].vertex[1].v) - dist;
7925 dists[2] = DotProduct(normal, triangles[j].vertex[2].v) - dist;
7926 if (dists[0] < -DIST_EPSILON || dists[1] < -DIST_EPSILON || dists[2] < -DIST_EPSILON)
7928 if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7933 else if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7938 // score is supposed to:
7939 // prefer axial splits
7940 // prefer evenly dividing the input triangles
7941 // prefer triangles on the plane
7942 // avoid triangles crossing the plane
7943 score = count_on*count_on - count_both*count_both + min(count_front, count_back)*(count_front+count_back);
7944 if (normal[0] == 1 || normal[1] == 1 || normal[2] == 1)
7946 if (i == -3 || bestscore < score)
7948 VectorCopy(normal, bestnormal);
7954 // now we have chosen an optimal split plane...
7956 // divide triangles by the splitting plane
7957 numfronttriangles = 0;
7958 numbacktriangles = 0;
7959 for (i = 0;i < numtriangles;i++)
7961 neededfrontpoints = 0;
7962 neededbackpoints = 0;
7964 PolygonF_Divide(3, triangles[i].vertex[0].v, bestnormal[0], bestnormal[1], bestnormal[2], bestdist, DIST_EPSILON, 5, outfrontpoints[0], &neededfrontpoints, 5, outbackpoints[0], &neededbackpoints, &countonpoints);
7965 if (countonpoints > 1)
7967 // triangle lies on plane, assign it to one child only
7968 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7969 if (DotProduct(bestnormal, normal) >= 0)
7971 // assign to front side child
7972 obj_fronttriangles[numfronttriangles++] = triangles[i];
7976 // assign to back side child
7977 obj_backtriangles[numbacktriangles++] = triangles[i];
7982 // convert clipped polygons to triangles
7983 for (j = 0;j < neededfrontpoints-2;j++)
7985 obj_fronttriangles[numfronttriangles] = triangles[i];
7986 VectorCopy(outfrontpoints[0], obj_fronttriangles[numfronttriangles].vertex[0].v);
7987 VectorCopy(outfrontpoints[j+1], obj_fronttriangles[numfronttriangles].vertex[1].v);
7988 VectorCopy(outfrontpoints[j+2], obj_fronttriangles[numfronttriangles].vertex[2].v);
7989 numfronttriangles++;
7991 for (j = 0;j < neededbackpoints-2;j++)
7993 obj_backtriangles[numbacktriangles] = triangles[i];
7994 VectorCopy(outbackpoints[0], obj_backtriangles[numbacktriangles].vertex[0].v);
7995 VectorCopy(outbackpoints[j+1], obj_backtriangles[numbacktriangles].vertex[1].v);
7996 VectorCopy(outbackpoints[j+2], obj_backtriangles[numbacktriangles].vertex[2].v);
8002 // now copy the triangles out of the big buffer
8003 if (numfronttriangles)
8005 fronttriangles = Mem_Alloc(loadmodel->mempool, fronttriangles * sizeof(*fronttriangles));
8006 memcpy(fronttriangles, obj_fronttriangles, numfronttriangles * sizeof(*fronttriangles));
8009 fronttriangles = NULL;
8010 if (numbacktriangles)
8012 backtriangles = Mem_Alloc(loadmodel->mempool, backtriangles * sizeof(*backtriangles));
8013 memcpy(backtriangles, obj_backtriangles, numbacktriangles * sizeof(*backtriangles));
8016 backtriangles = NULL;
8018 // free the original triangles we were given
8020 Mem_Free(triangles);
8024 // now create the children...
8025 node->children[0] = Mod_OBJ_BSPNodeForTriangles(node, fronttriangles, numfronttriangles, frontmins, frontmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8026 node->children[1] = Mod_OBJ_BSPNodeForTriangles(node, backtriangles, numbacktriangles, backmins, backmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8030 void Mod_OBJ_SnapVertex(float *v)
8033 float a = mod_obj_vertexprecision.value;
8035 v[0] -= floor(v[0] * a + 0.5f) * b;
8036 v[1] -= floor(v[1] * a + 0.5f) * b;
8037 v[2] -= floor(v[2] * a + 0.5f) * b;
8040 void Mod_OBJ_ConvertBSPNode(objnode_t *objnode, mnode_t *mnodeparent)
8042 if (objnode->children[0])
8044 // convert to mnode_t
8045 mnode_t *mnode = loadmodel->brush.data_nodes + loadmodel->brush.num_nodes++;
8046 mnode->parent = mnodeparent;
8047 mnode->plane = loadmodel->brush.data_planes + loadmodel->brush.num_planes++;
8048 VectorCopy(objnode->normal, mnode->plane->normal);
8049 mnode->plane->dist = objnode->dist;
8050 PlaneClassify(mnode->plane);
8051 VectorCopy(objnode->mins, mnode->mins);
8052 VectorCopy(objnode->maxs, mnode->maxs);
8053 // push combinedsupercontents up to the parent
8055 mnodeparent->combinedsupercontents |= mnode->combinedsupercontents;
8056 mnode->children[0] = Mod_OBJ_ConvertBSPNode(objnode->children[0], mnode);
8057 mnode->children[1] = Mod_OBJ_ConvertBSPNode(objnode->children[1], mnode);
8061 // convert to mleaf_t
8062 mleaf_t *mleaf = loadmodel->brush.data_leafs + loadmodel->brush.num_leafs++;
8063 mleaf->parent = mnodeparent;
8064 VectorCopy(objnode->mins, mleaf->mins);
8065 VectorCopy(objnode->maxs, mleaf->maxs);
8066 mleaf->clusterindex = loadmodel->brush.num_leafs - 1;
8067 if (objnode->numtriangles)
8069 objtriangle_t *triangles = objnode->triangles;
8070 int numtriangles = objnode->numtriangles;
8074 objvertex_t vertex[3];
8076 maxsurfaces = numtriangles;
8078 // calculate some more data on each triangle for surface gathering
8079 for (i = 0;i < numtriangles;i++)
8081 triangle = triangles + i;
8082 texture = loadmodel->data_textures + triangle->textureindex;
8083 Mod_OBJ_SnapVertex(triangle->vertex[0].v);
8084 Mod_OBJ_SnapVertex(triangle->vertex[1].v);
8085 Mod_OBJ_SnapVertex(triangle->vertex[2].v);
8086 TriangleNormal(triangle->vertex[0].v, triangle->vertex[1].v, triangle->vertex[2].v, normal);
8088 if (fabs(normal[axis]) < fabs(normal[1]))
8090 if (fabs(normal[axis]) < fabs(normal[2]))
8092 VectorClear(normal);
8094 triangle->axis = axis;
8095 VectorSubtract(triangle->vertex[1].v, triangle->vertex[0].v, edge[0]);
8096 VectorSubtract(triangle->vertex[2].v, triangle->vertex[1].v, edge[1]);
8097 VectorSubtract(triangle->vertex[0].v, triangle->vertex[2].v, edge[2]);
8098 CrossProduct(edge[0], normal, triangle->edgeplane[0]);
8099 CrossProduct(edge[1], normal, triangle->edgeplane[1]);
8100 CrossProduct(edge[2], normal, triangle->edgeplane[2]);
8101 VectorNormalize(triangle->edgeplane[0]);
8102 VectorNormalize(triangle->edgeplane[1]);
8103 VectorNormalize(triangle->edgeplane[2]);
8104 triangle->edgeplane[0][3] = DotProduct(triangle->edgeplane[0], triangle->vertex[0].v);
8105 triangle->edgeplane[1][3] = DotProduct(triangle->edgeplane[1], triangle->vertex[1].v);
8106 triangle->edgeplane[2][3] = DotProduct(triangle->edgeplane[2], triangle->vertex[2].v);
8107 triangle->surfaceindex = 0;
8108 // add to the combined supercontents while we're here...
8109 mleaf->combinedsupercontents |= texture->supercontents;
8112 for (i = 0;i < numtriangles;i++)
8114 // skip already-assigned triangles
8115 if (triangles[i].surfaceindex)
8117 texture = loadmodel->data_textures + triangles[i].textureindex;
8118 // assign a new surface to this triangle
8119 triangles[i].surfaceindex = surfaceindex++;
8120 axis = triangles[i].axis;
8122 // find the triangle's neighbors, this can take multiple passes
8127 for (j = i+1;j < numtriangles;j++)
8129 if (triangles[j].surfaceindex || triangles[j].axis != axis || triangles[j].texture != texture)
8131 triangle = triangles + j;
8132 for (k = i;k < j;k++)
8134 if (triangles[k].surfaceindex != surfaceindex)
8136 if (VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[0].v)
8137 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[1].v)
8138 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[2].v)
8139 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[0].v)
8140 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[1].v)
8141 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[2].v)
8142 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[0].v)
8143 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[1].v)
8144 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[2].v))
8146 // shares a vertex position
8150 for (k = 0;k < numvertices;k++)
8151 if (!VectorCompare(vertex[k].v, triangles[j].vertex[0].v) || !VectorCompare(vertex[k].v, triangles[j].vertex[1].v) || !VectorCompare(vertex[k].v, triangles[j].vertex[2].v))
8153 if (k == numvertices)
8154 break; // not a neighbor
8155 // this triangle is a neighbor and has the same axis and texture
8156 // check now if it overlaps in lightmap projection space
8157 triangles[j].surfaceindex;
8161 //triangles[i].surfaceindex = surfaceindex++;
8162 for (surfaceindex = 0;surfaceindex < numsurfaces;surfaceindex++)
8164 if (surfaces[surfaceindex].texture != texture)
8166 // check if any triangles already in this surface overlap in lightmap projection space
8173 // let the collision code simply use the surfaces
8174 mleaf->containscollisionsurfaces = mleaf->combinedsupercontents != 0;
8175 mleaf->numleafsurfaces = ?;
8176 mleaf->firstleafsurface = ?;
8178 // push combinedsupercontents up to the parent
8180 mnodeparent->combinedsupercontents |= mleaf->combinedsupercontents;
8185 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
8188 const char *textbase = (char *)buffer, *text = textbase;
8192 char materialname[MAX_QPATH];
8193 int j, index1, index2, index3, first, prev, index;
8196 int numtriangles = 0;
8197 int maxtriangles = 131072;
8198 objtriangle_t *triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8200 int maxtextures = 256, numtextures = 0, textureindex = 0;
8201 int maxv = 1024, numv = 0;
8202 int maxvt = 1024, numvt = 0;
8203 int maxvn = 1024, numvn = 0;
8204 char **texturenames;
8205 float *v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8206 float *vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8207 float *vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8208 objvertex_t vfirst, vprev, vcurrent;
8213 int maxverthash = 65536, numverthash = 0;
8214 int numhashindex = 65536;
8215 struct objverthash_s
8217 struct objverthash_s *next;
8223 *hash, **verthash = Mem_Alloc(tempmempool, numhashindex * sizeof(*verthash)), *verthashdata = Mem_Alloc(tempmempool, maxverthash * sizeof(*verthashdata)), *oldverthashdata;
8226 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8228 loadmodel->modeldatatypestring = "OBJ";
8230 loadmodel->type = mod_obj;
8231 loadmodel->soundfromcenter = true;
8232 loadmodel->TraceBox = Mod_OBJ_TraceBox;
8233 loadmodel->TraceLine = Mod_OBJ_TraceLine;
8234 loadmodel->TracePoint = Mod_OBJ_TracePoint;
8235 loadmodel->PointSuperContents = Mod_OBJ_PointSuperContents;
8236 loadmodel->brush.TraceLineOfSight = Mod_OBJ_TraceLineOfSight;
8237 loadmodel->brush.SuperContentsFromNativeContents = Mod_OBJ_SuperContentsFromNativeContents;
8238 loadmodel->brush.NativeContentsFromSuperContents = Mod_OBJ_NativeContentsFromSuperContents;
8239 loadmodel->brush.GetPVS = Mod_OBJ_GetPVS;
8240 loadmodel->brush.FatPVS = Mod_OBJ_FatPVS;
8241 loadmodel->brush.BoxTouchingPVS = Mod_OBJ_BoxTouchingPVS;
8242 loadmodel->brush.BoxTouchingLeafPVS = Mod_OBJ_BoxTouchingLeafPVS;
8243 loadmodel->brush.BoxTouchingVisibleLeafs = Mod_OBJ_BoxTouchingVisibleLeafs;
8244 loadmodel->brush.FindBoxClusters = Mod_OBJ_FindBoxClusters;
8245 loadmodel->brush.LightPoint = Mod_OBJ_LightPoint;
8246 loadmodel->brush.FindNonSolidLocation = Mod_OBJ_FindNonSolidLocation;
8247 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8248 loadmodel->brush.RoundUpToHullSize = NULL;
8249 loadmodel->brush.PointInLeaf = Mod_OBJ_PointInLeaf;
8250 loadmodel->Draw = R_Q1BSP_Draw;
8251 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
8252 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
8253 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
8254 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
8255 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
8256 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
8257 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
8258 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
8259 loadmodel->DrawLight = R_Q1BSP_DrawLight;
8264 // parse the OBJ text now
8271 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8272 line[linelen] = text[linelen];
8274 for (argc = 0;argc < (int)(sizeof(argv)/sizeof(argv[0]));argc++)
8278 while (*s == ' ' || *s == '\t')
8288 while (*s == ' ' || *s == '\t')
8293 if (argv[0][0] == '#')
8295 if (!strcmp(argv[0], "v"))
8301 v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8304 memcpy(v, oldv, numv * sizeof(float[3]));
8308 v[numv*3+0] = atof(argv[1]);
8309 v[numv*3+1] = atof(argv[2]);
8310 v[numv*3+2] = atof(argv[3]);
8313 else if (!strcmp(argv[0], "vt"))
8319 vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8322 memcpy(vt, oldvt, numvt * sizeof(float[2]));
8326 vt[numvt*2+0] = atof(argv[1]);
8327 vt[numvt*2+1] = atof(argv[2]);
8330 else if (!strcmp(argv[0], "vn"))
8336 vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8339 memcpy(vn, oldvn, numvn * sizeof(float[3]));
8343 vn[numvn*3+0] = atof(argv[1]);
8344 vn[numvn*3+1] = atof(argv[2]);
8345 vn[numvn*3+2] = atof(argv[3]);
8348 else if (!strcmp(argv[0], "f"))
8350 for (j = 1;j < argc;j++)
8352 index1 = atoi(argv[j]);
8353 while(argv[j][0] && argv[j][0] != '/')
8357 index2 = atoi(argv[j]);
8358 while(argv[j][0] && argv[j][0] != '/')
8362 index3 = atoi(argv[j]);
8363 // negative refers to a recent vertex
8364 // zero means not specified
8365 // positive means an absolute vertex index
8367 index1 = numv - index1;
8369 index2 = numvt - index2;
8371 index3 = numvn - index3;
8372 VectorCopy(v + 3*index1, vcurrent.v);
8373 Vector2Copy(vt + 2*index2, vcurrent.vt);
8374 VectorCopy(vn + 3*index3, vcurrent.vn);
8375 if (numtriangles == 0)
8377 VectorCopy(vcurrent.v, mins);
8378 VectorCopy(vcurrent.v, maxs);
8382 mins[0] = min(mins[0], vcurrent.v[0]);
8383 mins[1] = min(mins[1], vcurrent.v[1]);
8384 mins[2] = min(mins[2], vcurrent.v[2]);
8385 maxs[0] = max(maxs[0], vcurrent.v[0]);
8386 maxs[1] = max(maxs[1], vcurrent.v[1]);
8387 maxs[2] = max(maxs[2], vcurrent.v[2]);
8393 if (maxtriangles <= numtriangles)
8395 objtriangle_t *oldtriangles = triangles;
8397 triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8400 memcpy(triangles, oldtriangles, maxtriangles * sizeof(*triangles));
8401 Mem_Free(oldtriangles);
8404 triangles[numtriangles].textureindex = textureindex;
8405 triangles[numtriangles].vertex[0] = vfirst;
8406 triangles[numtriangles].vertex[1] = vprev;
8407 triangles[numtriangles].vertex[2] = vcurrent;
8414 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8416 else if (!!strcmp(argv[0], "usemtl"))
8418 for (i = 0;i < numtextures;i++)
8419 if (!strcmp(texturenames[numtextures], argv[1]))
8421 if (i < numtextures)
8422 texture = textures + i;
8425 if (maxtextures <= numtextures)
8427 texture_t *oldtextures = textures;
8429 textures = Mem_Alloc(tempmempool, maxtextures * sizeof(*textures));
8432 memcpy(textures, oldtextures, numtextures * sizeof(*textures));
8433 Mem_Free(oldtextures);
8436 textureindex = numtextures++;
8437 texturenames[textureindex] = Mem_Alloc(tempmempool, strlen(argv[1]) + 1);
8438 memcpy(texturenames[textureindex], argv[1], strlen(argv[1]) + 1);
8448 // now that we have the OBJ data loaded as-is, we can convert it
8450 // load the textures
8451 loadmodel->num_textures = numtextures;
8452 loadmodel->data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
8453 for (i = 0;i < numtextures;i++)
8454 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, texturenames[i], true, true, TEXF_MIPMAP | TEXF_ALPHA | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
8456 // free the texturenames array since we are now done with it
8457 for (i = 0;i < numtextures;i++)
8459 Mem_Free(texturenames[i]);
8460 texturenames[i] = NULL;
8462 Mem_Free(texturenames);
8463 texturenames = NULL;
8465 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8466 VectorCopy(mins, loadmodel->normalmins);
8467 VectorCopy(maxs, loadmodel->normalmaxs);
8468 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8469 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8470 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8471 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8472 modelradius = modelyawradius + modelradius * modelradius;
8473 modelyawradius = sqrt(modelyawradius);
8474 modelradius = sqrt(modelradius);
8475 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8476 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8477 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8478 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8479 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8480 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8481 loadmodel->radius = modelradius;
8482 loadmodel->radius2 = modelradius * modelradius;
8484 // make sure the temp triangle buffer is big enough for BSP building
8485 maxclippedtriangles = numtriangles*4;
8486 if (numtriangles > 0)
8488 clippedfronttriangles = Mem_Alloc(loadmodel->mempool, maxclippedtriangles * 2 * sizeof(objtriangle_t));
8489 clippedbacktriangles = clippedfronttriangles + maxclippedtriangles;
8492 // generate a rough BSP tree from triangle data, we don't have to be too careful here, it only has to define the basic areas of the map
8493 loadmodel->brush.num_leafs = 0;
8494 loadmodel->brush.num_nodes = 0;
8495 Mem_ExpandableArray_NewArray(&nodesarray, loadmodel->mempool, sizeof(objnode_t), 1024);
8496 rootnode = Mod_OBJ_BSPNodeForTriangles(triangles, numtriangles, mins, maxs, &nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8498 // convert the BSP tree to mnode_t and mleaf_t structures and convert the triangles to msurface_t...
8499 loadmodel->brush.data_leafs = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8500 loadmodel->brush.data_nodes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mnode_t));
8501 loadmodel->brush.data_planes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mplane_t));
8502 loadmodel->brush.num_leafs = 0;
8503 loadmodel->brush.num_nodes = 0;
8504 loadmodel->brush.num_planes = 0;
8505 Mod_OBJ_ConvertAndFreeBSPNode(rootnode);
8507 if (clippedfronttriangles)
8508 Mem_Free(clippedfronttriangles);
8509 maxclippedtriangles = 0;
8510 clippedfronttriangles = NULL;
8511 clippedbacktriangles = NULL;
8513 --- NOTHING DONE PAST THIS POINT ---
8515 loadmodel->numskins = LittleLong(pinmodel->num_skins);
8516 numxyz = LittleLong(pinmodel->num_xyz);
8517 numst = LittleLong(pinmodel->num_st);
8518 loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
8519 loadmodel->numframes = LittleLong(pinmodel->num_frames);
8520 loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
8521 loadmodel->num_poses = loadmodel->surfmesh.num_morphframes;
8522 skinwidth = LittleLong(pinmodel->skinwidth);
8523 skinheight = LittleLong(pinmodel->skinheight);
8524 iskinwidth = 1.0f / skinwidth;
8525 iskinheight = 1.0f / skinheight;
8527 loadmodel->num_surfaces = 1;
8528 loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
8529 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t) + loadmodel->num_surfaces * sizeof(int) + loadmodel->numframes * sizeof(animscene_t) + loadmodel->numframes * sizeof(float[6]) + loadmodel->surfmesh.num_triangles * sizeof(int[3]) + loadmodel->surfmesh.num_triangles * sizeof(int[3]));
8530 loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
8531 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8532 loadmodel->sortedmodelsurfaces[0] = 0;
8533 loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
8534 loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
8535 loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8536 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8538 loadmodel->synctype = ST_RAND;
8541 inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
8542 skinfiles = Mod_LoadSkinFiles();
8545 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8546 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8547 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8548 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
8549 Mod_FreeSkinFiles(skinfiles);
8551 else if (loadmodel->numskins)
8553 // skins found (most likely not a player model)
8554 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8555 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8556 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8557 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
8558 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i * loadmodel->num_surfaces, inskin, true, true, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP | TEXF_COMPRESS);
8562 // no skins (most likely a player model)
8563 loadmodel->numskins = 1;
8564 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8565 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8566 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8567 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
8570 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8571 for (i = 0;i < loadmodel->numskins;i++)
8573 loadmodel->skinscenes[i].firstframe = i;
8574 loadmodel->skinscenes[i].framecount = 1;
8575 loadmodel->skinscenes[i].loop = true;
8576 loadmodel->skinscenes[i].framerate = 10;
8579 // load the triangles and stvert data
8580 inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
8581 intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
8582 md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
8583 md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
8584 // swap the triangle list
8585 loadmodel->surfmesh.num_vertices = 0;
8586 for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
8588 for (j = 0;j < 3;j++)
8590 xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
8591 st = (unsigned short) LittleShort (intri[i].index_st[j]);
8594 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
8599 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
8602 hashindex = (xyz * 256 + st) & 65535;
8603 for (hash = md2verthash[hashindex];hash;hash = hash->next)
8604 if (hash->xyz == xyz && hash->st == st)
8608 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
8611 hash->next = md2verthash[hashindex];
8612 md2verthash[hashindex] = hash;
8614 loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
8618 vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
8619 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(float[2]) + loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t));
8620 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
8621 loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
8622 for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
8625 hash = md2verthashdata + i;
8626 vertremap[i] = hash->xyz;
8627 sts = LittleShort(inst[hash->st*2+0]);
8628 stt = LittleShort(inst[hash->st*2+1]);
8629 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
8631 Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
8635 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
8636 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
8639 Mem_Free(md2verthash);
8640 Mem_Free(md2verthashdata);
8642 // generate ushort elements array if possible
8643 if (loadmodel->surfmesh.num_vertices <= 65536)
8644 loadmodel->surfmesh.data_element3s = (unsigned short *)Mem_Alloc(loadmodel->mempool, sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles);
8647 datapointer = (base + LittleLong(pinmodel->ofs_frames));
8648 for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
8653 pinframe = (md2frame_t *)datapointer;
8654 datapointer += sizeof(md2frame_t);
8655 // store the frame scale/translate into the appropriate array
8656 for (j = 0;j < 3;j++)
8658 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
8659 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
8661 // convert the vertices
8662 v = (trivertx_t *)datapointer;
8663 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
8664 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
8665 out[k] = v[vertremap[k]];
8666 datapointer += numxyz * sizeof(trivertx_t);
8668 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
8669 loadmodel->animscenes[i].firstframe = i;
8670 loadmodel->animscenes[i].framecount = 1;
8671 loadmodel->animscenes[i].framerate = 10;
8672 loadmodel->animscenes[i].loop = true;
8675 Mem_Free(vertremap);
8677 Mod_MakeSortedSurfaces(loadmodel);
8678 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8679 Mod_Alias_CalculateBoundingBox();
8680 Mod_Alias_MorphMesh_CompileFrames();
8682 surface = loadmodel->data_surfaces;
8683 surface->texture = loadmodel->data_textures;
8684 surface->num_firsttriangle = 0;
8685 surface->num_triangles = loadmodel->surfmesh.num_triangles;
8686 surface->num_firstvertex = 0;
8687 surface->num_vertices = loadmodel->surfmesh.num_vertices;
8689 loadmodel->surfmesh.isanimated = false;
8691 if (loadmodel->surfmesh.data_element3s)
8692 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8693 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8696 #endif // !OBJASMODEL
8698 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
8700 // we already have done PVS culling at this point...
8701 // so we don't need to do it again.
8704 vec3_t testorigin, mins, maxs;
8706 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
8707 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
8708 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
8710 if(model->brush.TraceLineOfSight(model, eye, testorigin))
8713 // expand the box a little
8714 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
8715 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
8716 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
8717 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
8718 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
8719 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
8721 for(i = 0; i != numsamples; ++i)
8723 testorigin[0] = lhrandom(mins[0], maxs[0]);
8724 testorigin[1] = lhrandom(mins[1], maxs[1]);
8725 testorigin[2] = lhrandom(mins[2], maxs[2]);
8727 if(model->brush.TraceLineOfSight(model, eye, testorigin))