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_picmipworld = {CVAR_SAVE, "r_picmipworld", "1", "whether gl_picmip shall apply to world textures too"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
42 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)"};
43 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)"};
44 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
45 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
46 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, ..."};
47 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)"};
48 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
49 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces"};
51 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)"};
52 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"};
53 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"};
55 static texture_t mod_q1bsp_texture_solid;
56 static texture_t mod_q1bsp_texture_sky;
57 static texture_t mod_q1bsp_texture_lava;
58 static texture_t mod_q1bsp_texture_slime;
59 static texture_t mod_q1bsp_texture_water;
61 void Mod_BrushInit(void)
63 // Cvar_RegisterVariable(&r_subdivide_size);
64 Cvar_RegisterVariable(&r_novis);
65 Cvar_RegisterVariable(&r_picmipworld);
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_q1bsp_polygoncollisions);
85 Cvar_RegisterVariable(&mod_collision_bih);
86 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
88 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
89 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
90 mod_q1bsp_texture_solid.surfaceflags = 0;
91 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
93 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
94 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
95 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
96 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
98 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
99 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
100 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
101 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
103 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
104 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
105 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
106 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
108 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
109 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
110 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
111 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
114 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
121 // LordHavoc: modified to start at first clip node,
122 // in other words: first node of the (sub)model
123 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
125 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
127 return (mleaf_t *)node;
130 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
134 leaf = Mod_Q1BSP_PointInLeaf(model, p);
137 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
140 memcpy(out, leaf->ambient_sound_level, i);
146 memset(out, 0, outsize);
149 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
152 int nodestackindex = 0;
153 mnode_t *node, *nodestack[1024];
154 if (!model->brush.num_pvsclusters)
156 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
162 // node - recurse down the BSP tree
163 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
167 return -1; // ERROR: NAN bounding box!
168 // box is on one side of plane, take that path
169 node = node->children[sides-1];
173 // box crosses plane, take one path and remember the other
174 if (nodestackindex < 1024)
175 nodestack[nodestackindex++] = node->children[0];
176 node = node->children[1];
182 // leaf - add clusterindex to list
183 if (numclusters < maxclusters)
184 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
188 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
192 if (nodestackindex < 1024)
193 nodestack[nodestackindex++] = node->children[0];
194 node = node->children[1];
199 // leaf - add clusterindex to list
200 if (numclusters < maxclusters)
201 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
206 // try another path we didn't take earlier
207 if (nodestackindex == 0)
209 node = nodestack[--nodestackindex];
211 // return number of clusters found (even if more than the maxclusters)
215 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
217 int nodestackindex = 0;
218 mnode_t *node, *nodestack[1024];
219 if (!model->brush.num_pvsclusters)
221 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
227 // node - recurse down the BSP tree
228 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
232 return -1; // ERROR: NAN bounding box!
233 // box is on one side of plane, take that path
234 node = node->children[sides-1];
238 // box crosses plane, take one path and remember the other
239 if (nodestackindex < 1024)
240 nodestack[nodestackindex++] = node->children[0];
241 node = node->children[1];
247 // leaf - check cluster bit
248 int clusterindex = ((mleaf_t *)node)->clusterindex;
249 if (CHECKPVSBIT(pvs, clusterindex))
251 // it is visible, return immediately with the news
256 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
260 if (nodestackindex < 1024)
261 nodestack[nodestackindex++] = node->children[0];
262 node = node->children[1];
267 // leaf - check cluster bit
268 int clusterindex = ((mleaf_t *)node)->clusterindex;
269 if (CHECKPVSBIT(pvs, clusterindex))
271 // it is visible, return immediately with the news
277 // nothing to see here, try another path we didn't take earlier
278 if (nodestackindex == 0)
280 node = nodestack[--nodestackindex];
286 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
288 int nodestackindex = 0;
289 mnode_t *node, *nodestack[1024];
290 if (!model->brush.num_leafs)
292 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
298 // node - recurse down the BSP tree
299 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
303 return -1; // ERROR: NAN bounding box!
304 // box is on one side of plane, take that path
305 node = node->children[sides-1];
309 // box crosses plane, take one path and remember the other
310 if (nodestackindex < 1024)
311 nodestack[nodestackindex++] = node->children[0];
312 node = node->children[1];
318 // leaf - check cluster bit
319 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
320 if (CHECKPVSBIT(pvs, clusterindex))
322 // it is visible, return immediately with the news
327 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
331 if (nodestackindex < 1024)
332 nodestack[nodestackindex++] = node->children[0];
333 node = node->children[1];
338 // leaf - check cluster bit
339 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
340 if (CHECKPVSBIT(pvs, clusterindex))
342 // it is visible, return immediately with the news
348 // nothing to see here, try another path we didn't take earlier
349 if (nodestackindex == 0)
351 node = nodestack[--nodestackindex];
357 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
359 int nodestackindex = 0;
360 mnode_t *node, *nodestack[1024];
361 if (!model->brush.num_leafs)
363 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
369 // node - recurse down the BSP tree
370 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
374 return -1; // ERROR: NAN bounding box!
375 // box is on one side of plane, take that path
376 node = node->children[sides-1];
380 // box crosses plane, take one path and remember the other
381 if (nodestackindex < 1024)
382 nodestack[nodestackindex++] = node->children[0];
383 node = node->children[1];
389 // leaf - check if it is visible
390 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
392 // it is visible, return immediately with the news
397 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
401 if (nodestackindex < 1024)
402 nodestack[nodestackindex++] = node->children[0];
403 node = node->children[1];
408 // leaf - check if it is visible
409 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
411 // it is visible, return immediately with the news
417 // nothing to see here, try another path we didn't take earlier
418 if (nodestackindex == 0)
420 node = nodestack[--nodestackindex];
426 typedef struct findnonsolidlocationinfo_s
429 vec3_t absmin, absmax;
435 findnonsolidlocationinfo_t;
437 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
440 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
442 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
443 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
444 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
445 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
446 VectorSubtract(vert[1], vert[0], edge[0]);
447 VectorSubtract(vert[2], vert[1], edge[1]);
448 CrossProduct(edge[1], edge[0], facenormal);
449 if (facenormal[0] || facenormal[1] || facenormal[2])
451 VectorNormalize(facenormal);
452 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
453 if (f <= info->bestdist && f >= -info->bestdist)
455 VectorSubtract(vert[0], vert[2], edge[2]);
456 VectorNormalize(edge[0]);
457 VectorNormalize(edge[1]);
458 VectorNormalize(edge[2]);
459 CrossProduct(facenormal, edge[0], edgenormal[0]);
460 CrossProduct(facenormal, edge[1], edgenormal[1]);
461 CrossProduct(facenormal, edge[2], edgenormal[2]);
463 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
464 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
465 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
467 // we got lucky, the center is within the face
468 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
472 if (info->bestdist > dist)
474 info->bestdist = dist;
475 VectorScale(facenormal, (info->radius - -dist), info->nudge);
480 if (info->bestdist > dist)
482 info->bestdist = dist;
483 VectorScale(facenormal, (info->radius - dist), info->nudge);
489 // check which edge or vertex the center is nearest
490 for (i = 0;i < 3;i++)
492 f = DotProduct(info->center, edge[i]);
493 if (f >= DotProduct(vert[0], edge[i])
494 && f <= DotProduct(vert[1], edge[i]))
497 VectorMA(info->center, -f, edge[i], point);
498 dist = sqrt(DotProduct(point, point));
499 if (info->bestdist > dist)
501 info->bestdist = dist;
502 VectorScale(point, (info->radius / dist), info->nudge);
504 // skip both vertex checks
505 // (both are further away than this edge)
510 // not on edge, check first vertex of edge
511 VectorSubtract(info->center, vert[i], point);
512 dist = sqrt(DotProduct(point, point));
513 if (info->bestdist > dist)
515 info->bestdist = dist;
516 VectorScale(point, (info->radius / dist), info->nudge);
525 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
527 int surfacenum, k, *mark;
529 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
531 surface = info->model->data_surfaces + *mark;
532 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
534 if(surface->deprecatedq3num_bboxstride > 0)
537 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
538 for(i = 0; i < cnt; ++i)
540 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
542 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
544 tri = i * surface->deprecatedq3num_bboxstride + k;
545 if(tri >= surface->num_triangles)
547 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
554 for (k = 0;k < surface->num_triangles;k++)
556 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
563 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
567 float f = PlaneDiff(info->center, node->plane);
568 if (f >= -info->bestdist)
569 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
570 if (f <= info->bestdist)
571 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
575 if (((mleaf_t *)node)->numleafsurfaces)
576 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
580 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
583 findnonsolidlocationinfo_t info;
589 VectorCopy(in, info.center);
590 info.radius = radius;
595 VectorClear(info.nudge);
596 info.bestdist = radius;
597 VectorCopy(info.center, info.absmin);
598 VectorCopy(info.center, info.absmax);
599 info.absmin[0] -= info.radius + 1;
600 info.absmin[1] -= info.radius + 1;
601 info.absmin[2] -= info.radius + 1;
602 info.absmax[0] += info.radius + 1;
603 info.absmax[1] += info.radius + 1;
604 info.absmax[2] += info.radius + 1;
605 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
606 VectorAdd(info.center, info.nudge, info.center);
608 while (info.bestdist < radius && ++i < 10);
609 VectorCopy(info.center, out);
612 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
614 switch(nativecontents)
619 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
621 return SUPERCONTENTS_WATER;
623 return SUPERCONTENTS_SLIME;
625 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
627 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
632 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
634 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
635 return CONTENTS_SOLID;
636 if (supercontents & SUPERCONTENTS_SKY)
638 if (supercontents & SUPERCONTENTS_LAVA)
639 return CONTENTS_LAVA;
640 if (supercontents & SUPERCONTENTS_SLIME)
641 return CONTENTS_SLIME;
642 if (supercontents & SUPERCONTENTS_WATER)
643 return CONTENTS_WATER;
644 return CONTENTS_EMPTY;
647 typedef struct RecursiveHullCheckTraceInfo_s
649 // the hull we're tracing through
652 // the trace structure to fill in
655 // start, end, and end - start (in model space)
660 RecursiveHullCheckTraceInfo_t;
662 // 1/32 epsilon to keep floating point happy
663 #define DIST_EPSILON (0.03125)
665 #define HULLCHECKSTATE_EMPTY 0
666 #define HULLCHECKSTATE_SOLID 1
667 #define HULLCHECKSTATE_DONE 2
669 extern cvar_t collision_prefernudgedfraction;
670 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
672 // status variables, these don't need to be saved on the stack when
673 // recursing... but are because this should be thread-safe
674 // (note: tracing against a bbox is not thread-safe, yet)
679 // variables that need to be stored on the stack when recursing
684 // LordHavoc: a goto! everyone flee in terror... :)
689 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
690 if (!t->trace->startfound)
692 t->trace->startfound = true;
693 t->trace->startsupercontents |= num;
695 if (num & SUPERCONTENTS_LIQUIDSMASK)
696 t->trace->inwater = true;
698 t->trace->inopen = true;
699 if (num & SUPERCONTENTS_SOLID)
700 t->trace->hittexture = &mod_q1bsp_texture_solid;
701 else if (num & SUPERCONTENTS_SKY)
702 t->trace->hittexture = &mod_q1bsp_texture_sky;
703 else if (num & SUPERCONTENTS_LAVA)
704 t->trace->hittexture = &mod_q1bsp_texture_lava;
705 else if (num & SUPERCONTENTS_SLIME)
706 t->trace->hittexture = &mod_q1bsp_texture_slime;
708 t->trace->hittexture = &mod_q1bsp_texture_water;
709 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
710 t->trace->hitsupercontents = num;
711 if (num & t->trace->hitsupercontentsmask)
713 // if the first leaf is solid, set startsolid
714 if (t->trace->allsolid)
715 t->trace->startsolid = true;
716 #if COLLISIONPARANOID >= 3
719 return HULLCHECKSTATE_SOLID;
723 t->trace->allsolid = false;
724 #if COLLISIONPARANOID >= 3
727 return HULLCHECKSTATE_EMPTY;
731 // find the point distances
732 node = t->hull->clipnodes + num;
734 plane = t->hull->planes + node->planenum;
737 t1 = p1[plane->type] - plane->dist;
738 t2 = p2[plane->type] - plane->dist;
742 t1 = DotProduct (plane->normal, p1) - plane->dist;
743 t2 = DotProduct (plane->normal, p2) - plane->dist;
750 #if COLLISIONPARANOID >= 3
753 num = node->children[1];
762 #if COLLISIONPARANOID >= 3
765 num = node->children[0];
771 // the line intersects, find intersection point
772 // LordHavoc: this uses the original trace for maximum accuracy
773 #if COLLISIONPARANOID >= 3
778 t1 = t->start[plane->type] - plane->dist;
779 t2 = t->end[plane->type] - plane->dist;
783 t1 = DotProduct (plane->normal, t->start) - plane->dist;
784 t2 = DotProduct (plane->normal, t->end) - plane->dist;
787 midf = t1 / (t1 - t2);
788 midf = bound(p1f, midf, p2f);
789 VectorMA(t->start, midf, t->dist, mid);
791 // recurse both sides, front side first
792 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
793 // if this side is not empty, return what it is (solid or done)
794 if (ret != HULLCHECKSTATE_EMPTY)
797 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
798 // if other side is not solid, return what it is (empty or done)
799 if (ret != HULLCHECKSTATE_SOLID)
802 // front is air and back is solid, this is the impact point...
805 t->trace->plane.dist = -plane->dist;
806 VectorNegate (plane->normal, t->trace->plane.normal);
810 t->trace->plane.dist = plane->dist;
811 VectorCopy (plane->normal, t->trace->plane.normal);
814 // calculate the true fraction
815 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
816 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
817 midf = t1 / (t1 - t2);
818 t->trace->realfraction = bound(0, midf, 1);
820 // calculate the return fraction which is nudged off the surface a bit
821 midf = (t1 - DIST_EPSILON) / (t1 - t2);
822 t->trace->fraction = bound(0, midf, 1);
824 if (collision_prefernudgedfraction.integer)
825 t->trace->realfraction = t->trace->fraction;
827 #if COLLISIONPARANOID >= 3
830 return HULLCHECKSTATE_DONE;
833 //#if COLLISIONPARANOID < 2
834 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
837 mclipnode_t *nodes = t->hull->clipnodes;
838 mplane_t *planes = t->hull->planes;
840 VectorCopy(t->start, point);
843 plane = planes + nodes[num].planenum;
844 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
846 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
847 t->trace->startsupercontents |= num;
848 if (num & SUPERCONTENTS_LIQUIDSMASK)
849 t->trace->inwater = true;
851 t->trace->inopen = true;
852 if (num & t->trace->hitsupercontentsmask)
854 t->trace->allsolid = t->trace->startsolid = true;
855 return HULLCHECKSTATE_SOLID;
859 t->trace->allsolid = t->trace->startsolid = false;
860 return HULLCHECKSTATE_EMPTY;
865 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)
867 RecursiveHullCheckTraceInfo_t rhc;
869 memset(&rhc, 0, sizeof(rhc));
870 memset(trace, 0, sizeof(trace_t));
872 rhc.trace->fraction = 1;
873 rhc.trace->realfraction = 1;
874 rhc.trace->allsolid = true;
875 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
876 VectorCopy(start, rhc.start);
877 VectorCopy(start, rhc.end);
878 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
881 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)
883 RecursiveHullCheckTraceInfo_t rhc;
885 if (VectorCompare(start, end))
887 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
891 memset(&rhc, 0, sizeof(rhc));
892 memset(trace, 0, sizeof(trace_t));
894 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
895 rhc.trace->fraction = 1;
896 rhc.trace->realfraction = 1;
897 rhc.trace->allsolid = true;
898 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
899 VectorCopy(start, rhc.start);
900 VectorCopy(end, rhc.end);
901 VectorSubtract(rhc.end, rhc.start, rhc.dist);
902 #if COLLISIONPARANOID >= 2
903 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]);
904 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
909 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
910 memset(&testtrace, 0, sizeof(trace_t));
911 rhc.trace = &testtrace;
912 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
913 rhc.trace->fraction = 1;
914 rhc.trace->realfraction = 1;
915 rhc.trace->allsolid = true;
916 VectorCopy(test, rhc.start);
917 VectorCopy(test, rhc.end);
918 VectorClear(rhc.dist);
919 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
920 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
921 if (!trace->startsolid && testtrace.startsolid)
922 Con_Printf(" - ended in solid!\n");
926 if (VectorLength2(rhc.dist))
927 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
929 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
933 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)
935 // this function currently only supports same size start and end
937 RecursiveHullCheckTraceInfo_t rhc;
939 if (VectorCompare(boxmins, boxmaxs))
941 if (VectorCompare(start, end))
942 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
944 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
948 memset(&rhc, 0, sizeof(rhc));
949 memset(trace, 0, sizeof(trace_t));
951 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
952 rhc.trace->fraction = 1;
953 rhc.trace->realfraction = 1;
954 rhc.trace->allsolid = true;
955 VectorSubtract(boxmaxs, boxmins, boxsize);
957 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
958 else if (model->brush.ishlbsp)
960 // LordHavoc: this has to have a minor tolerance (the .1) because of
961 // minor float precision errors from the box being transformed around
962 if (boxsize[0] < 32.1)
964 if (boxsize[2] < 54) // pick the nearest of 36 or 72
965 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
967 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
970 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
974 // LordHavoc: this has to have a minor tolerance (the .1) because of
975 // minor float precision errors from the box being transformed around
976 if (boxsize[0] < 32.1)
977 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
979 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
981 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
982 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
983 VectorSubtract(rhc.end, rhc.start, rhc.dist);
984 #if COLLISIONPARANOID >= 2
985 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]);
986 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
991 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
992 memset(&testtrace, 0, sizeof(trace_t));
993 rhc.trace = &testtrace;
994 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
995 rhc.trace->fraction = 1;
996 rhc.trace->realfraction = 1;
997 rhc.trace->allsolid = true;
998 VectorCopy(test, rhc.start);
999 VectorCopy(test, rhc.end);
1000 VectorClear(rhc.dist);
1001 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1002 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1003 if (!trace->startsolid && testtrace.startsolid)
1004 Con_Printf(" - ended in solid!\n");
1008 if (VectorLength2(rhc.dist))
1009 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1011 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1015 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1017 int num = model->brushq1.hulls[0].firstclipnode;
1019 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1020 mplane_t *planes = model->brushq1.hulls[0].planes;
1023 plane = planes + nodes[num].planenum;
1024 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1026 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1029 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)
1033 colplanef_t cbox_planes[6];
1035 cbox.hasaabbplanes = true;
1036 cbox.supercontents = boxsupercontents;
1039 cbox.numtriangles = 0;
1040 cbox.planes = cbox_planes;
1042 cbox.elements = NULL;
1050 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];
1051 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];
1052 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];
1053 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];
1054 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];
1055 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];
1056 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1057 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1058 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1059 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1060 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1061 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1062 memset(trace, 0, sizeof(trace_t));
1063 trace->hitsupercontentsmask = hitsupercontentsmask;
1064 trace->fraction = 1;
1065 trace->realfraction = 1;
1066 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1068 RecursiveHullCheckTraceInfo_t rhc;
1069 static hull_t box_hull;
1070 static mclipnode_t box_clipnodes[6];
1071 static mplane_t box_planes[6];
1072 // fill in a default trace
1073 memset(&rhc, 0, sizeof(rhc));
1074 memset(trace, 0, sizeof(trace_t));
1075 //To keep everything totally uniform, bounding boxes are turned into small
1076 //BSP trees instead of being compared directly.
1077 // create a temp hull from bounding box sizes
1078 box_planes[0].dist = cmaxs[0] - mins[0];
1079 box_planes[1].dist = cmins[0] - maxs[0];
1080 box_planes[2].dist = cmaxs[1] - mins[1];
1081 box_planes[3].dist = cmins[1] - maxs[1];
1082 box_planes[4].dist = cmaxs[2] - mins[2];
1083 box_planes[5].dist = cmins[2] - maxs[2];
1084 #if COLLISIONPARANOID >= 3
1085 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]);
1088 if (box_hull.clipnodes == NULL)
1092 //Set up the planes and clipnodes so that the six floats of a bounding box
1093 //can just be stored out and get a proper hull_t structure.
1095 box_hull.clipnodes = box_clipnodes;
1096 box_hull.planes = box_planes;
1097 box_hull.firstclipnode = 0;
1098 box_hull.lastclipnode = 5;
1100 for (i = 0;i < 6;i++)
1102 box_clipnodes[i].planenum = i;
1106 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1108 box_clipnodes[i].children[side^1] = i + 1;
1110 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1112 box_planes[i].type = i>>1;
1113 box_planes[i].normal[i>>1] = 1;
1117 // trace a line through the generated clipping hull
1118 //rhc.boxsupercontents = boxsupercontents;
1119 rhc.hull = &box_hull;
1121 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1122 rhc.trace->fraction = 1;
1123 rhc.trace->realfraction = 1;
1124 rhc.trace->allsolid = true;
1125 VectorCopy(start, rhc.start);
1126 VectorCopy(end, rhc.end);
1127 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1128 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1129 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1130 if (rhc.trace->startsupercontents)
1131 rhc.trace->startsupercontents = boxsupercontents;
1135 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)
1137 memset(trace, 0, sizeof(trace_t));
1138 trace->fraction = 1;
1139 trace->realfraction = 1;
1140 if (BoxesOverlap(start, start, cmins, cmaxs))
1142 trace->startsupercontents |= boxsupercontents;
1143 if (hitsupercontentsmask & boxsupercontents)
1145 trace->startsolid = true;
1146 trace->allsolid = true;
1151 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1154 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1155 return trace.fraction == 1;
1158 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)
1162 float mid, distz = endz - startz;
1166 return false; // didn't hit anything
1168 switch (node->plane->type)
1171 node = node->children[x < node->plane->dist];
1174 node = node->children[y < node->plane->dist];
1177 side = startz < node->plane->dist;
1178 if ((endz < node->plane->dist) == side)
1180 node = node->children[side];
1183 // found an intersection
1184 mid = node->plane->dist;
1187 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1188 front += startz * node->plane->normal[2];
1189 back += endz * node->plane->normal[2];
1190 side = front < node->plane->dist;
1191 if ((back < node->plane->dist) == side)
1193 node = node->children[side];
1196 // found an intersection
1197 mid = startz + distz * (front - node->plane->dist) / (front - back);
1201 // go down front side
1202 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1203 return true; // hit something
1206 // check for impact on this node
1207 if (node->numsurfaces)
1209 int i, dsi, dti, lmwidth, lmheight;
1211 msurface_t *surface;
1212 unsigned char *lightmap;
1213 int maps, line3, size3;
1216 float scale, w, w00, w01, w10, w11;
1218 surface = model->data_surfaces + node->firstsurface;
1219 for (i = 0;i < node->numsurfaces;i++, surface++)
1221 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1222 continue; // no lightmaps
1224 // location we want to sample in the lightmap
1225 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;
1226 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;
1231 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1232 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1235 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1237 // calculate bilinear interpolation factors
1238 // and also multiply by fixedpoint conversion factors
1241 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1242 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1243 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1244 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1246 // values for pointer math
1247 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1248 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1250 // look up the pixel
1251 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1253 // bilinear filter each lightmap style, and sum them
1254 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1256 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1257 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1258 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1259 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1260 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1264 return true; // success
1269 // go down back side
1270 node = node->children[side ^ 1];
1272 distz = endz - startz;
1277 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1279 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1280 VectorSet(diffusenormal, 0, 0, 1);
1282 if (!model->brushq1.lightdata)
1284 VectorSet(ambientcolor, 1, 1, 1);
1285 VectorSet(diffusecolor, 0, 0, 0);
1289 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);
1292 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1295 unsigned char *outstart = out;
1296 while (out < outend)
1300 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));
1310 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));
1313 for (c = *in++;c > 0;c--)
1317 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));
1328 R_Q1BSP_LoadSplitSky
1330 A sky texture is 256*128, with the right side being a masked overlay
1333 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1338 unsigned *solidpixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1339 unsigned *alphapixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1341 // allocate a texture pool if we need it
1342 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1343 loadmodel->texturepool = R_AllocTexturePool();
1345 if (bytesperpixel == 4)
1347 for (y = 0;y < h;y++)
1349 for (x = 0;x < w;x++)
1351 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1352 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1358 // make an average value for the back to avoid
1359 // a fringe on the top level
1368 for (y = 0;y < h;y++)
1370 for (x = 0;x < w;x++)
1372 p = src[x*width+y+w];
1373 r += palette_rgb[p][0];
1374 g += palette_rgb[p][1];
1375 b += palette_rgb[p][2];
1378 bgra.b[2] = r/(w*h);
1379 bgra.b[1] = g/(w*h);
1380 bgra.b[0] = b/(w*h);
1382 for (y = 0;y < h;y++)
1384 for (x = 0;x < w;x++)
1386 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1388 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1393 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h);
1394 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1395 Mem_Free(solidpixels);
1396 Mem_Free(alphapixels);
1399 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1401 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1402 skinframe_t *skinframe;
1404 texture_t *tx, *tx2, *anims[10], *altanims[10];
1406 unsigned char *data, *mtdata;
1408 char mapname[MAX_QPATH], name[MAX_QPATH];
1409 unsigned char zero[4];
1411 memset(zero, 0, sizeof(zero));
1413 loadmodel->data_textures = NULL;
1415 // add two slots for notexture walls and notexture liquids
1418 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1419 m->nummiptex = LittleLong (m->nummiptex);
1420 loadmodel->num_textures = m->nummiptex + 2;
1421 loadmodel->num_texturesperskin = loadmodel->num_textures;
1426 loadmodel->num_textures = 2;
1427 loadmodel->num_texturesperskin = loadmodel->num_textures;
1430 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1432 // fill out all slots with notexture
1433 if (cls.state != ca_dedicated)
1434 skinframe = R_SkinFrame_LoadMissing();
1437 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1439 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1442 if (cls.state != ca_dedicated)
1444 tx->numskinframes = 1;
1445 tx->skinframerate = 1;
1446 tx->skinframes[0] = skinframe;
1447 tx->currentskinframe = tx->skinframes[0];
1449 tx->basematerialflags = MATERIALFLAG_WALL;
1450 if (i == loadmodel->num_textures - 1)
1452 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1453 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1454 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1458 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1459 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1461 tx->currentframe = tx;
1463 // clear water settings
1466 tx->refractfactor = 1;
1467 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1468 tx->reflectfactor = 1;
1469 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1470 tx->r_water_wateralpha = 1;
1471 tx->offsetmapping = OFFSETMAPPING_OFF;
1472 tx->offsetscale = 1;
1473 tx->specularscalemod = 1;
1474 tx->specularpowermod = 1;
1479 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1483 s = loadmodel->name;
1484 if (!strncasecmp(s, "maps/", 5))
1486 FS_StripExtension(s, mapname, sizeof(mapname));
1488 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1490 // LordHavoc: mostly rewritten map texture loader
1491 for (i = 0;i < m->nummiptex;i++)
1493 dofs[i] = LittleLong(dofs[i]);
1494 if (r_nosurftextures.integer)
1498 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1501 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1503 // copy name, but only up to 16 characters
1504 // (the output buffer can hold more than this, but the input buffer is
1506 for (j = 0;j < 16 && dmiptex->name[j];j++)
1507 name[j] = dmiptex->name[j];
1512 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1513 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1516 mtwidth = LittleLong(dmiptex->width);
1517 mtheight = LittleLong(dmiptex->height);
1519 j = LittleLong(dmiptex->offsets[0]);
1523 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1525 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1528 mtdata = (unsigned char *)dmiptex + j;
1531 if ((mtwidth & 15) || (mtheight & 15))
1532 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1534 // LordHavoc: force all names to lowercase
1535 for (j = 0;name[j];j++)
1536 if (name[j] >= 'A' && name[j] <= 'Z')
1537 name[j] += 'a' - 'A';
1539 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1542 tx = loadmodel->data_textures + i;
1543 strlcpy(tx->name, name, sizeof(tx->name));
1544 tx->width = mtwidth;
1545 tx->height = mtheight;
1547 if (tx->name[0] == '*')
1549 if (!strncmp(tx->name, "*lava", 5))
1551 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1552 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1554 else if (!strncmp(tx->name, "*slime", 6))
1556 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1557 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1561 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1562 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1565 else if (!strncmp(tx->name, "sky", 3))
1567 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1568 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1572 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1573 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1576 if (cls.state != ca_dedicated)
1578 // LordHavoc: HL sky textures are entirely different than quake
1579 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1581 data = loadimagepixelsbgra(tx->name, false, false, r_texture_convertsRGB_skin.integer);
1582 if (data && image_width == image_height * 2)
1584 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1587 else if (mtdata != NULL)
1588 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1592 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS, false);
1594 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS, false);
1597 // did not find external texture, load it from the bsp or wad3
1598 if (loadmodel->brush.ishlbsp)
1600 // internal texture overrides wad
1601 unsigned char *pixels, *freepixels;
1602 pixels = freepixels = NULL;
1604 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1606 pixels = freepixels = W_GetTextureBGRA(tx->name);
1609 tx->width = image_width;
1610 tx->height = image_height;
1611 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0), pixels, image_width, image_height);
1614 Mem_Free(freepixels);
1616 else if (mtdata) // texture included
1617 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0), false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1619 // if skinframe is still NULL the "missing" texture will be used
1621 tx->skinframes[0] = skinframe;
1624 tx->basematerialflags = MATERIALFLAG_WALL;
1625 if (tx->name[0] == '*')
1627 // LordHavoc: some turbulent textures should not be affected by wateralpha
1628 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1630 // replace the texture with transparent black
1631 Vector4Set(zero, 128, 128, 128, 128);
1632 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1633 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1635 else if (!strncmp(tx->name,"*lava",5)
1636 || !strncmp(tx->name,"*teleport",9)
1637 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1638 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1640 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1641 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1642 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1644 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1646 // replace the texture with black
1647 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1648 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1650 else if (!strncmp(tx->name, "sky", 3))
1651 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1652 else if (!strcmp(tx->name, "caulk"))
1653 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1654 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1655 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1657 // start out with no animation
1658 tx->currentframe = tx;
1659 tx->currentskinframe = tx->skinframes[0];
1663 // sequence the animations
1664 for (i = 0;i < m->nummiptex;i++)
1666 tx = loadmodel->data_textures + i;
1667 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1669 if (tx->anim_total[0] || tx->anim_total[1])
1670 continue; // already sequenced
1672 // find the number of frames in the animation
1673 memset(anims, 0, sizeof(anims));
1674 memset(altanims, 0, sizeof(altanims));
1676 for (j = i;j < m->nummiptex;j++)
1678 tx2 = loadmodel->data_textures + j;
1679 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1683 if (num >= '0' && num <= '9')
1684 anims[num - '0'] = tx2;
1685 else if (num >= 'a' && num <= 'j')
1686 altanims[num - 'a'] = tx2;
1688 Con_Printf("Bad animating texture %s\n", tx->name);
1692 for (j = 0;j < 10;j++)
1699 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1702 for (j = 0;j < max;j++)
1706 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1710 for (j = 0;j < altmax;j++)
1714 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1723 // if there is no alternate animation, duplicate the primary
1724 // animation into the alternate
1726 for (k = 0;k < 10;k++)
1727 altanims[k] = anims[k];
1730 // link together the primary animation
1731 for (j = 0;j < max;j++)
1734 tx2->animated = true;
1735 tx2->anim_total[0] = max;
1736 tx2->anim_total[1] = altmax;
1737 for (k = 0;k < 10;k++)
1739 tx2->anim_frames[0][k] = anims[k];
1740 tx2->anim_frames[1][k] = altanims[k];
1744 // if there really is an alternate anim...
1745 if (anims[0] != altanims[0])
1747 // link together the alternate animation
1748 for (j = 0;j < altmax;j++)
1751 tx2->animated = true;
1752 // the primary/alternate are reversed here
1753 tx2->anim_total[0] = altmax;
1754 tx2->anim_total[1] = max;
1755 for (k = 0;k < 10;k++)
1757 tx2->anim_frames[0][k] = altanims[k];
1758 tx2->anim_frames[1][k] = anims[k];
1765 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1768 unsigned char *in, *out, *data, d;
1769 char litfilename[MAX_QPATH];
1770 char dlitfilename[MAX_QPATH];
1771 fs_offset_t filesize;
1772 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1774 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1775 for (i=0; i<l->filelen; i++)
1776 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1778 else // LordHavoc: bsp version 29 (normal white lighting)
1780 // LordHavoc: hope is not lost yet, check for a .lit file to load
1781 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1782 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1783 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1784 strlcat (litfilename, ".lit", sizeof (litfilename));
1785 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1786 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1789 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1791 i = LittleLong(((int *)data)[1]);
1794 if (developer_loading.integer)
1795 Con_Printf("loaded %s\n", litfilename);
1796 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1797 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1799 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1802 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1804 i = LittleLong(((int *)data)[1]);
1807 if (developer_loading.integer)
1808 Con_Printf("loaded %s\n", dlitfilename);
1809 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1810 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1811 loadmodel->brushq3.deluxemapping_modelspace = false;
1812 loadmodel->brushq3.deluxemapping = true;
1821 Con_Printf("Unknown .lit file version (%d)\n", i);
1823 else if (filesize == 8)
1824 Con_Print("Empty .lit file, ignoring\n");
1826 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
1833 // LordHavoc: oh well, expand the white lighting data
1836 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1837 in = mod_base + l->fileofs;
1838 out = loadmodel->brushq1.lightdata;
1839 for (i = 0;i < l->filelen;i++)
1849 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1851 loadmodel->brushq1.num_compressedpvs = 0;
1852 loadmodel->brushq1.data_compressedpvs = NULL;
1855 loadmodel->brushq1.num_compressedpvs = l->filelen;
1856 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1857 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1860 // used only for HalfLife maps
1861 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1863 char key[128], value[4096];
1867 if (!COM_ParseToken_Simple(&data, false, false))
1869 if (com_token[0] != '{')
1873 if (!COM_ParseToken_Simple(&data, false, false))
1875 if (com_token[0] == '}')
1876 break; // end of worldspawn
1877 if (com_token[0] == '_')
1878 strlcpy(key, com_token + 1, sizeof(key));
1880 strlcpy(key, com_token, sizeof(key));
1881 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1882 key[strlen(key)-1] = 0;
1883 if (!COM_ParseToken_Simple(&data, false, false))
1885 dpsnprintf(value, sizeof(value), "%s", com_token);
1886 if (!strcmp("wad", key)) // for HalfLife maps
1888 if (loadmodel->brush.ishlbsp)
1891 for (i = 0;i < (int)sizeof(value);i++)
1892 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1896 for (;i < (int)sizeof(value);i++)
1898 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1899 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1901 else if (value[i] == ';' || value[i] == 0)
1905 W_LoadTextureWadFile(&value[j], false);
1917 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1919 loadmodel->brush.entities = NULL;
1922 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
1923 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1924 loadmodel->brush.entities[l->filelen] = 0;
1925 if (loadmodel->brush.ishlbsp)
1926 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1930 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1936 in = (dvertex_t *)(mod_base + l->fileofs);
1937 if (l->filelen % sizeof(*in))
1938 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1939 count = l->filelen / sizeof(*in);
1940 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1942 loadmodel->brushq1.vertexes = out;
1943 loadmodel->brushq1.numvertexes = count;
1945 for ( i=0 ; i<count ; i++, in++, out++)
1947 out->position[0] = LittleFloat(in->point[0]);
1948 out->position[1] = LittleFloat(in->point[1]);
1949 out->position[2] = LittleFloat(in->point[2]);
1953 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1954 // can be used for this
1956 int SB_ReadInt (unsigned char **buffer)
1959 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1965 float SB_ReadFloat (unsigned char **buffer)
1973 u.i = SB_ReadInt (buffer);
1977 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1979 unsigned char *index;
1983 index = (unsigned char *)(mod_base + l->fileofs);
1984 if (l->filelen % (48+4*hullinfo->filehulls))
1985 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1987 count = l->filelen / (48+4*hullinfo->filehulls);
1988 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1990 loadmodel->brushq1.submodels = out;
1991 loadmodel->brush.numsubmodels = count;
1993 for (i = 0; i < count; i++, out++)
1995 // spread out the mins / maxs by a pixel
1996 out->mins[0] = SB_ReadFloat (&index) - 1;
1997 out->mins[1] = SB_ReadFloat (&index) - 1;
1998 out->mins[2] = SB_ReadFloat (&index) - 1;
1999 out->maxs[0] = SB_ReadFloat (&index) + 1;
2000 out->maxs[1] = SB_ReadFloat (&index) + 1;
2001 out->maxs[2] = SB_ReadFloat (&index) + 1;
2002 out->origin[0] = SB_ReadFloat (&index);
2003 out->origin[1] = SB_ReadFloat (&index);
2004 out->origin[2] = SB_ReadFloat (&index);
2005 for (j = 0; j < hullinfo->filehulls; j++)
2006 out->headnode[j] = SB_ReadInt (&index);
2007 out->visleafs = SB_ReadInt (&index);
2008 out->firstface = SB_ReadInt (&index);
2009 out->numfaces = SB_ReadInt (&index);
2013 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2019 in = (dedge_t *)(mod_base + l->fileofs);
2020 if (l->filelen % sizeof(*in))
2021 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2022 count = l->filelen / sizeof(*in);
2023 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2025 loadmodel->brushq1.edges = out;
2026 loadmodel->brushq1.numedges = count;
2028 for ( i=0 ; i<count ; i++, in++, out++)
2030 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2031 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2032 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2034 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);
2035 if(!loadmodel->brushq1.numvertexes)
2036 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2044 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2048 int i, j, k, count, miptex;
2050 in = (texinfo_t *)(mod_base + l->fileofs);
2051 if (l->filelen % sizeof(*in))
2052 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2053 count = l->filelen / sizeof(*in);
2054 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2056 loadmodel->brushq1.texinfo = out;
2057 loadmodel->brushq1.numtexinfo = count;
2059 for (i = 0;i < count;i++, in++, out++)
2061 for (k = 0;k < 2;k++)
2062 for (j = 0;j < 4;j++)
2063 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2065 miptex = LittleLong(in->miptex);
2066 out->flags = LittleLong(in->flags);
2068 out->texture = NULL;
2069 if (loadmodel->data_textures)
2071 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2072 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2074 out->texture = loadmodel->data_textures + miptex;
2076 if (out->flags & TEX_SPECIAL)
2078 // if texture chosen is NULL or the shader needs a lightmap,
2079 // force to notexture water shader
2080 if (out->texture == NULL)
2081 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2085 // if texture chosen is NULL, force to notexture
2086 if (out->texture == NULL)
2087 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2093 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2098 mins[0] = mins[1] = mins[2] = 9999;
2099 maxs[0] = maxs[1] = maxs[2] = -9999;
2101 for (i = 0;i < numverts;i++)
2103 for (j = 0;j < 3;j++, v++)
2113 #define MAX_SUBDIVPOLYTRIANGLES 4096
2114 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2116 static int subdivpolyverts, subdivpolytriangles;
2117 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2118 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2120 static int subdivpolylookupvert(vec3_t v)
2123 for (i = 0;i < subdivpolyverts;i++)
2124 if (subdivpolyvert[i][0] == v[0]
2125 && subdivpolyvert[i][1] == v[1]
2126 && subdivpolyvert[i][2] == v[2])
2128 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2129 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2130 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2131 return subdivpolyverts++;
2134 static void SubdividePolygon(int numverts, float *verts)
2136 int i, i1, i2, i3, f, b, c, p;
2137 vec3_t mins, maxs, front[256], back[256];
2138 float m, *pv, *cv, dist[256], frac;
2141 Host_Error("SubdividePolygon: ran out of verts in buffer");
2143 BoundPoly(numverts, verts, mins, maxs);
2145 for (i = 0;i < 3;i++)
2147 m = (mins[i] + maxs[i]) * 0.5;
2148 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2149 if (maxs[i] - m < 8)
2151 if (m - mins[i] < 8)
2155 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2156 dist[c] = cv[i] - m;
2159 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2163 VectorCopy(pv, front[f]);
2168 VectorCopy(pv, back[b]);
2171 if (dist[p] == 0 || dist[c] == 0)
2173 if ((dist[p] > 0) != (dist[c] > 0) )
2176 frac = dist[p] / (dist[p] - dist[c]);
2177 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2178 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2179 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2185 SubdividePolygon(f, front[0]);
2186 SubdividePolygon(b, back[0]);
2190 i1 = subdivpolylookupvert(verts);
2191 i2 = subdivpolylookupvert(verts + 3);
2192 for (i = 2;i < numverts;i++)
2194 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2196 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2200 i3 = subdivpolylookupvert(verts + i * 3);
2201 subdivpolyindex[subdivpolytriangles][0] = i1;
2202 subdivpolyindex[subdivpolytriangles][1] = i2;
2203 subdivpolyindex[subdivpolytriangles][2] = i3;
2205 subdivpolytriangles++;
2209 //Breaks a polygon up along axial 64 unit
2210 //boundaries so that turbulent and sky warps
2211 //can be done reasonably.
2212 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2218 subdivpolytriangles = 0;
2219 subdivpolyverts = 0;
2220 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2221 if (subdivpolytriangles < 1)
2222 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2224 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2225 mesh->num_vertices = subdivpolyverts;
2226 mesh->num_triangles = subdivpolytriangles;
2227 mesh->vertex = (surfvertex_t *)(mesh + 1);
2228 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2229 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2231 for (i = 0;i < mesh->num_triangles;i++)
2232 for (j = 0;j < 3;j++)
2233 mesh->index[i*3+j] = subdivpolyindex[i][j];
2235 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2237 VectorCopy(subdivpolyvert[i], v->v);
2238 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2239 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2244 extern cvar_t gl_max_lightmapsize;
2245 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2248 msurface_t *surface;
2249 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2250 float texmins[2], texmaxs[2], val;
2251 rtexture_t *lightmaptexture, *deluxemaptexture;
2253 in = (dface_t *)(mod_base + l->fileofs);
2254 if (l->filelen % sizeof(*in))
2255 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2256 count = l->filelen / sizeof(*in);
2257 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2258 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2260 loadmodel->num_surfaces = count;
2262 loadmodel->brushq1.firstrender = true;
2263 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2267 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2269 numedges = (unsigned short)LittleShort(in->numedges);
2270 totalverts += numedges;
2271 totaltris += numedges - 2;
2274 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2276 lightmaptexture = NULL;
2277 deluxemaptexture = r_texture_blanknormalmap;
2279 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2280 totallightmapsamples = 0;
2284 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2286 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2288 // FIXME: validate edges, texinfo, etc?
2289 firstedge = LittleLong(in->firstedge);
2290 numedges = (unsigned short)LittleShort(in->numedges);
2291 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)
2292 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2293 i = (unsigned short)LittleShort(in->texinfo);
2294 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2295 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2296 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2297 surface->texture = surface->lightmapinfo->texinfo->texture;
2299 planenum = (unsigned short)LittleShort(in->planenum);
2300 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2301 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2303 //surface->flags = surface->texture->flags;
2304 //if (LittleShort(in->side))
2305 // surface->flags |= SURF_PLANEBACK;
2306 //surface->plane = loadmodel->brush.data_planes + planenum;
2308 surface->num_firstvertex = totalverts;
2309 surface->num_vertices = numedges;
2310 surface->num_firsttriangle = totaltris;
2311 surface->num_triangles = numedges - 2;
2312 totalverts += numedges;
2313 totaltris += numedges - 2;
2315 // convert edges back to a normal polygon
2316 for (i = 0;i < surface->num_vertices;i++)
2318 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2320 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2322 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2324 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2325 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2326 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2327 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2328 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2329 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2330 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2331 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2334 for (i = 0;i < surface->num_triangles;i++)
2336 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2337 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2338 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2341 // compile additional data about the surface geometry
2342 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);
2343 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);
2344 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2346 // generate surface extents information
2347 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2348 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2349 for (i = 1;i < surface->num_vertices;i++)
2351 for (j = 0;j < 2;j++)
2353 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2354 texmins[j] = min(texmins[j], val);
2355 texmaxs[j] = max(texmaxs[j], val);
2358 for (i = 0;i < 2;i++)
2360 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2361 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2364 smax = surface->lightmapinfo->extents[0] >> 4;
2365 tmax = surface->lightmapinfo->extents[1] >> 4;
2366 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2367 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2370 for (i = 0;i < MAXLIGHTMAPS;i++)
2371 surface->lightmapinfo->styles[i] = in->styles[i];
2372 surface->lightmaptexture = NULL;
2373 surface->deluxemaptexture = r_texture_blanknormalmap;
2374 i = LittleLong(in->lightofs);
2377 surface->lightmapinfo->samples = NULL;
2379 // give non-lightmapped water a 1x white lightmap
2380 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2382 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2383 surface->lightmapinfo->styles[0] = 0;
2384 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2388 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2389 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2390 else // LordHavoc: white lighting (bsp version 29)
2392 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2393 if (loadmodel->brushq1.nmaplightdata)
2394 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2397 // check if we should apply a lightmap to this
2398 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2400 if (ssize > 256 || tsize > 256)
2401 Host_Error("Bad surface extents");
2403 if (lightmapsize < ssize)
2404 lightmapsize = ssize;
2405 if (lightmapsize < tsize)
2406 lightmapsize = tsize;
2408 totallightmapsamples += ssize*tsize;
2410 // force lightmap upload on first time seeing the surface
2412 // additionally this is used by the later code to see if a
2413 // lightmap is needed on this surface (rather than duplicating the
2415 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2419 // small maps (such as ammo boxes especially) don't need big lightmap
2420 // textures, so this code tries to guess a good size based on
2421 // totallightmapsamples (size of the lightmaps lump basically), as well as
2422 // trying to max out the size if there is a lot of lightmap data to store
2423 // additionally, never choose a lightmapsize that is smaller than the
2424 // largest surface encountered (as it would fail)
2426 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2429 // now that we've decided the lightmap texture size, we can do the rest
2430 if (cls.state != ca_dedicated)
2432 int stainmapsize = 0;
2433 mod_alloclightmap_state_t allocState;
2435 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2436 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2438 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2439 float u, v, ubase, vbase, uscale, vscale;
2441 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2444 smax = surface->lightmapinfo->extents[0] >> 4;
2445 tmax = surface->lightmapinfo->extents[1] >> 4;
2446 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2447 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2448 stainmapsize += ssize * tsize * 3;
2450 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2452 // allocate a texture pool if we need it
2453 if (loadmodel->texturepool == NULL)
2454 loadmodel->texturepool = R_AllocTexturePool();
2455 // could not find room, make a new lightmap
2456 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2457 loadmodel->brushq3.data_lightmaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2458 loadmodel->brushq3.data_deluxemaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2459 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2460 if (loadmodel->brushq1.nmaplightdata)
2461 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2463 Mod_AllocLightmap_Reset(&allocState);
2464 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2466 surface->lightmaptexture = lightmaptexture;
2467 surface->deluxemaptexture = deluxemaptexture;
2468 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2469 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2471 uscale = 1.0f / (float)lightmapsize;
2472 vscale = 1.0f / (float)lightmapsize;
2473 ubase = lightmapx * uscale;
2474 vbase = lightmapy * vscale;
2476 for (i = 0;i < surface->num_vertices;i++)
2478 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);
2479 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);
2480 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2481 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2482 // LordHavoc: calc lightmap data offset for vertex lighting to use
2485 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2489 if (cl_stainmaps.integer)
2491 // allocate stainmaps for permanent marks on walls and clear white
2492 unsigned char *stainsamples = NULL;
2493 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2494 memset(stainsamples, 255, stainmapsize);
2496 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2498 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2500 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2501 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2502 surface->lightmapinfo->stainsamples = stainsamples;
2503 stainsamples += ssize * tsize * 3;
2508 // generate ushort elements array if possible
2509 if (loadmodel->surfmesh.data_element3s)
2510 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2511 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2514 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2517 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2518 node->parent = parent;
2521 // this is a node, recurse to children
2522 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2523 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2524 // combine supercontents of children
2525 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2530 mleaf_t *leaf = (mleaf_t *)node;
2531 // if this is a leaf, calculate supercontents mask from all collidable
2532 // primitives in the leaf (brushes and collision surfaces)
2533 // also flag if the leaf contains any collision surfaces
2534 leaf->combinedsupercontents = 0;
2535 // combine the supercontents values of all brushes in this leaf
2536 for (j = 0;j < leaf->numleafbrushes;j++)
2537 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2538 // check if this leaf contains any collision surfaces (q3 patches)
2539 for (j = 0;j < leaf->numleafsurfaces;j++)
2541 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2542 if (surface->num_collisiontriangles)
2544 leaf->containscollisionsurfaces = true;
2545 leaf->combinedsupercontents |= surface->texture->supercontents;
2551 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2557 in = (dnode_t *)(mod_base + l->fileofs);
2558 if (l->filelen % sizeof(*in))
2559 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2560 count = l->filelen / sizeof(*in);
2561 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2563 loadmodel->brush.data_nodes = out;
2564 loadmodel->brush.num_nodes = count;
2566 for ( i=0 ; i<count ; i++, in++, out++)
2568 for (j=0 ; j<3 ; j++)
2570 out->mins[j] = LittleShort(in->mins[j]);
2571 out->maxs[j] = LittleShort(in->maxs[j]);
2574 p = LittleLong(in->planenum);
2575 out->plane = loadmodel->brush.data_planes + p;
2577 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2578 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2580 for (j=0 ; j<2 ; j++)
2582 // LordHavoc: this code supports broken bsp files produced by
2583 // arguire qbsp which can produce more than 32768 nodes, any value
2584 // below count is assumed to be a node number, any other value is
2585 // assumed to be a leaf number
2586 p = (unsigned short)LittleShort(in->children[j]);
2589 if (p < loadmodel->brush.num_nodes)
2590 out->children[j] = loadmodel->brush.data_nodes + p;
2593 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2594 // map it to the solid leaf
2595 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2600 // note this uses 65535 intentionally, -1 is leaf 0
2602 if (p < loadmodel->brush.num_leafs)
2603 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2606 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2607 // map it to the solid leaf
2608 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2614 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2617 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2623 in = (dleaf_t *)(mod_base + l->fileofs);
2624 if (l->filelen % sizeof(*in))
2625 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2626 count = l->filelen / sizeof(*in);
2627 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2629 loadmodel->brush.data_leafs = out;
2630 loadmodel->brush.num_leafs = count;
2631 // get visleafs from the submodel data
2632 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2633 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2634 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2635 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2637 for ( i=0 ; i<count ; i++, in++, out++)
2639 for (j=0 ; j<3 ; j++)
2641 out->mins[j] = LittleShort(in->mins[j]);
2642 out->maxs[j] = LittleShort(in->maxs[j]);
2645 // FIXME: this function could really benefit from some error checking
2647 out->contents = LittleLong(in->contents);
2649 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2650 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2651 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2653 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);
2654 out->firstleafsurface = NULL;
2655 out->numleafsurfaces = 0;
2658 out->clusterindex = i - 1;
2659 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2660 out->clusterindex = -1;
2662 p = LittleLong(in->visofs);
2663 // ignore visofs errors on leaf 0 (solid)
2664 if (p >= 0 && out->clusterindex >= 0)
2666 if (p >= loadmodel->brushq1.num_compressedpvs)
2667 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2669 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);
2672 for (j = 0;j < 4;j++)
2673 out->ambient_sound_level[j] = in->ambient_level[j];
2675 // FIXME: Insert caustics here
2679 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2683 const unsigned char *pvs;
2684 // if there's no vis data, assume supported (because everything is visible all the time)
2685 if (!loadmodel->brush.data_pvsclusters)
2687 // check all liquid leafs to see if they can see into empty leafs, if any
2688 // can we can assume this map supports r_wateralpha
2689 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2691 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2693 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2694 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2695 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2702 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2709 in = (dclipnode_t *)(mod_base + l->fileofs);
2710 if (l->filelen % sizeof(*in))
2711 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2712 count = l->filelen / sizeof(*in);
2713 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2715 loadmodel->brushq1.clipnodes = out;
2716 loadmodel->brushq1.numclipnodes = count;
2718 for (i = 1; i < MAX_MAP_HULLS; i++)
2720 hull = &loadmodel->brushq1.hulls[i];
2721 hull->clipnodes = out;
2722 hull->firstclipnode = 0;
2723 hull->lastclipnode = count-1;
2724 hull->planes = loadmodel->brush.data_planes;
2725 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2726 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2727 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2728 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2729 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2730 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2731 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2734 for (i=0 ; i<count ; i++, out++, in++)
2736 out->planenum = LittleLong(in->planenum);
2737 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2738 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2739 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2740 if (out->children[0] >= count)
2741 out->children[0] -= 65536;
2742 if (out->children[1] >= count)
2743 out->children[1] -= 65536;
2744 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2745 Host_Error("Corrupt clipping hull(out of range planenum)");
2749 //Duplicate the drawing hull structure as a clipping hull
2750 static void Mod_Q1BSP_MakeHull0(void)
2757 hull = &loadmodel->brushq1.hulls[0];
2759 in = loadmodel->brush.data_nodes;
2760 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2762 hull->clipnodes = out;
2763 hull->firstclipnode = 0;
2764 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2765 hull->planes = loadmodel->brush.data_planes;
2767 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2769 out->planenum = in->plane - loadmodel->brush.data_planes;
2770 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2771 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2775 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2780 in = (short *)(mod_base + l->fileofs);
2781 if (l->filelen % sizeof(*in))
2782 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2783 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2784 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2786 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2788 j = (unsigned short) LittleShort(in[i]);
2789 if (j >= loadmodel->num_surfaces)
2790 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2791 loadmodel->brush.data_leafsurfaces[i] = j;
2795 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2800 in = (int *)(mod_base + l->fileofs);
2801 if (l->filelen % sizeof(*in))
2802 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2803 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2804 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2806 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2807 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2811 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2817 in = (dplane_t *)(mod_base + l->fileofs);
2818 if (l->filelen % sizeof(*in))
2819 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2821 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2822 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2824 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2826 out->normal[0] = LittleFloat(in->normal[0]);
2827 out->normal[1] = LittleFloat(in->normal[1]);
2828 out->normal[2] = LittleFloat(in->normal[2]);
2829 out->dist = LittleFloat(in->dist);
2835 static void Mod_Q1BSP_LoadMapBrushes(void)
2839 int submodel, numbrushes;
2840 qboolean firstbrush;
2841 char *text, *maptext;
2842 char mapfilename[MAX_QPATH];
2843 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2844 strlcat (mapfilename, ".map", sizeof (mapfilename));
2845 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
2849 if (!COM_ParseToken_Simple(&data, false, false))
2854 if (!COM_ParseToken_Simple(&data, false, false))
2856 if (com_token[0] != '{')
2862 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2865 if (!COM_ParseToken_Simple(&data, false, false))
2867 if (com_token[0] == '}')
2868 break; // end of entity
2869 if (com_token[0] == '{')
2876 if (submodel > loadmodel->brush.numsubmodels)
2878 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2882 model = loadmodel->brush.submodels[submodel];
2889 if (!COM_ParseToken_Simple(&data, false, false))
2891 if (com_token[0] == '}')
2892 break; // end of brush
2893 // each brush face should be this format:
2894 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2895 // FIXME: support hl .map format
2896 for (pointnum = 0;pointnum < 3;pointnum++)
2898 COM_ParseToken_Simple(&data, false, false);
2899 for (componentnum = 0;componentnum < 3;componentnum++)
2901 COM_ParseToken_Simple(&data, false, false);
2902 point[pointnum][componentnum] = atof(com_token);
2904 COM_ParseToken_Simple(&data, false, false);
2906 COM_ParseToken_Simple(&data, false, false);
2907 strlcpy(facetexture, com_token, sizeof(facetexture));
2908 COM_ParseToken_Simple(&data, false, false);
2909 //scroll_s = atof(com_token);
2910 COM_ParseToken_Simple(&data, false, false);
2911 //scroll_t = atof(com_token);
2912 COM_ParseToken_Simple(&data, false, false);
2913 //rotate = atof(com_token);
2914 COM_ParseToken_Simple(&data, false, false);
2915 //scale_s = atof(com_token);
2916 COM_ParseToken_Simple(&data, false, false);
2917 //scale_t = atof(com_token);
2918 TriangleNormal(point[0], point[1], point[2], planenormal);
2919 VectorNormalizeDouble(planenormal);
2920 planedist = DotProduct(point[0], planenormal);
2921 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2931 #define MAX_PORTALPOINTS 64
2933 typedef struct portal_s
2936 mnode_t *nodes[2]; // [0] = front side of plane
2937 struct portal_s *next[2];
2939 double points[3*MAX_PORTALPOINTS];
2940 struct portal_s *chain; // all portals are linked into a list
2944 static memexpandablearray_t portalarray;
2946 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2948 // process only nodes (leafs already had their box calculated)
2952 // calculate children first
2953 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2954 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2956 // make combined bounding box from children
2957 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2958 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2959 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2960 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2961 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2962 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2965 static void Mod_Q1BSP_FinalizePortals(void)
2967 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
2971 mleaf_t *leaf, *endleaf;
2973 // tally up portal and point counts and recalculate bounding boxes for all
2974 // leafs (because qbsp is very sloppy)
2975 leaf = loadmodel->brush.data_leafs;
2976 endleaf = leaf + loadmodel->brush.num_leafs;
2977 if (mod_recalculatenodeboxes.integer)
2979 for (;leaf < endleaf;leaf++)
2981 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2982 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2987 for (portalindex = 0;portalindex < portalrange;portalindex++)
2989 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
2992 // note: this check must match the one below or it will usually corrupt memory
2993 // 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
2994 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2997 numpoints += p->numpoints * 2;
3000 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3001 loadmodel->brush.num_portals = numportals;
3002 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3003 loadmodel->brush.num_portalpoints = numpoints;
3004 // clear all leaf portal chains
3005 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3006 loadmodel->brush.data_leafs[i].portals = NULL;
3007 // process all portals in the global portal chain, while freeing them
3008 portal = loadmodel->brush.data_portals;
3009 point = loadmodel->brush.data_portalpoints;
3010 for (portalindex = 0;portalindex < portalrange;portalindex++)
3012 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3015 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3017 // note: this check must match the one above or it will usually corrupt memory
3018 // 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
3019 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3021 // first make the back to front portal(forward portal)
3022 portal->points = point;
3023 portal->numpoints = p->numpoints;
3024 portal->plane.dist = p->plane.dist;
3025 VectorCopy(p->plane.normal, portal->plane.normal);
3026 portal->here = (mleaf_t *)p->nodes[1];
3027 portal->past = (mleaf_t *)p->nodes[0];
3029 for (j = 0;j < portal->numpoints;j++)
3031 VectorCopy(p->points + j*3, point->position);
3034 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3035 PlaneClassify(&portal->plane);
3037 // link into leaf's portal chain
3038 portal->next = portal->here->portals;
3039 portal->here->portals = portal;
3041 // advance to next portal
3044 // then make the front to back portal(backward portal)
3045 portal->points = point;
3046 portal->numpoints = p->numpoints;
3047 portal->plane.dist = -p->plane.dist;
3048 VectorNegate(p->plane.normal, portal->plane.normal);
3049 portal->here = (mleaf_t *)p->nodes[0];
3050 portal->past = (mleaf_t *)p->nodes[1];
3052 for (j = portal->numpoints - 1;j >= 0;j--)
3054 VectorCopy(p->points + j*3, point->position);
3057 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3058 PlaneClassify(&portal->plane);
3060 // link into leaf's portal chain
3061 portal->next = portal->here->portals;
3062 portal->here->portals = portal;
3064 // advance to next portal
3067 // add the portal's polygon points to the leaf bounding boxes
3068 if (mod_recalculatenodeboxes.integer)
3070 for (i = 0;i < 2;i++)
3072 leaf = (mleaf_t *)p->nodes[i];
3073 for (j = 0;j < p->numpoints;j++)
3075 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3076 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3077 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3078 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3079 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3080 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3086 // now recalculate the node bounding boxes from the leafs
3087 if (mod_recalculatenodeboxes.integer)
3088 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3096 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3099 Host_Error("AddPortalToNodes: NULL front node");
3101 Host_Error("AddPortalToNodes: NULL back node");
3102 if (p->nodes[0] || p->nodes[1])
3103 Host_Error("AddPortalToNodes: already included");
3104 // 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
3106 p->nodes[0] = front;
3107 p->next[0] = (portal_t *)front->portals;
3108 front->portals = (mportal_t *)p;
3111 p->next[1] = (portal_t *)back->portals;
3112 back->portals = (mportal_t *)p;
3117 RemovePortalFromNode
3120 static void RemovePortalFromNodes(portal_t *portal)
3124 void **portalpointer;
3126 for (i = 0;i < 2;i++)
3128 node = portal->nodes[i];
3130 portalpointer = (void **) &node->portals;
3133 t = (portal_t *)*portalpointer;
3135 Host_Error("RemovePortalFromNodes: portal not in leaf");
3139 if (portal->nodes[0] == node)
3141 *portalpointer = portal->next[0];
3142 portal->nodes[0] = NULL;
3144 else if (portal->nodes[1] == node)
3146 *portalpointer = portal->next[1];
3147 portal->nodes[1] = NULL;
3150 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3154 if (t->nodes[0] == node)
3155 portalpointer = (void **) &t->next[0];
3156 else if (t->nodes[1] == node)
3157 portalpointer = (void **) &t->next[1];
3159 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3164 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3165 static double *portalpointsbuffer;
3166 static int portalpointsbufferoffset;
3167 static int portalpointsbuffersize;
3168 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3171 mnode_t *front, *back, *other_node;
3172 mplane_t clipplane, *plane;
3173 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3174 int numfrontpoints, numbackpoints;
3175 double *frontpoints, *backpoints;
3177 // if a leaf, we're done
3181 // get some space for our clipping operations to use
3182 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3184 portalpointsbuffersize = portalpointsbufferoffset * 2;
3185 portalpointsbuffer = Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3187 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3188 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3189 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3190 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3192 plane = node->plane;
3194 front = node->children[0];
3195 back = node->children[1];
3197 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3199 // create the new portal by generating a polygon for the node plane,
3200 // and clipping it by all of the other portals(which came from nodes above this one)
3201 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3202 nodeportal->plane = *plane;
3204 // 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)
3205 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);
3206 nodeportal->numpoints = 4;
3207 side = 0; // shut up compiler warning
3208 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3210 clipplane = portal->plane;
3211 if (portal->nodes[0] == portal->nodes[1])
3212 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3213 if (portal->nodes[0] == node)
3215 else if (portal->nodes[1] == node)
3217 clipplane.dist = -clipplane.dist;
3218 VectorNegate(clipplane.normal, clipplane.normal);
3222 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3224 for (i = 0;i < nodeportal->numpoints*3;i++)
3225 frontpoints[i] = nodeportal->points[i];
3226 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);
3227 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3231 if (nodeportal->numpoints < 3)
3233 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3234 nodeportal->numpoints = 0;
3236 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3238 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3239 nodeportal->numpoints = 0;
3242 AddPortalToNodes(nodeportal, front, back);
3244 // split the portals of this node along this node's plane and assign them to the children of this node
3245 // (migrating the portals downward through the tree)
3246 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3248 if (portal->nodes[0] == portal->nodes[1])
3249 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3250 if (portal->nodes[0] == node)
3252 else if (portal->nodes[1] == node)
3255 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3256 nextportal = portal->next[side];
3257 if (!portal->numpoints)
3260 other_node = portal->nodes[!side];
3261 RemovePortalFromNodes(portal);
3263 // cut the portal into two portals, one on each side of the node plane
3264 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);
3266 if (!numfrontpoints)
3269 AddPortalToNodes(portal, back, other_node);
3271 AddPortalToNodes(portal, other_node, back);
3277 AddPortalToNodes(portal, front, other_node);
3279 AddPortalToNodes(portal, other_node, front);
3283 // the portal is split
3284 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3285 temp = splitportal->chain;
3286 *splitportal = *portal;
3287 splitportal->chain = temp;
3288 for (i = 0;i < numbackpoints*3;i++)
3289 splitportal->points[i] = backpoints[i];
3290 splitportal->numpoints = numbackpoints;
3291 for (i = 0;i < numfrontpoints*3;i++)
3292 portal->points[i] = frontpoints[i];
3293 portal->numpoints = numfrontpoints;
3297 AddPortalToNodes(portal, front, other_node);
3298 AddPortalToNodes(splitportal, back, other_node);
3302 AddPortalToNodes(portal, other_node, front);
3303 AddPortalToNodes(splitportal, other_node, back);
3307 Mod_Q1BSP_RecursiveNodePortals(front);
3308 Mod_Q1BSP_RecursiveNodePortals(back);
3310 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3313 static void Mod_Q1BSP_MakePortals(void)
3315 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3316 portalpointsbufferoffset = 0;
3317 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3318 portalpointsbuffer = Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3319 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3320 Mem_Free(portalpointsbuffer);
3321 portalpointsbuffer = NULL;
3322 portalpointsbufferoffset = 0;
3323 portalpointsbuffersize = 0;
3324 Mod_Q1BSP_FinalizePortals();
3325 Mem_ExpandableArray_FreeArray(&portalarray);
3328 //Returns PVS data for a given point
3329 //(note: can return NULL)
3330 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3333 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3335 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3336 if (((mleaf_t *)node)->clusterindex >= 0)
3337 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3342 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)
3346 float d = PlaneDiff(org, node->plane);
3348 node = node->children[0];
3349 else if (d < -radius)
3350 node = node->children[1];
3353 // go down both sides
3354 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3355 node = node->children[1];
3358 // if this leaf is in a cluster, accumulate the pvs bits
3359 if (((mleaf_t *)node)->clusterindex >= 0)
3362 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3363 for (i = 0;i < pvsbytes;i++)
3364 pvsbuffer[i] |= pvs[i];
3368 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3369 //of the given point.
3370 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3372 int bytes = model->brush.num_pvsclusterbytes;
3373 bytes = min(bytes, pvsbufferlength);
3374 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3376 memset(pvsbuffer, 0xFF, bytes);
3380 memset(pvsbuffer, 0, bytes);
3381 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3385 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3390 VectorSubtract(inmaxs, inmins, size);
3391 if (cmodel->brush.ishlbsp)
3394 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3395 else if (size[0] <= 32)
3397 if (size[2] < 54) // pick the nearest of 36 or 72
3398 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3400 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3403 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3408 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3409 else if (size[0] <= 32)
3410 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3412 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3414 VectorCopy(inmins, outmins);
3415 VectorAdd(inmins, hull->clip_size, outmaxs);
3418 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3423 float dist, modelyawradius, modelradius;
3424 msurface_t *surface;
3425 int numshadowmeshtriangles;
3426 hullinfo_t hullinfo;
3427 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3428 model_brush_lightstyleinfo_t styleinfo[256];
3429 unsigned char *datapointer;
3431 mod->modeldatatypestring = "Q1BSP";
3433 mod->type = mod_brushq1;
3435 header = (dheader_t *)buffer;
3437 i = LittleLong(header->version);
3438 if (i != BSPVERSION && i != 30)
3439 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3440 mod->brush.ishlbsp = i == 30;
3442 // fill in hull info
3443 VectorClear (hullinfo.hullsizes[0][0]);
3444 VectorClear (hullinfo.hullsizes[0][1]);
3445 if (mod->brush.ishlbsp)
3447 mod->modeldatatypestring = "HLBSP";
3449 hullinfo.filehulls = 4;
3450 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3451 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3452 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3453 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3454 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3455 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3459 hullinfo.filehulls = 4;
3460 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3461 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3462 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3463 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3467 mod_base = (unsigned char*)buffer;
3468 for (i = 0; i < HEADER_LUMPS; i++)
3470 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3471 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3474 mod->soundfromcenter = true;
3475 mod->TraceBox = Mod_Q1BSP_TraceBox;
3476 mod->TraceLine = Mod_Q1BSP_TraceLine;
3477 mod->TracePoint = Mod_Q1BSP_TracePoint;
3478 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3479 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3480 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3481 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3482 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3483 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3484 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3485 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3486 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3487 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3488 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3489 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3490 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3491 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3492 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3493 mod->Draw = R_Q1BSP_Draw;
3494 mod->DrawDepth = R_Q1BSP_DrawDepth;
3495 mod->DrawDebug = R_Q1BSP_DrawDebug;
3496 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3497 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3498 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3499 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3500 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3501 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3502 mod->DrawLight = R_Q1BSP_DrawLight;
3506 mod->brush.qw_md4sum = 0;
3507 mod->brush.qw_md4sum2 = 0;
3508 for (i = 0;i < HEADER_LUMPS;i++)
3511 if (i == LUMP_ENTITIES)
3513 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3514 mod->brush.qw_md4sum ^= LittleLong(temp);
3515 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3517 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3518 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3521 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3522 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3523 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3524 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3525 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3526 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3527 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3528 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3529 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3530 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3531 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3532 // load submodels before leafs because they contain the number of vis leafs
3533 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3534 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3535 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3536 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3538 // check if the map supports transparent water rendering
3539 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3541 if (mod->brushq1.data_compressedpvs)
3542 Mem_Free(mod->brushq1.data_compressedpvs);
3543 mod->brushq1.data_compressedpvs = NULL;
3544 mod->brushq1.num_compressedpvs = 0;
3546 Mod_Q1BSP_MakeHull0();
3547 Mod_Q1BSP_MakePortals();
3549 mod->numframes = 2; // regular and alternate animation
3552 // make a single combined shadow mesh to allow optimized shadow volume creation
3553 numshadowmeshtriangles = 0;
3554 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3556 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3557 numshadowmeshtriangles += surface->num_triangles;
3559 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3560 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3561 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, loadmodel->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
3562 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true, false);
3563 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
3565 if (loadmodel->brush.numsubmodels)
3566 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3568 // LordHavoc: to clear the fog around the original quake submodel code, I
3570 // first of all, some background info on the submodels:
3571 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3572 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3573 // now the weird for loop itself:
3574 // the loop functions in an odd way, on each iteration it sets up the
3575 // current 'mod' model (which despite the confusing code IS the model of
3576 // the number i), at the end of the loop it duplicates the model to become
3577 // the next submodel, and loops back to set up the new submodel.
3579 // LordHavoc: now the explanation of my sane way (which works identically):
3580 // set up the world model, then on each submodel copy from the world model
3581 // and set up the submodel with the respective model info.
3582 totalstylesurfaces = 0;
3584 for (i = 0;i < mod->brush.numsubmodels;i++)
3586 memset(stylecounts, 0, sizeof(stylecounts));
3587 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3589 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3590 for (j = 0;j < MAXLIGHTMAPS;j++)
3591 stylecounts[surface->lightmapinfo->styles[j]]++;
3593 for (k = 0;k < 255;k++)
3597 totalstylesurfaces += stylecounts[k];
3600 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3601 for (i = 0;i < mod->brush.numsubmodels;i++)
3603 // LordHavoc: this code was originally at the end of this loop, but
3604 // has been transformed to something more readable at the start here.
3609 // duplicate the basic information
3610 dpsnprintf(name, sizeof(name), "*%i", i);
3611 mod = Mod_FindName(name, loadmodel->name);
3612 // copy the base model to this one
3614 // rename the clone back to its proper name
3615 strlcpy(mod->name, name, sizeof(mod->name));
3616 mod->brush.parentmodel = loadmodel;
3617 // textures and memory belong to the main model
3618 mod->texturepool = NULL;
3619 mod->mempool = NULL;
3620 mod->brush.GetPVS = NULL;
3621 mod->brush.FatPVS = NULL;
3622 mod->brush.BoxTouchingPVS = NULL;
3623 mod->brush.BoxTouchingLeafPVS = NULL;
3624 mod->brush.BoxTouchingVisibleLeafs = NULL;
3625 mod->brush.FindBoxClusters = NULL;
3626 mod->brush.LightPoint = NULL;
3627 mod->brush.AmbientSoundLevelsForPoint = NULL;
3630 mod->brush.submodel = i;
3632 if (loadmodel->brush.submodels)
3633 loadmodel->brush.submodels[i] = mod;
3635 bm = &mod->brushq1.submodels[i];
3637 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3638 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3640 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3641 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3644 mod->firstmodelsurface = bm->firstface;
3645 mod->nummodelsurfaces = bm->numfaces;
3647 // set node/leaf parents for this submodel
3648 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3650 // make the model surface list (used by shadowing/lighting)
3651 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3652 Mod_MakeSortedSurfaces(mod);
3654 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3655 // (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)
3656 VectorCopy(bm->mins, mod->normalmins);
3657 VectorCopy(bm->maxs, mod->normalmaxs);
3658 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3659 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3660 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3661 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3662 modelradius = modelyawradius + modelradius * modelradius;
3663 modelyawradius = sqrt(modelyawradius);
3664 modelradius = sqrt(modelradius);
3665 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3666 mod->yawmins[2] = mod->normalmins[2];
3667 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3668 mod->yawmaxs[2] = mod->normalmaxs[2];
3669 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3670 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3671 mod->radius = modelradius;
3672 mod->radius2 = modelradius * modelradius;
3674 // this gets altered below if sky or water is used
3675 mod->DrawSky = NULL;
3676 mod->DrawAddWaterPlanes = NULL;
3678 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3679 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3680 if (mod->nummodelsurfaces)
3682 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3683 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3685 if (j < mod->nummodelsurfaces)
3686 mod->DrawSky = R_Q1BSP_DrawSky;
3688 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3689 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
3691 if (j < mod->nummodelsurfaces)
3692 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3694 // build lightstyle update chains
3695 // (used to rapidly mark lightmapupdateflags on many surfaces
3696 // when d_lightstylevalue changes)
3697 memset(stylecounts, 0, sizeof(stylecounts));
3698 for (k = 0;k < mod->nummodelsurfaces;k++)
3700 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3701 for (j = 0;j < MAXLIGHTMAPS;j++)
3702 stylecounts[surface->lightmapinfo->styles[j]]++;
3704 mod->brushq1.num_lightstyles = 0;
3705 for (k = 0;k < 255;k++)
3709 styleinfo[mod->brushq1.num_lightstyles].style = k;
3710 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3711 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3712 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3713 remapstyles[k] = mod->brushq1.num_lightstyles;
3714 mod->brushq1.num_lightstyles++;
3717 for (k = 0;k < mod->nummodelsurfaces;k++)
3719 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3720 for (j = 0;j < MAXLIGHTMAPS;j++)
3722 if (surface->lightmapinfo->styles[j] != 255)
3724 int r = remapstyles[surface->lightmapinfo->styles[j]];
3725 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3729 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3730 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3734 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3735 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3737 //mod->brushq1.num_visleafs = bm->visleafs;
3739 if (mod_q1bsp_polygoncollisions.integer)
3741 Mod_MakeCollisionBIH(mod, true);
3742 // point traces and contents checks still use the bsp tree
3743 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3744 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3747 // generate VBOs and other shared data before cloning submodels
3751 Mod_Q1BSP_LoadMapBrushes();
3752 //Mod_Q1BSP_ProcessLightList();
3756 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);
3759 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3763 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3770 in = (void *)(mod_base + l->fileofs);
3771 if (l->filelen % sizeof(*in))
3772 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3773 count = l->filelen / sizeof(*in);
3774 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3777 loadmodel->num = count;
3779 for (i = 0;i < count;i++, in++, out++)
3785 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3792 in = (void *)(mod_base + l->fileofs);
3793 if (l->filelen % sizeof(*in))
3794 Host_Error("Mod_Q2BSP_LoadVertices: 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_LoadVisibility(lump_t *l)
3814 in = (void *)(mod_base + l->fileofs);
3815 if (l->filelen % sizeof(*in))
3816 Host_Error("Mod_Q2BSP_LoadVisibility: 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_LoadNodes(lump_t *l)
3836 in = (void *)(mod_base + l->fileofs);
3837 if (l->filelen % sizeof(*in))
3838 Host_Error("Mod_Q2BSP_LoadNodes: 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_LoadTexInfo(lump_t *l)
3858 in = (void *)(mod_base + l->fileofs);
3859 if (l->filelen % sizeof(*in))
3860 Host_Error("Mod_Q2BSP_LoadTexInfo: 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_LoadFaces(lump_t *l)
3880 in = (void *)(mod_base + l->fileofs);
3881 if (l->filelen % sizeof(*in))
3882 Host_Error("Mod_Q2BSP_LoadFaces: 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_LoadLighting(lump_t *l)
3902 in = (void *)(mod_base + l->fileofs);
3903 if (l->filelen % sizeof(*in))
3904 Host_Error("Mod_Q2BSP_LoadLighting: 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_LoadLeafs(lump_t *l)
3924 in = (void *)(mod_base + l->fileofs);
3925 if (l->filelen % sizeof(*in))
3926 Host_Error("Mod_Q2BSP_LoadLeafs: 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_LoadLeafFaces(lump_t *l)
3946 in = (void *)(mod_base + l->fileofs);
3947 if (l->filelen % sizeof(*in))
3948 Host_Error("Mod_Q2BSP_LoadLeafFaces: 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_LoadLeafBrushes(lump_t *l)
3968 in = (void *)(mod_base + l->fileofs);
3969 if (l->filelen % sizeof(*in))
3970 Host_Error("Mod_Q2BSP_LoadLeafBrushes: 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_LoadEdges(lump_t *l)
3990 in = (void *)(mod_base + l->fileofs);
3991 if (l->filelen % sizeof(*in))
3992 Host_Error("Mod_Q2BSP_LoadEdges: 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_LoadSurfEdges(lump_t *l)
4012 in = (void *)(mod_base + l->fileofs);
4013 if (l->filelen % sizeof(*in))
4014 Host_Error("Mod_Q2BSP_LoadSurfEdges: 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_LoadBrushes(lump_t *l)
4034 in = (void *)(mod_base + l->fileofs);
4035 if (l->filelen % sizeof(*in))
4036 Host_Error("Mod_Q2BSP_LoadBrushes: 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_LoadBrushSides(lump_t *l)
4056 in = (void *)(mod_base + l->fileofs);
4057 if (l->filelen % sizeof(*in))
4058 Host_Error("Mod_Q2BSP_LoadBrushSides: 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_LoadAreas(lump_t *l)
4078 in = (void *)(mod_base + l->fileofs);
4079 if (l->filelen % sizeof(*in))
4080 Host_Error("Mod_Q2BSP_LoadAreas: 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_LoadAreaPortals(lump_t *l)
4100 in = (void *)(mod_base + l->fileofs);
4101 if (l->filelen % sizeof(*in))
4102 Host_Error("Mod_Q2BSP_LoadAreaPortals: 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_LoadModels(lump_t *l)
4122 in = (void *)(mod_base + l->fileofs);
4123 if (l->filelen % sizeof(*in))
4124 Host_Error("Mod_Q2BSP_LoadModels: 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 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4140 q2dheader_t *header;
4142 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4144 mod->modeldatatypestring = "Q2BSP";
4146 mod->type = mod_brushq2;
4148 header = (q2dheader_t *)buffer;
4150 i = LittleLong(header->version);
4151 if (i != Q2BSPVERSION)
4152 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4154 mod_base = (unsigned char *)header;
4156 // swap all the lumps
4157 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4158 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4160 mod->brush.qw_md4sum = 0;
4161 mod->brush.qw_md4sum2 = 0;
4162 for (i = 0;i < Q2HEADER_LUMPS;i++)
4164 if (i == Q2LUMP_ENTITIES)
4166 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4167 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4169 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4172 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4173 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4174 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4175 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4176 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4177 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4178 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4179 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4180 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4181 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4182 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4183 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4184 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4185 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4186 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4187 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4188 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4189 // LordHavoc: must go last because this makes the submodels
4190 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4193 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4194 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4196 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4199 char key[128], value[MAX_INPUTLINE];
4201 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4202 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4203 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4206 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4207 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4208 loadmodel->brush.entities[l->filelen] = 0;
4209 data = loadmodel->brush.entities;
4210 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4211 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4212 loadmodel->brushq3.deluxemapping = false;
4213 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4217 if (!COM_ParseToken_Simple(&data, false, false))
4219 if (com_token[0] == '}')
4220 break; // end of worldspawn
4221 if (com_token[0] == '_')
4222 strlcpy(key, com_token + 1, sizeof(key));
4224 strlcpy(key, com_token, sizeof(key));
4225 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4226 key[strlen(key)-1] = 0;
4227 if (!COM_ParseToken_Simple(&data, false, false))
4229 strlcpy(value, com_token, sizeof(value));
4230 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4232 #if _MSC_VER >= 1400
4233 #define sscanf sscanf_s
4236 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4237 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4239 VectorSet(v, 64, 64, 128);
4240 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4241 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]);
4242 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4243 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4246 else if (!strcmp("deluxeMaps", key))
4248 if (!strcmp(com_token, "1"))
4250 loadmodel->brushq3.deluxemapping = true;
4251 loadmodel->brushq3.deluxemapping_modelspace = true;
4253 else if (!strcmp(com_token, "2"))
4255 loadmodel->brushq3.deluxemapping = true;
4256 loadmodel->brushq3.deluxemapping_modelspace = false;
4263 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4269 in = (q3dtexture_t *)(mod_base + l->fileofs);
4270 if (l->filelen % sizeof(*in))
4271 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4272 count = l->filelen / sizeof(*in);
4273 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4275 loadmodel->data_textures = out;
4276 loadmodel->num_textures = count;
4277 loadmodel->num_texturesperskin = loadmodel->num_textures;
4279 for (i = 0;i < count;i++)
4281 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4282 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4283 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4284 if (cls.state != ca_dedicated)
4286 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS);
4287 // restore the surfaceflags and supercontents
4288 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4289 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4294 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4300 in = (q3dplane_t *)(mod_base + l->fileofs);
4301 if (l->filelen % sizeof(*in))
4302 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4303 count = l->filelen / sizeof(*in);
4304 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4306 loadmodel->brush.data_planes = out;
4307 loadmodel->brush.num_planes = count;
4309 for (i = 0;i < count;i++, in++, out++)
4311 out->normal[0] = LittleFloat(in->normal[0]);
4312 out->normal[1] = LittleFloat(in->normal[1]);
4313 out->normal[2] = LittleFloat(in->normal[2]);
4314 out->dist = LittleFloat(in->dist);
4319 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4322 q3mbrushside_t *out;
4325 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4326 if (l->filelen % sizeof(*in))
4327 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4328 count = l->filelen / sizeof(*in);
4329 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4331 loadmodel->brush.data_brushsides = out;
4332 loadmodel->brush.num_brushsides = count;
4334 for (i = 0;i < count;i++, in++, out++)
4336 n = LittleLong(in->planeindex);
4337 if (n < 0 || n >= loadmodel->brush.num_planes)
4338 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4339 out->plane = loadmodel->brush.data_planes + n;
4340 n = LittleLong(in->textureindex);
4341 if (n < 0 || n >= loadmodel->num_textures)
4342 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4343 out->texture = loadmodel->data_textures + n;
4347 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4349 q3dbrushside_ig_t *in;
4350 q3mbrushside_t *out;
4353 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4354 if (l->filelen % sizeof(*in))
4355 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4356 count = l->filelen / sizeof(*in);
4357 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4359 loadmodel->brush.data_brushsides = out;
4360 loadmodel->brush.num_brushsides = count;
4362 for (i = 0;i < count;i++, in++, out++)
4364 n = LittleLong(in->planeindex);
4365 if (n < 0 || n >= loadmodel->brush.num_planes)
4366 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4367 out->plane = loadmodel->brush.data_planes + n;
4368 n = LittleLong(in->textureindex);
4369 if (n < 0 || n >= loadmodel->num_textures)
4370 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4371 out->texture = loadmodel->data_textures + n;
4375 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4379 int i, j, n, c, count, maxplanes, q3surfaceflags;
4380 colplanef_t *planes;
4382 in = (q3dbrush_t *)(mod_base + l->fileofs);
4383 if (l->filelen % sizeof(*in))
4384 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4385 count = l->filelen / sizeof(*in);
4386 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4388 loadmodel->brush.data_brushes = out;
4389 loadmodel->brush.num_brushes = count;
4394 for (i = 0;i < count;i++, in++, out++)
4396 n = LittleLong(in->firstbrushside);
4397 c = LittleLong(in->numbrushsides);
4398 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4399 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4400 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4401 out->numbrushsides = c;
4402 n = LittleLong(in->textureindex);
4403 if (n < 0 || n >= loadmodel->num_textures)
4404 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4405 out->texture = loadmodel->data_textures + n;
4407 // make a list of mplane_t structs to construct a colbrush from
4408 if (maxplanes < out->numbrushsides)
4410 maxplanes = out->numbrushsides;
4413 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4416 for (j = 0;j < out->numbrushsides;j++)
4418 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4419 planes[j].dist = out->firstbrushside[j].plane->dist;
4420 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4421 planes[j].texture = out->firstbrushside[j].texture;
4422 q3surfaceflags |= planes[j].q3surfaceflags;
4424 // make the colbrush from the planes
4425 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4427 // this whole loop can take a while (e.g. on redstarrepublic4)
4428 CL_KeepaliveMessage(false);
4434 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4440 in = (q3deffect_t *)(mod_base + l->fileofs);
4441 if (l->filelen % sizeof(*in))
4442 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4443 count = l->filelen / sizeof(*in);
4444 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4446 loadmodel->brushq3.data_effects = out;
4447 loadmodel->brushq3.num_effects = count;
4449 for (i = 0;i < count;i++, in++, out++)
4451 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4452 n = LittleLong(in->brushindex);
4453 if (n >= loadmodel->brush.num_brushes)
4455 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4458 out->brushindex = n;
4459 out->unknown = LittleLong(in->unknown);
4463 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4468 in = (q3dvertex_t *)(mod_base + l->fileofs);
4469 if (l->filelen % sizeof(*in))
4470 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4471 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4472 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4473 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4474 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4475 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4476 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4478 for (i = 0;i < count;i++, in++)
4480 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4481 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4482 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4483 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4484 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4485 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4486 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4487 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4488 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4489 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4490 // svector/tvector are calculated later in face loading
4491 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4492 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4493 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4494 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4498 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4504 in = (int *)(mod_base + l->fileofs);
4505 if (l->filelen % sizeof(int[3]))
4506 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4507 count = l->filelen / sizeof(*in);
4509 if(!loadmodel->brushq3.num_vertices)
4512 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4513 loadmodel->brushq3.num_triangles = 0;
4517 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4518 loadmodel->brushq3.num_triangles = count / 3;
4519 loadmodel->brushq3.data_element3i = out;
4521 for (i = 0;i < count;i++, in++, out++)
4523 *out = LittleLong(*in);
4524 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4526 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4532 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4534 q3dlightmap_t *input_pointer;
4535 int i, j, k, count, power, power2, endlightmap, mergewidth, mergeheight;
4538 unsigned char *convertedpixels;
4539 char mapname[MAX_QPATH];
4540 int size, bytesperpixel, rgbmap[3];
4542 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4544 // defaults for q3bsp
4551 loadmodel->brushq3.lightmapsize = 128;
4553 if (cls.state == ca_dedicated)
4556 if(mod_q3bsp_nolightmaps.integer)
4562 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4563 if (developer_loading.integer)
4564 Con_Printf("Using internal lightmaps\n");
4565 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4566 if (l->filelen % sizeof(*input_pointer))
4567 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4568 count = l->filelen / sizeof(*input_pointer);
4569 for(i = 0; i < count; ++i)
4570 inpixels[i] = input_pointer[i].rgb;
4574 // no internal lightmaps
4575 // try external lightmaps
4576 if (developer_loading.integer)
4577 Con_Printf("Using external lightmaps\n");
4578 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4579 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false);
4583 // using EXTERNAL lightmaps instead
4584 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4586 Mem_Free(inpixels[0]);
4587 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4597 for(count = 1; ; ++count)
4599 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false);
4600 if(!inpixels[count])
4601 break; // we got all of them
4602 if(image_width != size || image_height != size)
4604 Mem_Free(inpixels[count]);
4605 inpixels[count] = NULL;
4606 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);
4612 convertedpixels = (unsigned char *) Mem_Alloc(tempmempool, size*size*4);
4613 loadmodel->brushq3.lightmapsize = size;
4614 loadmodel->brushq3.num_originallightmaps = count;
4616 // now check the surfaces to see if any of them index an odd numbered
4617 // lightmap, if so this is not a deluxemapped bsp file
4619 // also check what lightmaps are actually used, because q3map2 sometimes
4620 // (always?) makes an unused one at the end, which
4621 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4622 // reason when only one lightmap is used, which can throw off the
4623 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4624 // to see if the second lightmap is blank, if so it is not deluxemapped.
4625 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4626 // in Mod_Q3BSP_LoadEntities was failed
4627 if (!loadmodel->brushq3.deluxemapping)
4629 loadmodel->brushq3.deluxemapping = !(count & 1);
4630 loadmodel->brushq3.deluxemapping_modelspace = true;
4632 if (loadmodel->brushq3.deluxemapping)
4634 int facecount = faceslump->filelen / sizeof(q3dface_t);
4635 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4636 for (i = 0;i < facecount;i++)
4638 j = LittleLong(faces[i].lightmapindex);
4641 endlightmap = max(endlightmap, j + 1);
4642 if ((j & 1) || j + 1 >= count)
4644 loadmodel->brushq3.deluxemapping = false;
4651 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4652 // reason when only one lightmap is used, which can throw off the
4653 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4654 // to see if the second lightmap is blank, if so it is not deluxemapped.
4656 // further research has shown q3map2 sometimes creates a deluxemap and two
4657 // blank lightmaps, which must be handled properly as well
4658 if (endlightmap == 1 && count > 1)
4661 for (i = 0;i < size*size;i++)
4663 if (c[bytesperpixel*i + rgbmap[0]])
4665 if (c[bytesperpixel*i + rgbmap[1]])
4667 if (c[bytesperpixel*i + rgbmap[2]])
4672 // all pixels in the unused lightmap were black...
4673 loadmodel->brushq3.deluxemapping = false;
4678 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4680 // figure out what the most reasonable merge power is within limits
4682 loadmodel->brushq3.num_lightmapmergepower = 0;
4684 for(i = 0; (128 << i) < size; ++i)
4686 // i is now 0 for 128, 1 for 256, etc
4688 for (power = 1;power + i <= mod_q3bsp_lightmapmergepower.integer && (size << power) <= (int)vid.maxtexturesize_2d && (1 << (power * 2)) < 4 * (count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)); power++)
4689 loadmodel->brushq3.num_lightmapmergepower = power;
4691 loadmodel->brushq3.num_lightmapmerge = 1 << loadmodel->brushq3.num_lightmapmergepower;
4693 loadmodel->brushq3.num_mergedlightmaps = ((count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) + (1 << (loadmodel->brushq3.num_lightmapmergepower * 2)) - 1) >> (loadmodel->brushq3.num_lightmapmergepower * 2);
4694 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4695 if (loadmodel->brushq3.deluxemapping)
4696 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4698 // allocate a texture pool if we need it
4699 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4700 loadmodel->texturepool = R_AllocTexturePool();
4702 power = loadmodel->brushq3.num_lightmapmergepower;
4704 for (i = 0;i < count;i++)
4706 // figure out which merged lightmap texture this fits into
4707 int lightmapindex = i >> (loadmodel->brushq3.deluxemapping + power2);
4708 for (k = 0;k < size*size;k++)
4710 convertedpixels[k*4+0] = inpixels[i][k*bytesperpixel+rgbmap[0]];
4711 convertedpixels[k*4+1] = inpixels[i][k*bytesperpixel+rgbmap[1]];
4712 convertedpixels[k*4+2] = inpixels[i][k*bytesperpixel+rgbmap[2]];
4713 convertedpixels[k*4+3] = 255;
4715 if (loadmodel->brushq3.num_lightmapmergepower > 0)
4717 // if the lightmap has not been allocated yet, create it
4718 if (!loadmodel->brushq3.data_lightmaps[lightmapindex])
4720 // create a lightmap only as large as necessary to hold the
4721 // remaining size*size blocks
4722 // if there are multiple merged lightmap textures then they will
4723 // all be full size except the last one which may be smaller
4724 // because it only needs to the remaining blocks, and it will often
4725 // be odd sizes like 2048x512 due to only being 25% full or so.
4726 j = (count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) - (lightmapindex << power2);
4727 for (mergewidth = 1;mergewidth < j && mergewidth < (1 << power);mergewidth *= 2)
4729 for (mergeheight = 1;mergewidth*mergeheight < j && mergeheight < (1 << power);mergeheight *= 2)
4731 if (developer_loading.integer)
4732 Con_Printf("lightmap merge texture #%i is %ix%i (%i of %i used)\n", lightmapindex, mergewidth*size, mergeheight*size, min(j, mergewidth*mergeheight), mergewidth*mergeheight);
4733 loadmodel->brushq3.data_lightmaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", lightmapindex), mergewidth * size, mergeheight * size, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : TEXF_ALLOWUPDATES), NULL);
4734 if (loadmodel->brushq3.data_deluxemaps)
4735 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%04i", lightmapindex), mergewidth * size, mergeheight * size, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : TEXF_ALLOWUPDATES), NULL);
4737 mergewidth = R_TextureWidth(loadmodel->brushq3.data_lightmaps[lightmapindex]) / size;
4738 mergeheight = R_TextureHeight(loadmodel->brushq3.data_lightmaps[lightmapindex]) / size;
4739 j = (i >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) & ((1 << power2) - 1);
4740 if (loadmodel->brushq3.deluxemapping && (i & 1))
4741 R_UpdateTexture(loadmodel->brushq3.data_deluxemaps[lightmapindex], convertedpixels, (j % mergewidth) * size, (j / mergewidth) * size, size, size);
4743 R_UpdateTexture(loadmodel->brushq3.data_lightmaps [lightmapindex], convertedpixels, (j % mergewidth) * size, (j / mergewidth) * size, size, size);
4747 // figure out which merged lightmap texture this fits into
4748 if (loadmodel->brushq3.deluxemapping && (i & 1))
4749 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%04i", lightmapindex), size, size, convertedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), NULL);
4751 loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", lightmapindex), size, size, convertedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), NULL);
4755 Mem_Free(convertedpixels);
4758 for(i = 0; i < count; ++i)
4759 Mem_Free(inpixels[i]);
4763 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
4768 *collisionstride = stride;
4771 cnt = (num_triangles + stride - 1) / stride;
4772 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
4773 for(j = 0; j < cnt; ++j)
4775 mins = &((*collisionbbox6f)[6 * j + 0]);
4776 maxs = &((*collisionbbox6f)[6 * j + 3]);
4777 for(k = 0; k < stride; ++k)
4779 tri = j * stride + k;
4780 if(tri >= num_triangles)
4782 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
4783 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
4784 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
4785 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
4786 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
4787 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
4788 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
4789 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
4790 if(vert[0] < mins[0]) mins[0] = vert[0];
4791 if(vert[1] < mins[1]) mins[1] = vert[1];
4792 if(vert[2] < mins[2]) mins[2] = vert[2];
4793 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4794 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4795 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4796 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
4797 if(vert[0] < mins[0]) mins[0] = vert[0];
4798 if(vert[1] < mins[1]) mins[1] = vert[1];
4799 if(vert[2] < mins[2]) mins[2] = vert[2];
4800 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4801 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4802 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4807 *collisionbbox6f = NULL;
4810 typedef struct patchtess_s
4814 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
4817 float *originalvertex3f;
4820 #define PATCHTESS_SAME_LODGROUP(a,b) \
4822 (a).lodgroup[0] == (b).lodgroup[0] && \
4823 (a).lodgroup[1] == (b).lodgroup[1] && \
4824 (a).lodgroup[2] == (b).lodgroup[2] && \
4825 (a).lodgroup[3] == (b).lodgroup[3] && \
4826 (a).lodgroup[4] == (b).lodgroup[4] && \
4827 (a).lodgroup[5] == (b).lodgroup[5] \
4830 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4832 q3dface_t *in, *oldin;
4833 msurface_t *out, *oldout;
4834 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;
4835 float lightmaptcbase[2], lightmaptcscale[2];
4836 //int *originalelement3i;
4837 //int *originalneighbor3i;
4838 float *originalvertex3f;
4839 //float *originalsvector3f;
4840 //float *originaltvector3f;
4841 float *originalnormal3f;
4842 float *originalcolor4f;
4843 float *originaltexcoordtexture2f;
4844 float *originaltexcoordlightmap2f;
4845 float *surfacecollisionvertex3f;
4846 int *surfacecollisionelement3i;
4848 patchtess_t *patchtess = NULL;
4849 int patchtesscount = 0;
4852 in = (q3dface_t *)(mod_base + l->fileofs);
4853 if (l->filelen % sizeof(*in))
4854 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4855 count = l->filelen / sizeof(*in);
4856 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4858 loadmodel->data_surfaces = out;
4859 loadmodel->num_surfaces = count;
4862 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
4870 for (;i < count;i++, in++, out++)
4872 // check face type first
4873 type = LittleLong(in->type);
4874 if (type != Q3FACETYPE_FLAT
4875 && type != Q3FACETYPE_PATCH
4876 && type != Q3FACETYPE_MESH
4877 && type != Q3FACETYPE_FLARE)
4879 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4883 n = LittleLong(in->textureindex);
4884 if (n < 0 || n >= loadmodel->num_textures)
4886 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4889 out->texture = loadmodel->data_textures + n;
4890 n = LittleLong(in->effectindex);
4891 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4893 if (developer_extra.integer)
4894 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4900 out->effect = loadmodel->brushq3.data_effects + n;
4902 if (cls.state != ca_dedicated)
4904 out->lightmaptexture = NULL;
4905 out->deluxemaptexture = r_texture_blanknormalmap;
4906 n = LittleLong(in->lightmapindex);
4909 else if (n >= loadmodel->brushq3.num_originallightmaps)
4911 if(loadmodel->brushq3.num_originallightmaps != 0)
4912 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
4917 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> (loadmodel->brushq3.num_lightmapmergepower * 2 + loadmodel->brushq3.deluxemapping)];
4918 if (loadmodel->brushq3.deluxemapping)
4919 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> (loadmodel->brushq3.num_lightmapmergepower * 2 + loadmodel->brushq3.deluxemapping)];
4923 firstvertex = LittleLong(in->firstvertex);
4924 numvertices = LittleLong(in->numvertices);
4925 firstelement = LittleLong(in->firstelement);
4926 numtriangles = LittleLong(in->numelements) / 3;
4927 if (numtriangles * 3 != LittleLong(in->numelements))
4929 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));
4932 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4934 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);
4937 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4939 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);
4944 case Q3FACETYPE_FLAT:
4945 case Q3FACETYPE_MESH:
4946 // no processing necessary
4948 case Q3FACETYPE_PATCH:
4949 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4950 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4951 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))
4953 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4956 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4958 // convert patch to Q3FACETYPE_MESH
4959 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4960 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4961 // bound to user settings
4962 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4963 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4964 // bound to sanity settings
4965 xtess = bound(0, xtess, 1024);
4966 ytess = bound(0, ytess, 1024);
4968 // lower quality collision patches! Same procedure as before, but different cvars
4969 // convert patch to Q3FACETYPE_MESH
4970 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4971 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4972 // bound to user settings
4973 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
4974 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
4975 // bound to sanity settings
4976 cxtess = bound(0, cxtess, 1024);
4977 cytess = bound(0, cytess, 1024);
4979 // store it for the LOD grouping step
4980 patchtess[patchtesscount].info.xsize = patchsize[0];
4981 patchtess[patchtesscount].info.ysize = patchsize[1];
4982 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
4983 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
4984 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
4985 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
4987 patchtess[patchtesscount].surface_id = i;
4988 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
4989 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
4990 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
4991 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
4992 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
4993 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
4994 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
4997 case Q3FACETYPE_FLARE:
4998 if (developer_extra.integer)
4999 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5003 out->num_vertices = numvertices;
5004 out->num_triangles = numtriangles;
5005 meshvertices += out->num_vertices;
5006 meshtriangles += out->num_triangles;
5009 // Fix patches tesselations so that they make no seams
5013 for(i = 0; i < patchtesscount; ++i)
5015 for(j = i+1; j < patchtesscount; ++j)
5017 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5020 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5027 // Calculate resulting number of triangles
5028 collisionvertices = 0;
5029 collisiontriangles = 0;
5030 for(i = 0; i < patchtesscount; ++i)
5032 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5033 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5034 numvertices = finalwidth * finalheight;
5035 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5037 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5038 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5039 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5040 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5042 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5043 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5044 numvertices = finalwidth * finalheight;
5045 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5047 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5048 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5049 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5050 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5056 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5057 if (collisiontriangles)
5059 loadmodel->brush.data_collisionvertex3f = Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5060 loadmodel->brush.data_collisionelement3i = Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5064 collisionvertices = 0;
5065 collisiontriangles = 0;
5066 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5068 if (out->num_vertices < 3 || out->num_triangles < 1)
5071 type = LittleLong(in->type);
5072 firstvertex = LittleLong(in->firstvertex);
5073 firstelement = LittleLong(in->firstelement);
5074 out->num_firstvertex = meshvertices;
5075 out->num_firsttriangle = meshtriangles;
5076 out->num_firstcollisiontriangle = collisiontriangles;
5079 case Q3FACETYPE_FLAT:
5080 case Q3FACETYPE_MESH:
5081 // no processing necessary, except for lightmap merging
5082 for (j = 0;j < out->num_vertices;j++)
5084 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5085 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5086 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5087 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5088 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5089 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5090 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5091 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5092 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5093 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5094 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5095 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5096 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5097 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5099 for (j = 0;j < out->num_triangles*3;j++)
5100 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5102 case Q3FACETYPE_PATCH:
5103 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5104 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5105 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5106 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5107 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5108 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5109 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5111 xtess = ytess = cxtess = cytess = -1;
5112 for(j = 0; j < patchtesscount; ++j)
5113 if(patchtess[j].surface_id == i)
5115 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5116 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5117 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5118 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5123 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5124 xtess = ytess = cxtess = cytess = 0;
5127 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5128 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5129 finalvertices = finalwidth * finalheight;
5130 oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5131 type = Q3FACETYPE_MESH;
5132 // generate geometry
5133 // (note: normals are skipped because they get recalculated)
5134 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5135 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5136 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5137 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5138 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5139 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5141 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);
5143 if (developer_extra.integer)
5145 if (out->num_triangles < finaltriangles)
5146 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);
5148 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);
5150 // q3map does not put in collision brushes for curves... ugh
5151 // build the lower quality collision geometry
5152 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5153 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5154 finalvertices = finalwidth * finalheight;
5155 oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5157 // legacy collision geometry implementation
5158 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5159 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5160 out->num_collisionvertices = finalvertices;
5161 out->num_collisiontriangles = finaltriangles;
5162 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5163 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5165 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5166 Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5168 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5170 // now optimize the collision mesh by finding triangle bboxes...
5171 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5172 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);
5174 // store collision geometry for BIH collision tree
5175 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5176 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5177 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5178 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5179 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5181 // remove this once the legacy code is removed
5183 int nc = out->num_collisiontriangles;
5185 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5187 if(nc != out->num_collisiontriangles)
5189 Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5194 if (developer_extra.integer)
5195 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);
5197 collisionvertices += finalvertices;
5198 collisiontriangles += out->num_collisiontriangles;
5203 meshvertices += out->num_vertices;
5204 meshtriangles += out->num_triangles;
5205 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5206 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)
5208 if (invalidelements)
5210 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);
5211 for (j = 0;j < out->num_triangles * 3;j++)
5213 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5214 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)
5215 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5219 // calculate a bounding box
5220 VectorClear(out->mins);
5221 VectorClear(out->maxs);
5222 if (out->num_vertices)
5224 if (cls.state != ca_dedicated && out->lightmaptexture)
5226 // figure out which part of the merged lightmap this fits into
5227 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5228 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5229 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5230 lightmapindex &= mergewidth * mergeheight - 1;
5231 lightmaptcscale[0] = 1.0f / mergewidth;
5232 lightmaptcscale[1] = 1.0f / mergeheight;
5233 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5234 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5235 // modify the lightmap texcoords to match this region of the merged lightmap
5236 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5238 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5239 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5242 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5243 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5244 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5246 out->mins[0] = min(out->mins[0], v[0]);
5247 out->maxs[0] = max(out->maxs[0], v[0]);
5248 out->mins[1] = min(out->mins[1], v[1]);
5249 out->maxs[1] = max(out->maxs[1], v[1]);
5250 out->mins[2] = min(out->mins[2], v[2]);
5251 out->maxs[2] = max(out->maxs[2], v[2]);
5253 out->mins[0] -= 1.0f;
5254 out->mins[1] -= 1.0f;
5255 out->mins[2] -= 1.0f;
5256 out->maxs[0] += 1.0f;
5257 out->maxs[1] += 1.0f;
5258 out->maxs[2] += 1.0f;
5260 // set lightmap styles for consistency with q1bsp
5261 //out->lightmapinfo->styles[0] = 0;
5262 //out->lightmapinfo->styles[1] = 255;
5263 //out->lightmapinfo->styles[2] = 255;
5264 //out->lightmapinfo->styles[3] = 255;
5269 for (;i < count;i++, out++)
5271 if(out->num_vertices && out->num_triangles)
5273 if(out->num_vertices == 0)
5274 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no vertices, ignoring\n", i);
5275 if(out->num_triangles == 0)
5276 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no triangles, ignoring\n", i);
5279 // for per pixel lighting
5280 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);
5282 // generate ushort elements array if possible
5283 if (loadmodel->surfmesh.data_element3s)
5284 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5285 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5287 // free the no longer needed vertex data
5288 loadmodel->brushq3.num_vertices = 0;
5289 if (loadmodel->brushq3.data_vertex3f)
5290 Mem_Free(loadmodel->brushq3.data_vertex3f);
5291 loadmodel->brushq3.data_vertex3f = NULL;
5292 loadmodel->brushq3.data_normal3f = NULL;
5293 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5294 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5295 loadmodel->brushq3.data_color4f = NULL;
5296 // free the no longer needed triangle data
5297 loadmodel->brushq3.num_triangles = 0;
5298 if (loadmodel->brushq3.data_element3i)
5299 Mem_Free(loadmodel->brushq3.data_element3i);
5300 loadmodel->brushq3.data_element3i = NULL;
5303 Mem_Free(patchtess);
5306 static void Mod_Q3BSP_LoadModels(lump_t *l)
5310 int i, j, n, c, count;
5312 in = (q3dmodel_t *)(mod_base + l->fileofs);
5313 if (l->filelen % sizeof(*in))
5314 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5315 count = l->filelen / sizeof(*in);
5316 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5318 loadmodel->brushq3.data_models = out;
5319 loadmodel->brushq3.num_models = count;
5321 for (i = 0;i < count;i++, in++, out++)
5323 for (j = 0;j < 3;j++)
5325 out->mins[j] = LittleFloat(in->mins[j]);
5326 out->maxs[j] = LittleFloat(in->maxs[j]);
5328 n = LittleLong(in->firstface);
5329 c = LittleLong(in->numfaces);
5330 if (n < 0 || n + c > loadmodel->num_surfaces)
5331 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5334 n = LittleLong(in->firstbrush);
5335 c = LittleLong(in->numbrushes);
5336 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5337 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5338 out->firstbrush = n;
5339 out->numbrushes = c;
5343 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5349 in = (int *)(mod_base + l->fileofs);
5350 if (l->filelen % sizeof(*in))
5351 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5352 count = l->filelen / sizeof(*in);
5353 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5355 loadmodel->brush.data_leafbrushes = out;
5356 loadmodel->brush.num_leafbrushes = count;
5358 for (i = 0;i < count;i++, in++, out++)
5360 n = LittleLong(*in);
5361 if (n < 0 || n >= loadmodel->brush.num_brushes)
5362 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5367 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5373 in = (int *)(mod_base + l->fileofs);
5374 if (l->filelen % sizeof(*in))
5375 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5376 count = l->filelen / sizeof(*in);
5377 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5379 loadmodel->brush.data_leafsurfaces = out;
5380 loadmodel->brush.num_leafsurfaces = count;
5382 for (i = 0;i < count;i++, in++, out++)
5384 n = LittleLong(*in);
5385 if (n < 0 || n >= loadmodel->num_surfaces)
5386 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5391 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5395 int i, j, n, c, count;
5397 in = (q3dleaf_t *)(mod_base + l->fileofs);
5398 if (l->filelen % sizeof(*in))
5399 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5400 count = l->filelen / sizeof(*in);
5401 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5403 loadmodel->brush.data_leafs = out;
5404 loadmodel->brush.num_leafs = count;
5406 for (i = 0;i < count;i++, in++, out++)
5410 out->clusterindex = LittleLong(in->clusterindex);
5411 out->areaindex = LittleLong(in->areaindex);
5412 for (j = 0;j < 3;j++)
5414 // yes the mins/maxs are ints
5415 out->mins[j] = LittleLong(in->mins[j]) - 1;
5416 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5418 n = LittleLong(in->firstleafface);
5419 c = LittleLong(in->numleaffaces);
5420 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5421 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5422 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5423 out->numleafsurfaces = c;
5424 n = LittleLong(in->firstleafbrush);
5425 c = LittleLong(in->numleafbrushes);
5426 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5427 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5428 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5429 out->numleafbrushes = c;
5433 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5439 in = (q3dnode_t *)(mod_base + l->fileofs);
5440 if (l->filelen % sizeof(*in))
5441 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5442 count = l->filelen / sizeof(*in);
5443 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5445 loadmodel->brush.data_nodes = out;
5446 loadmodel->brush.num_nodes = count;
5448 for (i = 0;i < count;i++, in++, out++)
5451 n = LittleLong(in->planeindex);
5452 if (n < 0 || n >= loadmodel->brush.num_planes)
5453 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5454 out->plane = loadmodel->brush.data_planes + n;
5455 for (j = 0;j < 2;j++)
5457 n = LittleLong(in->childrenindex[j]);
5460 if (n >= loadmodel->brush.num_nodes)
5461 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5462 out->children[j] = loadmodel->brush.data_nodes + n;
5467 if (n >= loadmodel->brush.num_leafs)
5468 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5469 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5472 for (j = 0;j < 3;j++)
5474 // yes the mins/maxs are ints
5475 out->mins[j] = LittleLong(in->mins[j]) - 1;
5476 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5480 // set the parent pointers
5481 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5484 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5487 q3dlightgrid_t *out;
5490 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5491 if (l->filelen % sizeof(*in))
5492 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5493 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5494 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5495 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5496 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5497 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5498 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5499 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5500 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5501 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5502 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5503 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5504 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5505 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5506 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]);
5507 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]);
5509 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5512 if (l->filelen < count * (int)sizeof(*in))
5514 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]);
5515 return; // ignore the grid if we cannot understand it
5517 if (l->filelen != count * (int)sizeof(*in))
5518 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5519 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5520 loadmodel->brushq3.data_lightgrid = out;
5521 loadmodel->brushq3.num_lightgrid = count;
5522 // no swapping or validation necessary
5523 memcpy(out, in, count * (int)sizeof(*out));
5527 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5532 if (l->filelen == 0)
5535 // unvised maps often have cluster indices even without pvs, so check
5536 // leafs to find real number of clusters
5537 loadmodel->brush.num_pvsclusters = 1;
5538 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5539 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5542 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5543 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5544 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5545 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5549 in = (q3dpvs_t *)(mod_base + l->fileofs);
5551 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5553 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5554 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5555 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5556 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5557 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5558 if (l->filelen < totalchains + (int)sizeof(*in))
5559 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);
5561 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5562 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5565 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5567 int i, j, k, index[3];
5568 float transformed[3], blend1, blend2, blend, stylescale;
5569 q3dlightgrid_t *a, *s;
5571 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5572 stylescale = r_refdef.scene.rtlightstylevalue[0];
5574 if (!model->brushq3.num_lightgrid)
5576 ambientcolor[0] = stylescale;
5577 ambientcolor[1] = stylescale;
5578 ambientcolor[2] = stylescale;
5582 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5583 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5584 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5585 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5586 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5587 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5588 index[0] = (int)floor(transformed[0]);
5589 index[1] = (int)floor(transformed[1]);
5590 index[2] = (int)floor(transformed[2]);
5591 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5593 // now lerp the values
5594 VectorClear(diffusenormal);
5595 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5596 for (k = 0;k < 2;k++)
5598 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5599 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5601 for (j = 0;j < 2;j++)
5603 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5604 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5606 for (i = 0;i < 2;i++)
5608 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5609 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5611 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5612 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5613 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5614 // this uses the mod_md3_sin table because the values are
5615 // already in the 0-255 range, the 64+ bias fetches a cosine
5616 // instead of a sine value
5617 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5618 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5619 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5620 //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)));
5625 // normalize the light direction before turning
5626 VectorNormalize(diffusenormal);
5627 //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]);
5630 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5633 double midf, mid[3];
5639 // find the point distances
5640 mplane_t *plane = node->plane;
5641 if (plane->type < 3)
5643 t1 = p1[plane->type] - plane->dist;
5644 t2 = p2[plane->type] - plane->dist;
5648 t1 = DotProduct (plane->normal, p1) - plane->dist;
5649 t2 = DotProduct (plane->normal, p2) - plane->dist;
5656 node = node->children[1];
5665 node = node->children[0];
5671 midf = t1 / (t1 - t2);
5672 VectorLerp(p1, midf, p2, mid);
5674 // recurse both sides, front side first
5675 // return 2 if empty is followed by solid (hit something)
5676 // do not return 2 if both are solid or both empty,
5677 // or if start is solid and end is empty
5678 // as these degenerate cases usually indicate the eye is in solid and
5679 // should see the target point anyway
5680 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5683 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5688 return ((mleaf_t *)node)->clusterindex < 0;
5691 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5693 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5696 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5697 return trace.fraction == 1;
5701 double tracestart[3], traceend[3];
5702 VectorCopy(start, tracestart);
5703 VectorCopy(end, traceend);
5704 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5708 static void Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t point)
5710 const bih_leaf_t *leaf;
5711 const bih_node_t *node;
5712 const colbrushf_t *brush;
5714 while (nodenum >= 0)
5716 node = model->collision_bih.nodes + nodenum;
5717 axis = node->type - BIH_SPLITX;
5718 if (point[axis] <= node->backmax)
5720 if (point[axis] >= node->frontmin)
5721 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, node->front, point);
5722 nodenum = node->back;
5724 else if (point[axis] >= node->frontmin)
5725 nodenum = node->front;
5726 else // no overlap with either child? just return
5729 if (!model->collision_bih.leafs)
5731 leaf = model->collision_bih.leafs + (-1-nodenum);
5735 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5736 Collision_TracePointBrushFloat(trace, point, brush);
5738 case BIH_COLLISIONTRIANGLE:
5739 // collision triangle - skipped because they have no volume
5741 case BIH_RENDERTRIANGLE:
5742 // render triangle - skipped because they have no volume
5747 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)
5749 const bih_leaf_t *leaf;
5750 const bih_node_t *node;
5751 const colbrushf_t *brush;
5753 const texture_t *texture;
5768 segmentmins[0] = min(start[0], end[0]);
5769 segmentmins[1] = min(start[1], end[1]);
5770 segmentmins[2] = min(start[2], end[2]);
5771 segmentmaxs[0] = max(start[0], end[0]);
5772 segmentmaxs[1] = max(start[1], end[1]);
5773 segmentmaxs[2] = max(start[2], end[2]);
5774 while (nodenum >= 0)
5776 node = model->collision_bih.nodes + nodenum;
5778 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
5781 axis = node->type - BIH_SPLITX;
5783 if (segmentmins[axis] <= node->backmax)
5785 if (segmentmaxs[axis] >= node->frontmin)
5786 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5787 nodenum = node->back;
5789 else if (segmentmaxs[axis] >= node->frontmin)
5790 nodenum = node->front;
5792 return; // trace falls between children
5794 frontdist1 = start[axis] - node->frontmin;
5795 frontdist2 = end[axis] - node->frontmin;
5796 backdist1 = start[axis] - node->backmax;
5797 backdist2 = end[axis] - node->backmax;
5810 if ((sideflags & 3) != 3)
5811 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5812 nodenum = node->back;
5814 else if ((sideflags & 3) != 3)
5815 nodenum = node->front;
5817 return; // trace falls between children
5822 // start end START END
5823 nodenum = node->front;
5826 // START end START END
5828 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5829 VectorLerp(start, frontfrac, end, clipped[0]);
5831 segmentmins[0] = min(start[0], end[0]);
5832 segmentmins[1] = min(start[1], end[1]);
5833 segmentmins[2] = min(start[2], end[2]);
5834 segmentmaxs[0] = max(start[0], end[0]);
5835 segmentmaxs[1] = max(start[1], end[1]);
5836 segmentmaxs[2] = max(start[2], end[2]);
5838 nodenum = node->front;
5842 // start END START END
5843 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5844 VectorLerp(start, frontfrac, end, clipped[0]);
5846 segmentmins[0] = min(start[0], end[0]);
5847 segmentmins[1] = min(start[1], end[1]);
5848 segmentmins[2] = min(start[2], end[2]);
5849 segmentmaxs[0] = max(start[0], end[0]);
5850 segmentmaxs[1] = max(start[1], end[1]);
5851 segmentmaxs[2] = max(start[2], end[2]);
5853 nodenum = node->front;
5856 // START END START END
5857 return; // line falls in gap between children
5859 // start end start END
5860 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5862 backfrac = backdist1 / (backdist1 - backdist2);
5863 VectorLerp(start, backfrac, end, clipped[0]);
5865 segmentmins[0] = min(start[0], end[0]);
5866 segmentmins[1] = min(start[1], end[1]);
5867 segmentmins[2] = min(start[2], end[2]);
5868 segmentmaxs[0] = max(start[0], end[0]);
5869 segmentmaxs[1] = max(start[1], end[1]);
5870 segmentmaxs[2] = max(start[2], end[2]);
5872 nodenum = node->back;
5875 // START end start END
5877 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5878 VectorLerp(start, frontfrac, end, clipped[1]);
5879 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5880 backfrac = backdist1 / (backdist1 - backdist2);
5881 VectorLerp(start, backfrac, end, clipped[0]);
5883 segmentmins[0] = min(start[0], end[0]);
5884 segmentmins[1] = min(start[1], end[1]);
5885 segmentmins[2] = min(start[2], end[2]);
5886 segmentmaxs[0] = max(start[0], end[0]);
5887 segmentmaxs[1] = max(start[1], end[1]);
5888 segmentmaxs[2] = max(start[2], end[2]);
5890 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5892 nodenum = node->back;
5895 // start END start END
5897 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5898 VectorLerp(start, frontfrac, end, clipped[1]);
5899 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5900 backfrac = backdist1 / (backdist1 - backdist2);
5901 VectorLerp(start, backfrac, end, clipped[0]);
5903 segmentmins[0] = min(start[0], end[0]);
5904 segmentmins[1] = min(start[1], end[1]);
5905 segmentmins[2] = min(start[2], end[2]);
5906 segmentmaxs[0] = max(start[0], end[0]);
5907 segmentmaxs[1] = max(start[1], end[1]);
5908 segmentmaxs[2] = max(start[2], end[2]);
5910 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5912 nodenum = node->back;
5915 // START END start END
5917 backfrac = backdist1 / (backdist1 - backdist2);
5918 VectorLerp(start, backfrac, end, clipped[0]);
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
5931 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5933 backfrac = backdist1 / (backdist1 - backdist2);
5934 VectorLerp(start, backfrac, end, clipped[0]);
5936 segmentmins[0] = min(start[0], end[0]);
5937 segmentmins[1] = min(start[1], end[1]);
5938 segmentmins[2] = min(start[2], end[2]);
5939 segmentmaxs[0] = max(start[0], end[0]);
5940 segmentmaxs[1] = max(start[1], end[1]);
5941 segmentmaxs[2] = max(start[2], end[2]);
5943 nodenum = node->back;
5946 // START end START end
5948 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5949 VectorLerp(start, frontfrac, end, clipped[1]);
5950 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5951 backfrac = backdist1 / (backdist1 - backdist2);
5952 VectorLerp(start, backfrac, end, clipped[0]);
5954 segmentmins[0] = min(start[0], end[0]);
5955 segmentmins[1] = min(start[1], end[1]);
5956 segmentmins[2] = min(start[2], end[2]);
5957 segmentmaxs[0] = max(start[0], end[0]);
5958 segmentmaxs[1] = max(start[1], end[1]);
5959 segmentmaxs[2] = max(start[2], end[2]);
5961 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5963 nodenum = node->back;
5966 // start END START end
5968 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5969 VectorLerp(start, frontfrac, end, clipped[1]);
5970 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5971 backfrac = backdist1 / (backdist1 - backdist2);
5972 VectorLerp(start, backfrac, end, clipped[0]);
5974 segmentmins[0] = min(start[0], end[0]);
5975 segmentmins[1] = min(start[1], end[1]);
5976 segmentmins[2] = min(start[2], end[2]);
5977 segmentmaxs[0] = max(start[0], end[0]);
5978 segmentmaxs[1] = max(start[1], end[1]);
5979 segmentmaxs[2] = max(start[2], end[2]);
5981 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5983 nodenum = node->back;
5986 // START END START end
5988 backfrac = backdist1 / (backdist1 - backdist2);
5989 VectorLerp(start, backfrac, end, clipped[0]);
5991 segmentmins[0] = min(start[0], end[0]);
5992 segmentmins[1] = min(start[1], end[1]);
5993 segmentmins[2] = min(start[2], end[2]);
5994 segmentmaxs[0] = max(start[0], end[0]);
5995 segmentmaxs[1] = max(start[1], end[1]);
5996 segmentmaxs[2] = max(start[2], end[2]);
5998 nodenum = node->back;
6001 // start end start end
6002 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6003 nodenum = node->back;
6006 // START end start end
6008 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6009 VectorLerp(start, frontfrac, end, clipped[1]);
6010 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
6012 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6014 nodenum = node->back;
6017 // start END start end
6019 frontfrac = frontdist1 / (frontdist1 - frontdist2);
6020 VectorLerp(start, frontfrac, end, clipped[1]);
6021 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
6023 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
6025 nodenum = node->back;
6028 // START END start end
6029 nodenum = node->back;
6035 if (!model->collision_bih.leafs)
6037 leaf = model->collision_bih.leafs + (-1-nodenum);
6039 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6045 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6046 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6048 case BIH_COLLISIONTRIANGLE:
6049 if (!mod_q3bsp_curves_collisions.integer)
6051 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6052 texture = model->data_textures + leaf->textureindex;
6053 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);
6055 case BIH_RENDERTRIANGLE:
6056 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6057 texture = model->data_textures + leaf->textureindex;
6058 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);
6063 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)
6065 const bih_leaf_t *leaf;
6066 const bih_node_t *node;
6067 const colbrushf_t *brush;
6069 const texture_t *texture;
6071 while (nodenum >= 0)
6073 node = model->collision_bih.nodes + nodenum;
6074 axis = node->type - BIH_SPLITX;
6076 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6080 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6081 nodenum = node->back;
6084 if (segmentmins[axis] <= node->backmax)
6086 if (segmentmaxs[axis] >= node->frontmin)
6087 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6088 nodenum = node->back;
6090 else if (segmentmaxs[axis] >= node->frontmin)
6091 nodenum = node->front;
6093 return; // trace falls between children
6095 if (!model->collision_bih.leafs)
6097 leaf = model->collision_bih.leafs + (-1-nodenum);
6099 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6105 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6106 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6108 case BIH_COLLISIONTRIANGLE:
6109 if (!mod_q3bsp_curves_collisions.integer)
6111 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6112 texture = model->data_textures + leaf->textureindex;
6113 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);
6115 case BIH_RENDERTRIANGLE:
6116 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6117 texture = model->data_textures + leaf->textureindex;
6118 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);
6123 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)
6125 memset(trace, 0, sizeof(*trace));
6126 trace->fraction = 1;
6127 trace->realfraction = 1;
6128 trace->hitsupercontentsmask = hitsupercontentsmask;
6129 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6132 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)
6134 if (VectorCompare(start, end))
6136 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6140 memset(trace, 0, sizeof(*trace));
6141 trace->fraction = 1;
6142 trace->realfraction = 1;
6143 trace->hitsupercontentsmask = hitsupercontentsmask;
6144 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6147 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)
6149 float segmentmins[3], segmentmaxs[3];
6150 colboxbrushf_t thisbrush_start, thisbrush_end;
6151 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6153 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6155 vec3_t shiftstart, shiftend;
6156 VectorAdd(start, boxmins, shiftstart);
6157 VectorAdd(end, boxmins, shiftend);
6158 if (VectorCompare(start, end))
6159 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6162 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6163 VectorSubtract(trace->endpos, boxmins, trace->endpos);
6168 // box trace, performed as brush trace
6169 memset(trace, 0, sizeof(*trace));
6170 trace->fraction = 1;
6171 trace->realfraction = 1;
6172 trace->hitsupercontentsmask = hitsupercontentsmask;
6173 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6174 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6175 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6176 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6177 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6178 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6179 VectorAdd(start, boxmins, boxstartmins);
6180 VectorAdd(start, boxmaxs, boxstartmaxs);
6181 VectorAdd(end, boxmins, boxendmins);
6182 VectorAdd(end, boxmaxs, boxendmaxs);
6183 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6184 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6185 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6188 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6191 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6192 return trace.startsupercontents;
6195 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)
6198 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6200 int hitsupercontents;
6201 VectorSet(end, start[0], start[1], model->normalmins[2]);
6203 memset(trace, 0, sizeof(*trace));
6204 trace->fraction = 1;
6205 trace->realfraction = 1;
6206 trace->hitsupercontentsmask = hitsupercontentsmask;
6208 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6209 hitsupercontents = trace->hitsupercontents;
6210 memset(trace, 0, sizeof(*trace));
6211 trace->fraction = 1;
6212 trace->realfraction = 1;
6213 trace->hitsupercontentsmask = hitsupercontentsmask;
6214 trace->startsupercontents = hitsupercontents;
6218 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6221 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6224 VectorSet(end, start[0], start[1], model->normalmins[2]);
6225 memset(&trace, 0, sizeof(trace));
6227 trace.realfraction = 1;
6228 trace.hitsupercontentsmask = 0;
6229 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(&trace, model, model->collision_bih.rootnode, start, end, start, end);
6230 return trace.hitsupercontents;
6236 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6241 // find which leaf the point is in
6243 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6244 // point trace the brushes
6245 leaf = (mleaf_t *)node;
6246 for (i = 0;i < leaf->numleafbrushes;i++)
6248 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6249 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6251 brush->markframe = markframe;
6252 Collision_TracePointBrushFloat(trace, point, brush);
6255 // can't do point traces on curves (they have no thickness)
6258 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)
6260 int i, startside, endside;
6261 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6263 msurface_t *surface;
6266 // walk the tree until we hit a leaf, recursing for any split cases
6270 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6272 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6273 node = node->children[1];
6275 // abort if this part of the bsp tree can not be hit by this trace
6276 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6278 plane = node->plane;
6279 // axial planes are much more common than non-axial, so an optimized
6280 // axial case pays off here
6281 if (plane->type < 3)
6283 dist1 = start[plane->type] - plane->dist;
6284 dist2 = end[plane->type] - plane->dist;
6288 dist1 = DotProduct(start, plane->normal) - plane->dist;
6289 dist2 = DotProduct(end, plane->normal) - plane->dist;
6291 startside = dist1 < 0;
6292 endside = dist2 < 0;
6293 if (startside == endside)
6295 // most of the time the line fragment is on one side of the plane
6296 node = node->children[startside];
6300 // line crosses node plane, split the line
6301 dist1 = PlaneDiff(linestart, plane);
6302 dist2 = PlaneDiff(lineend, plane);
6303 midfrac = dist1 / (dist1 - dist2);
6304 VectorLerp(linestart, midfrac, lineend, mid);
6305 // take the near side first
6306 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6307 // if we found an impact on the front side, don't waste time
6308 // exploring the far side
6309 if (midfrac <= trace->realfraction)
6310 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6315 // abort if this part of the bsp tree can not be hit by this trace
6316 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6319 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6320 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6321 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6322 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6323 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6324 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6325 // line trace the brushes
6326 leaf = (mleaf_t *)node;
6328 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6331 for (i = 0;i < leaf->numleafbrushes;i++)
6333 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6334 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6336 brush->markframe = markframe;
6337 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6340 // can't do point traces on curves (they have no thickness)
6341 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6343 // line trace the curves
6344 for (i = 0;i < leaf->numleafsurfaces;i++)
6346 surface = model->data_surfaces + leaf->firstleafsurface[i];
6347 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6349 surface->deprecatedq3collisionmarkframe = markframe;
6350 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);
6356 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)
6362 msurface_t *surface;
6364 float nodesegmentmins[3], nodesegmentmaxs[3];
6365 // walk the tree until we hit a leaf, recursing for any split cases
6369 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6371 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6372 node = node->children[1];
6374 // abort if this part of the bsp tree can not be hit by this trace
6375 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6377 plane = node->plane;
6378 // axial planes are much more common than non-axial, so an optimized
6379 // axial case pays off here
6380 if (plane->type < 3)
6382 // this is an axial plane, compare bounding box directly to it and
6383 // recurse sides accordingly
6384 // recurse down node sides
6385 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6386 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6387 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6388 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6392 // this is a non-axial plane, so check if the start and end boxes
6393 // are both on one side of the plane to handle 'diagonal' cases
6394 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6398 // segment crosses plane
6399 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6402 // if sides == 0 then the trace itself is bogus (Not A Number values),
6403 // in this case we simply pretend the trace hit nothing
6405 return; // ERROR: NAN bounding box!
6406 // take whichever side the segment box is on
6407 node = node->children[sides - 1];
6410 // abort if this part of the bsp tree can not be hit by this trace
6411 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6413 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6414 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6415 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6416 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6417 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6418 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6420 leaf = (mleaf_t *)node;
6422 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6425 for (i = 0;i < leaf->numleafbrushes;i++)
6427 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6428 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6430 brush->markframe = markframe;
6431 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6434 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6436 for (i = 0;i < leaf->numleafsurfaces;i++)
6438 surface = model->data_surfaces + leaf->firstleafsurface[i];
6439 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6441 surface->deprecatedq3collisionmarkframe = markframe;
6442 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);
6449 static int markframe = 0;
6451 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)
6455 memset(trace, 0, sizeof(*trace));
6456 trace->fraction = 1;
6457 trace->realfraction = 1;
6458 trace->hitsupercontentsmask = hitsupercontentsmask;
6459 if (mod_collision_bih.integer)
6460 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6461 else if (model->brush.submodel)
6463 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6464 if (brush->colbrushf)
6465 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6468 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6471 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)
6474 float segmentmins[3], segmentmaxs[3];
6475 msurface_t *surface;
6478 if (VectorCompare(start, end))
6480 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6484 memset(trace, 0, sizeof(*trace));
6485 trace->fraction = 1;
6486 trace->realfraction = 1;
6487 trace->hitsupercontentsmask = hitsupercontentsmask;
6488 segmentmins[0] = min(start[0], end[0]) - 1;
6489 segmentmins[1] = min(start[1], end[1]) - 1;
6490 segmentmins[2] = min(start[2], end[2]) - 1;
6491 segmentmaxs[0] = max(start[0], end[0]) + 1;
6492 segmentmaxs[1] = max(start[1], end[1]) + 1;
6493 segmentmaxs[2] = max(start[2], end[2]) + 1;
6494 if (mod_collision_bih.integer)
6495 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6496 else if (model->brush.submodel)
6498 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6499 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6500 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6501 if (mod_q3bsp_curves_collisions.integer)
6502 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6503 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6504 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);
6507 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6510 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)
6513 float segmentmins[3], segmentmaxs[3];
6514 msurface_t *surface;
6516 colboxbrushf_t thisbrush_start, thisbrush_end;
6517 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6519 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6521 vec3_t shiftstart, shiftend;
6522 VectorAdd(start, boxmins, shiftstart);
6523 VectorAdd(end, boxmins, shiftend);
6524 if (VectorCompare(start, end))
6525 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6528 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6529 VectorSubtract(trace->endpos, boxmins, trace->endpos);
6534 // box trace, performed as brush trace
6535 memset(trace, 0, sizeof(*trace));
6536 trace->fraction = 1;
6537 trace->realfraction = 1;
6538 trace->hitsupercontentsmask = hitsupercontentsmask;
6539 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6540 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6541 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6542 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6543 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6544 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6545 VectorAdd(start, boxmins, boxstartmins);
6546 VectorAdd(start, boxmaxs, boxstartmaxs);
6547 VectorAdd(end, boxmins, boxendmins);
6548 VectorAdd(end, boxmaxs, boxendmaxs);
6549 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6550 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6551 if (mod_collision_bih.integer)
6552 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6553 else if (model->brush.submodel)
6555 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6556 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6557 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, brush->colbrushf, brush->colbrushf);
6558 if (mod_q3bsp_curves_collisions.integer)
6559 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6560 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6561 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);
6564 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, &thisbrush_start.brush, &thisbrush_end.brush, ++markframe, segmentmins, segmentmaxs);
6567 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6570 int supercontents = 0;
6572 if (mod_collision_bih.integer)
6575 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6576 supercontents = trace.startsupercontents;
6578 // test if the point is inside each brush
6579 else if (model->brush.submodel)
6581 // submodels are effectively one leaf
6582 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6583 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6584 supercontents |= brush->colbrushf->supercontents;
6588 mnode_t *node = model->brush.data_nodes;
6590 // find which leaf the point is in
6592 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6593 leaf = (mleaf_t *)node;
6594 // now check the brushes in the leaf
6595 for (i = 0;i < leaf->numleafbrushes;i++)
6597 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6598 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6599 supercontents |= brush->colbrushf->supercontents;
6602 return supercontents;
6605 void Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces)
6613 int nummodelbrushes = model->nummodelbrushes;
6614 int nummodelsurfaces = model->nummodelsurfaces;
6616 const int *collisionelement3i;
6617 const float *collisionvertex3f;
6618 const int *renderelement3i;
6619 const float *rendervertex3f;
6620 bih_leaf_t *bihleafs;
6621 bih_node_t *bihnodes;
6623 int *temp_leafsortscratch;
6624 const msurface_t *surface;
6625 const q3mbrush_t *brush;
6627 // find out how many BIH leaf nodes we need
6629 if (userendersurfaces)
6631 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6632 bihnumleafs += surface->num_triangles;
6636 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6637 if (brush->colbrushf)
6639 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6641 if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
6642 bihnumleafs += surface->num_triangles;
6644 bihnumleafs += surface->num_collisiontriangles;
6651 // allocate the memory for the BIH leaf nodes
6652 bihleafs = Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6654 // now populate the BIH leaf nodes
6657 // add render surfaces
6658 renderelement3i = model->surfmesh.data_element3i;
6659 rendervertex3f = model->surfmesh.data_vertex3f;
6660 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6662 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6664 if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
6666 bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
6667 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6668 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6669 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6670 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6671 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6672 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6673 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6674 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6679 if (!userendersurfaces)
6681 // add collision brushes
6682 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6684 if (!brush->colbrushf)
6686 bihleafs[bihleafindex].type = BIH_BRUSH;
6687 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6688 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6689 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6690 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6694 // add collision surfaces
6695 collisionelement3i = model->brush.data_collisionelement3i;
6696 collisionvertex3f = model->brush.data_collisionvertex3f;
6697 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6699 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6701 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
6702 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6703 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6704 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6705 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6706 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6707 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6708 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6709 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6715 // allocate buffers for the produced and temporary data
6716 bihmaxnodes = bihnumleafs - 1;
6717 bihnodes = Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6718 temp_leafsort = Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6719 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6722 BIH_Build(&model->collision_bih, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6724 // we're done with the temporary data
6725 Mem_Free(temp_leafsort);
6727 // resize the BIH nodes array if it over-allocated
6728 if (model->collision_bih.maxnodes > model->collision_bih.numnodes)
6730 model->collision_bih.maxnodes = model->collision_bih.numnodes;
6731 model->collision_bih.nodes = Mem_Realloc(loadmodel->mempool, model->collision_bih.nodes, model->collision_bih.numnodes * sizeof(bih_node_t));
6735 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6737 int supercontents = 0;
6738 if (nativecontents & CONTENTSQ3_SOLID)
6739 supercontents |= SUPERCONTENTS_SOLID;
6740 if (nativecontents & CONTENTSQ3_WATER)
6741 supercontents |= SUPERCONTENTS_WATER;
6742 if (nativecontents & CONTENTSQ3_SLIME)
6743 supercontents |= SUPERCONTENTS_SLIME;
6744 if (nativecontents & CONTENTSQ3_LAVA)
6745 supercontents |= SUPERCONTENTS_LAVA;
6746 if (nativecontents & CONTENTSQ3_BODY)
6747 supercontents |= SUPERCONTENTS_BODY;
6748 if (nativecontents & CONTENTSQ3_CORPSE)
6749 supercontents |= SUPERCONTENTS_CORPSE;
6750 if (nativecontents & CONTENTSQ3_NODROP)
6751 supercontents |= SUPERCONTENTS_NODROP;
6752 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6753 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6754 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6755 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6756 if (nativecontents & CONTENTSQ3_DONOTENTER)
6757 supercontents |= SUPERCONTENTS_DONOTENTER;
6758 if (nativecontents & CONTENTSQ3_BOTCLIP)
6759 supercontents |= SUPERCONTENTS_BOTCLIP;
6760 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6761 supercontents |= SUPERCONTENTS_OPAQUE;
6762 return supercontents;
6765 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6767 int nativecontents = 0;
6768 if (supercontents & SUPERCONTENTS_SOLID)
6769 nativecontents |= CONTENTSQ3_SOLID;
6770 if (supercontents & SUPERCONTENTS_WATER)
6771 nativecontents |= CONTENTSQ3_WATER;
6772 if (supercontents & SUPERCONTENTS_SLIME)
6773 nativecontents |= CONTENTSQ3_SLIME;
6774 if (supercontents & SUPERCONTENTS_LAVA)
6775 nativecontents |= CONTENTSQ3_LAVA;
6776 if (supercontents & SUPERCONTENTS_BODY)
6777 nativecontents |= CONTENTSQ3_BODY;
6778 if (supercontents & SUPERCONTENTS_CORPSE)
6779 nativecontents |= CONTENTSQ3_CORPSE;
6780 if (supercontents & SUPERCONTENTS_NODROP)
6781 nativecontents |= CONTENTSQ3_NODROP;
6782 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6783 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6784 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6785 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6786 if (supercontents & SUPERCONTENTS_DONOTENTER)
6787 nativecontents |= CONTENTSQ3_DONOTENTER;
6788 if (supercontents & SUPERCONTENTS_BOTCLIP)
6789 nativecontents |= CONTENTSQ3_BOTCLIP;
6790 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6791 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6792 return nativecontents;
6795 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6800 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6801 node = node->children[1];
6803 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6804 if (loadmodel->brush.num_leafs < numleafs)
6805 loadmodel->brush.num_leafs = numleafs;
6808 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6810 int i, j, numshadowmeshtriangles, lumps;
6811 q3dheader_t *header;
6812 float corner[3], yawradius, modelradius;
6813 msurface_t *surface;
6815 mod->modeldatatypestring = "Q3BSP";
6817 mod->type = mod_brushq3;
6818 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6821 header = (q3dheader_t *)buffer;
6822 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6823 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6825 i = LittleLong(header->version);
6826 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6827 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6829 mod->soundfromcenter = true;
6830 mod->TraceBox = Mod_Q3BSP_TraceBox;
6831 mod->TraceLine = Mod_Q3BSP_TraceLine;
6832 mod->TracePoint = Mod_Q3BSP_TracePoint;
6833 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6834 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6835 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6836 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6837 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6838 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6839 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6840 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6841 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6842 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6843 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6844 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6845 mod->brush.AmbientSoundLevelsForPoint = NULL;
6846 mod->brush.RoundUpToHullSize = NULL;
6847 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6848 mod->Draw = R_Q1BSP_Draw;
6849 mod->DrawDepth = R_Q1BSP_DrawDepth;
6850 mod->DrawDebug = R_Q1BSP_DrawDebug;
6851 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
6852 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
6853 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
6854 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
6855 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
6856 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
6857 mod->DrawLight = R_Q1BSP_DrawLight;
6859 mod_base = (unsigned char *)header;
6861 // swap all the lumps
6862 header->ident = LittleLong(header->ident);
6863 header->version = LittleLong(header->version);
6864 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
6865 for (i = 0;i < lumps;i++)
6867 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
6868 if((char *) bufferend < (char *) buffer + j)
6869 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
6870 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
6871 if((char *) bufferend < (char *) buffer + j)
6872 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
6875 * NO, do NOT clear them!
6876 * they contain actual data referenced by other stuff.
6877 * Instead, before using the advertisements lump, check header->versio
6879 * Sorry, but otherwise it breaks memory of the first lump.
6880 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
6882 header->lumps[i].fileofs = 0;
6883 header->lumps[i].filelen = 0;
6887 mod->brush.qw_md4sum = 0;
6888 mod->brush.qw_md4sum2 = 0;
6889 for (i = 0;i < lumps;i++)
6891 if (i == Q3LUMP_ENTITIES)
6893 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6894 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
6896 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6898 // all this checksumming can take a while, so let's send keepalives here too
6899 CL_KeepaliveMessage(false);
6902 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
6903 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
6904 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
6905 if (header->version == Q3BSPVERSION_IG)
6906 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
6908 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
6909 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
6910 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
6911 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
6912 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
6913 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
6914 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
6915 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
6916 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
6917 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
6918 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
6919 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
6920 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
6921 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
6922 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
6924 // the MakePortals code works fine on the q3bsp data as well
6925 Mod_Q1BSP_MakePortals();
6927 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
6928 loadmodel->brush.supportwateralpha = true;
6930 // make a single combined shadow mesh to allow optimized shadow volume creation
6931 numshadowmeshtriangles = 0;
6932 if (cls.state != ca_dedicated)
6934 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
6936 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
6937 numshadowmeshtriangles += surface->num_triangles;
6939 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
6940 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
6941 if (surface->num_triangles > 0)
6942 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, loadmodel->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
6943 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true, false);
6944 if (loadmodel->brush.shadowmesh)
6945 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
6948 loadmodel->brush.num_leafs = 0;
6949 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
6951 if (loadmodel->brush.numsubmodels)
6952 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
6955 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
6960 // duplicate the basic information
6961 dpsnprintf(name, sizeof(name), "*%i", i);
6962 mod = Mod_FindName(name, loadmodel->name);
6963 // copy the base model to this one
6965 // rename the clone back to its proper name
6966 strlcpy(mod->name, name, sizeof(mod->name));
6967 mod->brush.parentmodel = loadmodel;
6968 // textures and memory belong to the main model
6969 mod->texturepool = NULL;
6970 mod->mempool = NULL;
6971 mod->brush.GetPVS = NULL;
6972 mod->brush.FatPVS = NULL;
6973 mod->brush.BoxTouchingPVS = NULL;
6974 mod->brush.BoxTouchingLeafPVS = NULL;
6975 mod->brush.BoxTouchingVisibleLeafs = NULL;
6976 mod->brush.FindBoxClusters = NULL;
6977 mod->brush.LightPoint = NULL;
6978 mod->brush.AmbientSoundLevelsForPoint = NULL;
6980 mod->brush.submodel = i;
6981 if (loadmodel->brush.submodels)
6982 loadmodel->brush.submodels[i] = mod;
6984 // make the model surface list (used by shadowing/lighting)
6985 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
6986 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
6987 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
6988 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
6989 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
6990 Mod_MakeSortedSurfaces(mod);
6992 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
6993 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
6994 // enlarge the bounding box to enclose all geometry of this model,
6995 // because q3map2 sometimes lies (mostly to affect the lightgrid),
6996 // which can in turn mess up the farclip (as well as culling when
6997 // outside the level - an unimportant concern)
6999 //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]);
7000 for (j = 0;j < mod->nummodelsurfaces;j++)
7002 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7003 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7005 if (!surface->num_vertices)
7007 for (k = 0;k < surface->num_vertices;k++, v += 3)
7009 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7010 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7011 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7012 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7013 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7014 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7017 //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]);
7018 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7019 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7020 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7021 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7022 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7023 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7024 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7025 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7026 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7027 mod->yawmins[2] = mod->normalmins[2];
7028 mod->yawmaxs[2] = mod->normalmaxs[2];
7029 mod->radius = modelradius;
7030 mod->radius2 = modelradius * modelradius;
7032 // this gets altered below if sky or water is used
7033 mod->DrawSky = NULL;
7034 mod->DrawAddWaterPlanes = NULL;
7036 for (j = 0;j < mod->nummodelsurfaces;j++)
7037 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7039 if (j < mod->nummodelsurfaces)
7040 mod->DrawSky = R_Q1BSP_DrawSky;
7042 for (j = 0;j < mod->nummodelsurfaces;j++)
7043 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
7045 if (j < mod->nummodelsurfaces)
7046 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7048 Mod_MakeCollisionBIH(mod, false);
7050 // generate VBOs and other shared data before cloning submodels
7055 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);
7058 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7060 int i = LittleLong(((int *)buffer)[1]);
7061 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7062 Mod_Q3BSP_Load(mod,buffer, bufferend);
7063 else if (i == Q2BSPVERSION)
7064 Mod_Q2BSP_Load(mod,buffer, bufferend);
7066 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7069 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7071 Host_Error("Mod_MAP_Load: not yet implemented");
7077 typedef struct objvertex_s
7087 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7089 const char *textbase = (char *)buffer, *text = textbase;
7093 char materialname[MAX_QPATH];
7094 int i, j, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, numsurfaces, surfacevertices, surfacetriangles, surfaceelements;
7095 int index1, index2, index3;
7096 objvertex_t vfirst, vprev, vcurrent;
7099 int numtriangles = 0;
7100 int maxtriangles = 0;
7101 objvertex_t *vertices = NULL;
7103 int maxtextures = 0, numtextures = 0, textureindex = 0;
7104 int maxv = 0, numv = 1;
7105 int maxvt = 0, numvt = 1;
7106 int maxvn = 0, numvn = 1;
7107 char *texturenames = NULL;
7108 float dist, modelradius, modelyawradius;
7114 objvertex_t *thisvertex = NULL;
7115 int vertexhashindex;
7116 int *vertexhashtable = NULL;
7117 objvertex_t *vertexhashdata = NULL;
7118 objvertex_t *vdata = NULL;
7119 int vertexhashsize = 0;
7120 int vertexhashcount = 0;
7121 skinfile_t *skinfiles = NULL;
7122 unsigned char *data = NULL;
7124 memset(&vfirst, 0, sizeof(vfirst));
7125 memset(&vprev, 0, sizeof(vprev));
7126 memset(&vcurrent, 0, sizeof(vcurrent));
7128 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7130 loadmodel->modeldatatypestring = "OBJ";
7132 loadmodel->type = mod_obj;
7133 loadmodel->soundfromcenter = true;
7134 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7135 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7136 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7137 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7138 loadmodel->brush.TraceLineOfSight = NULL;
7139 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7140 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7141 loadmodel->brush.GetPVS = NULL;
7142 loadmodel->brush.FatPVS = NULL;
7143 loadmodel->brush.BoxTouchingPVS = NULL;
7144 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7145 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7146 loadmodel->brush.FindBoxClusters = NULL;
7147 loadmodel->brush.LightPoint = NULL;
7148 loadmodel->brush.FindNonSolidLocation = NULL;
7149 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7150 loadmodel->brush.RoundUpToHullSize = NULL;
7151 loadmodel->brush.PointInLeaf = NULL;
7152 loadmodel->Draw = R_Q1BSP_Draw;
7153 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7154 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7155 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7156 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7157 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7158 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7159 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7160 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7161 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7163 skinfiles = Mod_LoadSkinFiles();
7164 if (loadmodel->numskins < 1)
7165 loadmodel->numskins = 1;
7167 // make skinscenes for the skins (no groups)
7168 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7169 for (i = 0;i < loadmodel->numskins;i++)
7171 loadmodel->skinscenes[i].firstframe = i;
7172 loadmodel->skinscenes[i].framecount = 1;
7173 loadmodel->skinscenes[i].loop = true;
7174 loadmodel->skinscenes[i].framerate = 10;
7180 // parse the OBJ text now
7187 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7188 line[linelen] = text[linelen];
7190 for (argc = 0;argc < 4;argc++)
7194 while (*s == ' ' || *s == '\t')
7204 while (*s == ' ' || *s == '\t')
7214 if (argv[0][0] == '#')
7216 if (!strcmp(argv[0], "v"))
7220 maxv = max(maxv * 2, 1024);
7221 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7223 v[numv*3+0] = atof(argv[1]);
7224 v[numv*3+2] = atof(argv[2]);
7225 v[numv*3+1] = atof(argv[3]);
7228 else if (!strcmp(argv[0], "vt"))
7232 maxvt = max(maxvt * 2, 1024);
7233 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7235 vt[numvt*2+0] = atof(argv[1]);
7236 vt[numvt*2+1] = 1-atof(argv[2]);
7239 else if (!strcmp(argv[0], "vn"))
7243 maxvn = max(maxvn * 2, 1024);
7244 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7246 vn[numvn*3+0] = atof(argv[1]);
7247 vn[numvn*3+2] = atof(argv[2]);
7248 vn[numvn*3+1] = atof(argv[3]);
7251 else if (!strcmp(argv[0], "f"))
7255 if (maxtextures <= numtextures)
7257 maxtextures = max(maxtextures * 2, 256);
7258 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7260 textureindex = numtextures++;
7261 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7263 for (j = 1;j < argc;j++)
7265 index1 = atoi(argv[j]);
7266 while(argv[j][0] && argv[j][0] != '/')
7270 index2 = atoi(argv[j]);
7271 while(argv[j][0] && argv[j][0] != '/')
7275 index3 = atoi(argv[j]);
7276 // negative refers to a recent vertex
7277 // zero means not specified
7278 // positive means an absolute vertex index
7280 index1 = numv - index1;
7282 index2 = numvt - index2;
7284 index3 = numvn - index3;
7285 vcurrent.nextindex = -1;
7286 vcurrent.textureindex = textureindex;
7287 VectorCopy(v + 3*index1, vcurrent.v);
7288 Vector2Copy(vt + 2*index2, vcurrent.vt);
7289 VectorCopy(vn + 3*index3, vcurrent.vn);
7290 if (numtriangles == 0)
7292 VectorCopy(vcurrent.v, mins);
7293 VectorCopy(vcurrent.v, maxs);
7297 mins[0] = min(mins[0], vcurrent.v[0]);
7298 mins[1] = min(mins[1], vcurrent.v[1]);
7299 mins[2] = min(mins[2], vcurrent.v[2]);
7300 maxs[0] = max(maxs[0], vcurrent.v[0]);
7301 maxs[1] = max(maxs[1], vcurrent.v[1]);
7302 maxs[2] = max(maxs[2], vcurrent.v[2]);
7308 if (maxtriangles <= numtriangles)
7310 maxtriangles = max(maxtriangles * 2, 32768);
7311 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7313 vertices[numtriangles*3+0] = vfirst;
7314 vertices[numtriangles*3+1] = vprev;
7315 vertices[numtriangles*3+2] = vcurrent;
7321 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7323 else if (!strcmp(argv[0], "usemtl"))
7325 for (i = 0;i < numtextures;i++)
7326 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7328 if (i < numtextures)
7332 if (maxtextures <= numtextures)
7334 maxtextures = max(maxtextures * 2, 256);
7335 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7337 textureindex = numtextures++;
7338 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7343 // now that we have the OBJ data loaded as-is, we can convert it
7345 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7346 VectorCopy(mins, loadmodel->normalmins);
7347 VectorCopy(maxs, loadmodel->normalmaxs);
7348 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7349 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7350 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7351 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7352 modelradius = modelyawradius + modelradius * modelradius;
7353 modelyawradius = sqrt(modelyawradius);
7354 modelradius = sqrt(modelradius);
7355 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7356 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7357 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7358 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7359 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7360 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7361 loadmodel->radius = modelradius;
7362 loadmodel->radius2 = modelradius * modelradius;
7364 // allocate storage for triangles
7365 loadmodel->num_surfaces = loadmodel->nummodelsurfaces = numsurfaces = numtextures;
7366 loadmodel->surfmesh.data_element3i = Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7367 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t));
7368 // allocate vertex hash structures to build an optimal vertex subset
7369 vertexhashsize = numtriangles*2;
7370 vertexhashtable = Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7371 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7372 vertexhashdata = Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7373 vertexhashcount = 0;
7375 // gather surface stats for assigning vertex/triangle ranges
7379 for (textureindex = 0;textureindex < numtextures;textureindex++)
7381 msurface_t *surface = loadmodel->data_surfaces + textureindex;
7382 // copy the mins/maxs of the model backwards so that the first vertex
7383 // added will set the surface bounds to a point
7384 VectorCopy(loadmodel->normalmaxs, surface->mins);
7385 VectorCopy(loadmodel->normalmins, surface->maxs);
7386 surfacevertices = 0;
7387 surfaceelements = 0;
7388 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7390 thisvertex = vertices + vertexindex;
7391 if (thisvertex->textureindex != textureindex)
7393 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7394 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7395 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7396 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7397 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7398 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7399 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7400 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7402 vdata = vertexhashdata + i;
7403 if (vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7408 i = vertexhashcount++;
7409 vdata = vertexhashdata + i;
7410 *vdata = *thisvertex;
7411 vdata->nextindex = vertexhashtable[vertexhashindex];
7412 vertexhashtable[vertexhashindex] = i;
7415 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7418 surfacetriangles = surfaceelements / 3;
7419 surface->num_vertices = surfacevertices;
7420 surface->num_triangles = surfacetriangles;
7421 surface->num_firstvertex = firstvertex;
7422 surface->num_firsttriangle = firsttriangle;
7423 firstvertex += surface->num_vertices;
7424 firsttriangle += surface->num_triangles;
7426 numvertices = firstvertex;
7428 // allocate storage for final mesh data
7429 loadmodel->num_textures = numtextures * loadmodel->numskins;
7430 loadmodel->num_texturesperskin = numtextures;
7431 data = (unsigned char *)Mem_Alloc(loadmodel->mempool, numsurfaces * sizeof(int) + numsurfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + numvertices * sizeof(float[14]));
7432 loadmodel->sortedmodelsurfaces = (int *)data;data += numsurfaces * sizeof(int);
7433 loadmodel->data_textures = (texture_t *)data;data += numsurfaces * loadmodel->numskins * sizeof(texture_t);
7434 loadmodel->surfmesh.num_vertices = numvertices;
7435 loadmodel->surfmesh.num_triangles = numtriangles;
7436 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7437 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7438 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7439 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7440 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7441 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7442 if (loadmodel->surfmesh.num_vertices <= 65536)
7443 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7445 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7447 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7448 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7449 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7452 // load the textures
7453 for (textureindex = 0;textureindex < numtextures;textureindex++)
7454 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7455 Mod_FreeSkinFiles(skinfiles);
7457 // set the surface textures
7458 for (textureindex = 0;textureindex < numtextures;textureindex++)
7460 msurface_t *surface = loadmodel->data_surfaces + textureindex;
7461 surface->texture = loadmodel->data_textures + textureindex;
7466 Mem_Free(texturenames);
7470 Mem_Free(vertexhashtable);
7471 Mem_Free(vertexhashdata);
7473 // compute all the mesh information that was not loaded from the file
7474 Mod_MakeSortedSurfaces(loadmodel);
7475 if (loadmodel->surfmesh.data_element3s)
7476 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7477 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7478 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7479 // generate normals if the file did not have them
7480 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7481 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
7482 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);
7483 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7485 Mod_MakeCollisionBIH(loadmodel, true);
7500 typedef struct objvertex_s
7508 typedef struct objtriangle_s
7510 objvertex_t vertex[3];
7512 // these fields are used only in conversion to surfaces
7515 int surfacevertexindex[3];
7516 float edgeplane[3][4];
7522 struct objnode_s *children[2];
7523 struct objnode_s *parent;
7524 objtriangle_t *triangles;
7533 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)
7539 float bestnormal[3];
7544 int numfronttriangles;
7545 int numbacktriangles;
7550 float outfrontpoints[5][3];
7551 float outbackpoints[5][3];
7552 int neededfrontpoints;
7553 int neededbackpoints;
7557 node = (objnode_t *)Mem_ExpandableArray_AllocRecord(array);
7558 node->parent = parent;
7561 VectorCopy(triangles[0].vertex[0].v, mins);
7562 VectorCopy(triangles[0].vertex[0].v, maxs);
7564 else if (parent && parent->children[0] == node)
7566 VectorCopy(parent->mins, mins);
7567 Vectorcopy(parent->maxs, maxs);
7569 else if (parent && parent->children[1] == node)
7571 VectorCopy(parent->mins, mins);
7572 Vectorcopy(parent->maxs, maxs);
7579 for (i = 0;i < numtriangles;i++)
7581 for (j = 0;j < 3;j++)
7583 mins[0] = min(mins[0], triangles[i].vertex[j].v[0]);
7584 mins[1] = min(mins[1], triangles[i].vertex[j].v[1]);
7585 mins[2] = min(mins[2], triangles[i].vertex[j].v[2]);
7586 maxs[0] = max(maxs[0], triangles[i].vertex[j].v[0]);
7587 maxs[1] = max(maxs[1], triangles[i].vertex[j].v[1]);
7588 maxs[2] = max(maxs[2], triangles[i].vertex[j].v[2]);
7591 VectorCopy(mins, node->mins);
7592 VectorCopy(maxs, node->maxs);
7593 if (numtriangles <= mod_obj_leaftriangles.integer)
7596 loadmodel->brush.num_leafs++;
7597 node->triangles = triangles;
7598 node->numtriangles = numtriangles;
7603 loadmodel->brush.num_nodes++;
7604 // pick a splitting plane from the various choices available to us...
7605 // early splits simply halve the interval
7607 VectorClear(bestnormal);
7609 if (numtriangles <= mod_obj_splitterlimit.integer)
7610 limit = numtriangles;
7613 for (i = -3;i < limit;i++)
7617 // first we try 3 axial splits (kdtree-like)
7619 VectorClear(normal);
7621 dist = (mins[j] + maxs[j]) * 0.5f;
7625 // then we try each triangle plane
7626 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7627 VectorNormalize(normal);
7628 dist = DotProduct(normal, triangles[i].vertex[0].v);
7629 // use positive axial values whenever possible
7630 if (normal[0] == -1)
7632 if (normal[1] == -1)
7634 if (normal[2] == -1)
7636 // skip planes that match the current best
7637 if (VectorCompare(normal, bestnormal) && dist == bestdist)
7644 for (j = 0;j < numtriangles;j++)
7646 dists[0] = DotProduct(normal, triangles[j].vertex[0].v) - dist;
7647 dists[1] = DotProduct(normal, triangles[j].vertex[1].v) - dist;
7648 dists[2] = DotProduct(normal, triangles[j].vertex[2].v) - dist;
7649 if (dists[0] < -DIST_EPSILON || dists[1] < -DIST_EPSILON || dists[2] < -DIST_EPSILON)
7651 if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7656 else if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7661 // score is supposed to:
7662 // prefer axial splits
7663 // prefer evenly dividing the input triangles
7664 // prefer triangles on the plane
7665 // avoid triangles crossing the plane
7666 score = count_on*count_on - count_both*count_both + min(count_front, count_back)*(count_front+count_back);
7667 if (normal[0] == 1 || normal[1] == 1 || normal[2] == 1)
7669 if (i == -3 || bestscore < score)
7671 VectorCopy(normal, bestnormal);
7677 // now we have chosen an optimal split plane...
7679 // divide triangles by the splitting plane
7680 numfronttriangles = 0;
7681 numbacktriangles = 0;
7682 for (i = 0;i < numtriangles;i++)
7684 neededfrontpoints = 0;
7685 neededbackpoints = 0;
7687 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);
7688 if (countonpoints > 1)
7690 // triangle lies on plane, assign it to one child only
7691 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7692 if (DotProduct(bestnormal, normal) >= 0)
7694 // assign to front side child
7695 obj_fronttriangles[numfronttriangles++] = triangles[i];
7699 // assign to back side child
7700 obj_backtriangles[numbacktriangles++] = triangles[i];
7705 // convert clipped polygons to triangles
7706 for (j = 0;j < neededfrontpoints-2;j++)
7708 obj_fronttriangles[numfronttriangles] = triangles[i];
7709 VectorCopy(outfrontpoints[0], obj_fronttriangles[numfronttriangles].vertex[0].v);
7710 VectorCopy(outfrontpoints[j+1], obj_fronttriangles[numfronttriangles].vertex[1].v);
7711 VectorCopy(outfrontpoints[j+2], obj_fronttriangles[numfronttriangles].vertex[2].v);
7712 numfronttriangles++;
7714 for (j = 0;j < neededbackpoints-2;j++)
7716 obj_backtriangles[numbacktriangles] = triangles[i];
7717 VectorCopy(outbackpoints[0], obj_backtriangles[numbacktriangles].vertex[0].v);
7718 VectorCopy(outbackpoints[j+1], obj_backtriangles[numbacktriangles].vertex[1].v);
7719 VectorCopy(outbackpoints[j+2], obj_backtriangles[numbacktriangles].vertex[2].v);
7725 // now copy the triangles out of the big buffer
7726 if (numfronttriangles)
7728 fronttriangles = Mem_Alloc(loadmodel->mempool, fronttriangles * sizeof(*fronttriangles));
7729 memcpy(fronttriangles, obj_fronttriangles, numfronttriangles * sizeof(*fronttriangles));
7732 fronttriangles = NULL;
7733 if (numbacktriangles)
7735 backtriangles = Mem_Alloc(loadmodel->mempool, backtriangles * sizeof(*backtriangles));
7736 memcpy(backtriangles, obj_backtriangles, numbacktriangles * sizeof(*backtriangles));
7739 backtriangles = NULL;
7741 // free the original triangles we were given
7743 Mem_Free(triangles);
7747 // now create the children...
7748 node->children[0] = Mod_OBJ_BSPNodeForTriangles(node, fronttriangles, numfronttriangles, frontmins, frontmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
7749 node->children[1] = Mod_OBJ_BSPNodeForTriangles(node, backtriangles, numbacktriangles, backmins, backmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
7753 void Mod_OBJ_SnapVertex(float *v)
7756 float a = mod_obj_vertexprecision.value;
7758 v[0] -= floor(v[0] * a + 0.5f) * b;
7759 v[1] -= floor(v[1] * a + 0.5f) * b;
7760 v[2] -= floor(v[2] * a + 0.5f) * b;
7763 void Mod_OBJ_ConvertBSPNode(objnode_t *objnode, mnode_t *mnodeparent)
7765 if (objnode->children[0])
7767 // convert to mnode_t
7768 mnode_t *mnode = loadmodel->brush.data_nodes + loadmodel->brush.num_nodes++;
7769 mnode->parent = mnodeparent;
7770 mnode->plane = loadmodel->brush.data_planes + loadmodel->brush.num_planes++;
7771 VectorCopy(objnode->normal, mnode->plane->normal);
7772 mnode->plane->dist = objnode->dist;
7773 PlaneClassify(mnode->plane);
7774 VectorCopy(objnode->mins, mnode->mins);
7775 VectorCopy(objnode->maxs, mnode->maxs);
7776 // push combinedsupercontents up to the parent
7778 mnodeparent->combinedsupercontents |= mnode->combinedsupercontents;
7779 mnode->children[0] = Mod_OBJ_ConvertBSPNode(objnode->children[0], mnode);
7780 mnode->children[1] = Mod_OBJ_ConvertBSPNode(objnode->children[1], mnode);
7784 // convert to mleaf_t
7785 mleaf_t *mleaf = loadmodel->brush.data_leafs + loadmodel->brush.num_leafs++;
7786 mleaf->parent = mnodeparent;
7787 VectorCopy(objnode->mins, mleaf->mins);
7788 VectorCopy(objnode->maxs, mleaf->maxs);
7789 mleaf->clusterindex = loadmodel->brush.num_leafs - 1;
7790 if (objnode->numtriangles)
7792 objtriangle_t *triangles = objnode->triangles;
7793 int numtriangles = objnode->numtriangles;
7797 objvertex_t vertex[3];
7799 maxsurfaces = numtriangles;
7801 // calculate some more data on each triangle for surface gathering
7802 for (i = 0;i < numtriangles;i++)
7804 triangle = triangles + i;
7805 texture = loadmodel->data_textures + triangle->textureindex;
7806 Mod_OBJ_SnapVertex(triangle->vertex[0].v);
7807 Mod_OBJ_SnapVertex(triangle->vertex[1].v);
7808 Mod_OBJ_SnapVertex(triangle->vertex[2].v);
7809 TriangleNormal(triangle->vertex[0].v, triangle->vertex[1].v, triangle->vertex[2].v, normal);
7811 if (fabs(normal[axis]) < fabs(normal[1]))
7813 if (fabs(normal[axis]) < fabs(normal[2]))
7815 VectorClear(normal);
7817 triangle->axis = axis;
7818 VectorSubtract(triangle->vertex[1].v, triangle->vertex[0].v, edge[0]);
7819 VectorSubtract(triangle->vertex[2].v, triangle->vertex[1].v, edge[1]);
7820 VectorSubtract(triangle->vertex[0].v, triangle->vertex[2].v, edge[2]);
7821 CrossProduct(edge[0], normal, triangle->edgeplane[0]);
7822 CrossProduct(edge[1], normal, triangle->edgeplane[1]);
7823 CrossProduct(edge[2], normal, triangle->edgeplane[2]);
7824 VectorNormalize(triangle->edgeplane[0]);
7825 VectorNormalize(triangle->edgeplane[1]);
7826 VectorNormalize(triangle->edgeplane[2]);
7827 triangle->edgeplane[0][3] = DotProduct(triangle->edgeplane[0], triangle->vertex[0].v);
7828 triangle->edgeplane[1][3] = DotProduct(triangle->edgeplane[1], triangle->vertex[1].v);
7829 triangle->edgeplane[2][3] = DotProduct(triangle->edgeplane[2], triangle->vertex[2].v);
7830 triangle->surfaceindex = 0;
7831 // add to the combined supercontents while we're here...
7832 mleaf->combinedsupercontents |= texture->supercontents;
7835 for (i = 0;i < numtriangles;i++)
7837 // skip already-assigned triangles
7838 if (triangles[i].surfaceindex)
7840 texture = loadmodel->data_textures + triangles[i].textureindex;
7841 // assign a new surface to this triangle
7842 triangles[i].surfaceindex = surfaceindex++;
7843 axis = triangles[i].axis;
7845 // find the triangle's neighbors, this can take multiple passes
7850 for (j = i+1;j < numtriangles;j++)
7852 if (triangles[j].surfaceindex || triangles[j].axis != axis || triangles[j].texture != texture)
7854 triangle = triangles + j;
7855 for (k = i;k < j;k++)
7857 if (triangles[k].surfaceindex != surfaceindex)
7859 if (VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[0].v)
7860 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[1].v)
7861 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[2].v)
7862 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[0].v)
7863 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[1].v)
7864 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[2].v)
7865 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[0].v)
7866 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[1].v)
7867 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[2].v))
7869 // shares a vertex position
7873 for (k = 0;k < numvertices;k++)
7874 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))
7876 if (k == numvertices)
7877 break; // not a neighbor
7878 // this triangle is a neighbor and has the same axis and texture
7879 // check now if it overlaps in lightmap projection space
7880 triangles[j].surfaceindex;
7884 //triangles[i].surfaceindex = surfaceindex++;
7885 for (surfaceindex = 0;surfaceindex < numsurfaces;surfaceindex++)
7887 if (surfaces[surfaceindex].texture != texture)
7889 // check if any triangles already in this surface overlap in lightmap projection space
7896 // let the collision code simply use the surfaces
7897 mleaf->containscollisionsurfaces = mleaf->combinedsupercontents != 0;
7898 mleaf->numleafsurfaces = ?;
7899 mleaf->firstleafsurface = ?;
7901 // push combinedsupercontents up to the parent
7903 mnodeparent->combinedsupercontents |= mleaf->combinedsupercontents;
7908 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7911 const char *textbase = (char *)buffer, *text = textbase;
7915 char materialname[MAX_QPATH];
7916 int j, index1, index2, index3, first, prev, index;
7919 int numtriangles = 0;
7920 int maxtriangles = 131072;
7921 objtriangle_t *triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
7923 int maxtextures = 256, numtextures = 0, textureindex = 0;
7924 int maxv = 1024, numv = 0;
7925 int maxvt = 1024, numvt = 0;
7926 int maxvn = 1024, numvn = 0;
7927 char **texturenames;
7928 float *v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
7929 float *vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
7930 float *vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
7931 objvertex_t vfirst, vprev, vcurrent;
7936 int maxverthash = 65536, numverthash = 0;
7937 int numhashindex = 65536;
7938 struct objverthash_s
7940 struct objverthash_s *next;
7946 *hash, **verthash = Mem_Alloc(tempmempool, numhashindex * sizeof(*verthash)), *verthashdata = Mem_Alloc(tempmempool, maxverthash * sizeof(*verthashdata)), *oldverthashdata;
7949 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7951 loadmodel->modeldatatypestring = "OBJ";
7953 loadmodel->type = mod_obj;
7954 loadmodel->soundfromcenter = true;
7955 loadmodel->TraceBox = Mod_OBJ_TraceBox;
7956 loadmodel->TraceLine = Mod_OBJ_TraceLine;
7957 loadmodel->TracePoint = Mod_OBJ_TracePoint;
7958 loadmodel->PointSuperContents = Mod_OBJ_PointSuperContents;
7959 loadmodel->brush.TraceLineOfSight = Mod_OBJ_TraceLineOfSight;
7960 loadmodel->brush.SuperContentsFromNativeContents = Mod_OBJ_SuperContentsFromNativeContents;
7961 loadmodel->brush.NativeContentsFromSuperContents = Mod_OBJ_NativeContentsFromSuperContents;
7962 loadmodel->brush.GetPVS = Mod_OBJ_GetPVS;
7963 loadmodel->brush.FatPVS = Mod_OBJ_FatPVS;
7964 loadmodel->brush.BoxTouchingPVS = Mod_OBJ_BoxTouchingPVS;
7965 loadmodel->brush.BoxTouchingLeafPVS = Mod_OBJ_BoxTouchingLeafPVS;
7966 loadmodel->brush.BoxTouchingVisibleLeafs = Mod_OBJ_BoxTouchingVisibleLeafs;
7967 loadmodel->brush.FindBoxClusters = Mod_OBJ_FindBoxClusters;
7968 loadmodel->brush.LightPoint = Mod_OBJ_LightPoint;
7969 loadmodel->brush.FindNonSolidLocation = Mod_OBJ_FindNonSolidLocation;
7970 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7971 loadmodel->brush.RoundUpToHullSize = NULL;
7972 loadmodel->brush.PointInLeaf = Mod_OBJ_PointInLeaf;
7973 loadmodel->Draw = R_Q1BSP_Draw;
7974 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7975 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7976 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7977 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7978 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7979 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7980 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7981 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7982 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7987 // parse the OBJ text now
7994 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7995 line[linelen] = text[linelen];
7997 for (argc = 0;argc < (int)(sizeof(argv)/sizeof(argv[0]));argc++)
8001 while (*s == ' ' || *s == '\t')
8011 while (*s == ' ' || *s == '\t')
8016 if (argv[0][0] == '#')
8018 if (!strcmp(argv[0], "v"))
8024 v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
8027 memcpy(v, oldv, numv * sizeof(float[3]));
8031 v[numv*3+0] = atof(argv[1]);
8032 v[numv*3+1] = atof(argv[2]);
8033 v[numv*3+2] = atof(argv[3]);
8036 else if (!strcmp(argv[0], "vt"))
8042 vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
8045 memcpy(vt, oldvt, numvt * sizeof(float[2]));
8049 vt[numvt*2+0] = atof(argv[1]);
8050 vt[numvt*2+1] = atof(argv[2]);
8053 else if (!strcmp(argv[0], "vn"))
8059 vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8062 memcpy(vn, oldvn, numvn * sizeof(float[3]));
8066 vn[numvn*3+0] = atof(argv[1]);
8067 vn[numvn*3+1] = atof(argv[2]);
8068 vn[numvn*3+2] = atof(argv[3]);
8071 else if (!strcmp(argv[0], "f"))
8073 for (j = 1;j < argc;j++)
8075 index1 = atoi(argv[j]);
8076 while(argv[j][0] && argv[j][0] != '/')
8080 index2 = atoi(argv[j]);
8081 while(argv[j][0] && argv[j][0] != '/')
8085 index3 = atoi(argv[j]);
8086 // negative refers to a recent vertex
8087 // zero means not specified
8088 // positive means an absolute vertex index
8090 index1 = numv - index1;
8092 index2 = numvt - index2;
8094 index3 = numvn - index3;
8095 VectorCopy(v + 3*index1, vcurrent.v);
8096 Vector2Copy(vt + 2*index2, vcurrent.vt);
8097 VectorCopy(vn + 3*index3, vcurrent.vn);
8098 if (numtriangles == 0)
8100 VectorCopy(vcurrent.v, mins);
8101 VectorCopy(vcurrent.v, maxs);
8105 mins[0] = min(mins[0], vcurrent.v[0]);
8106 mins[1] = min(mins[1], vcurrent.v[1]);
8107 mins[2] = min(mins[2], vcurrent.v[2]);
8108 maxs[0] = max(maxs[0], vcurrent.v[0]);
8109 maxs[1] = max(maxs[1], vcurrent.v[1]);
8110 maxs[2] = max(maxs[2], vcurrent.v[2]);
8116 if (maxtriangles <= numtriangles)
8118 objtriangle_t *oldtriangles = triangles;
8120 triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8123 memcpy(triangles, oldtriangles, maxtriangles * sizeof(*triangles));
8124 Mem_Free(oldtriangles);
8127 triangles[numtriangles].textureindex = textureindex;
8128 triangles[numtriangles].vertex[0] = vfirst;
8129 triangles[numtriangles].vertex[1] = vprev;
8130 triangles[numtriangles].vertex[2] = vcurrent;
8137 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8139 else if (!!strcmp(argv[0], "usemtl"))
8141 for (i = 0;i < numtextures;i++)
8142 if (!strcmp(texturenames[numtextures], argv[1]))
8144 if (i < numtextures)
8145 texture = textures + i;
8148 if (maxtextures <= numtextures)
8150 texture_t *oldtextures = textures;
8152 textures = Mem_Alloc(tempmempool, maxtextures * sizeof(*textures));
8155 memcpy(textures, oldtextures, numtextures * sizeof(*textures));
8156 Mem_Free(oldtextures);
8159 textureindex = numtextures++;
8160 texturenames[textureindex] = Mem_Alloc(tempmempool, strlen(argv[1]) + 1);
8161 memcpy(texturenames[textureindex], argv[1], strlen(argv[1]) + 1);
8171 // now that we have the OBJ data loaded as-is, we can convert it
8173 // load the textures
8174 loadmodel->num_textures = numtextures;
8175 loadmodel->data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
8176 for (i = 0;i < numtextures;i++)
8177 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, texturenames[i], true, true, TEXF_MIPMAP | TEXF_ALPHA | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS);
8179 // free the texturenames array since we are now done with it
8180 for (i = 0;i < numtextures;i++)
8182 Mem_Free(texturenames[i]);
8183 texturenames[i] = NULL;
8185 Mem_Free(texturenames);
8186 texturenames = NULL;
8188 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8189 VectorCopy(mins, loadmodel->normalmins);
8190 VectorCopy(maxs, loadmodel->normalmaxs);
8191 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8192 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8193 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8194 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8195 modelradius = modelyawradius + modelradius * modelradius;
8196 modelyawradius = sqrt(modelyawradius);
8197 modelradius = sqrt(modelradius);
8198 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8199 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8200 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8201 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8202 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8203 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8204 loadmodel->radius = modelradius;
8205 loadmodel->radius2 = modelradius * modelradius;
8207 // make sure the temp triangle buffer is big enough for BSP building
8208 maxclippedtriangles = numtriangles*4;
8209 if (numtriangles > 0)
8211 clippedfronttriangles = Mem_Alloc(loadmodel->mempool, maxclippedtriangles * 2 * sizeof(objtriangle_t));
8212 clippedbacktriangles = clippedfronttriangles + maxclippedtriangles;
8215 // 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
8216 loadmodel->brush.num_leafs = 0;
8217 loadmodel->brush.num_nodes = 0;
8218 Mem_ExpandableArray_NewArray(&nodesarray, loadmodel->mempool, sizeof(objnode_t), 1024);
8219 rootnode = Mod_OBJ_BSPNodeForTriangles(triangles, numtriangles, mins, maxs, &nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8221 // convert the BSP tree to mnode_t and mleaf_t structures and convert the triangles to msurface_t...
8222 loadmodel->brush.data_leafs = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8223 loadmodel->brush.data_nodes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mnode_t));
8224 loadmodel->brush.data_planes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mplane_t));
8225 loadmodel->brush.num_leafs = 0;
8226 loadmodel->brush.num_nodes = 0;
8227 loadmodel->brush.num_planes = 0;
8228 Mod_OBJ_ConvertAndFreeBSPNode(rootnode);
8230 if (clippedfronttriangles)
8231 Mem_Free(clippedfronttriangles);
8232 maxclippedtriangles = 0;
8233 clippedfronttriangles = NULL;
8234 clippedbacktriangles = NULL;
8236 --- NOTHING DONE PAST THIS POINT ---
8238 loadmodel->numskins = LittleLong(pinmodel->num_skins);
8239 numxyz = LittleLong(pinmodel->num_xyz);
8240 numst = LittleLong(pinmodel->num_st);
8241 loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
8242 loadmodel->numframes = LittleLong(pinmodel->num_frames);
8243 loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
8244 loadmodel->num_poses = loadmodel->surfmesh.num_morphframes;
8245 skinwidth = LittleLong(pinmodel->skinwidth);
8246 skinheight = LittleLong(pinmodel->skinheight);
8247 iskinwidth = 1.0f / skinwidth;
8248 iskinheight = 1.0f / skinheight;
8250 loadmodel->num_surfaces = 1;
8251 loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
8252 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]));
8253 loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
8254 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8255 loadmodel->sortedmodelsurfaces[0] = 0;
8256 loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
8257 loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
8258 loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8259 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8261 loadmodel->synctype = ST_RAND;
8264 inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
8265 skinfiles = Mod_LoadSkinFiles();
8268 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8269 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8270 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8271 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
8272 Mod_FreeSkinFiles(skinfiles);
8274 else if (loadmodel->numskins)
8276 // skins found (most likely not a player model)
8277 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8278 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8279 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8280 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
8281 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i * loadmodel->num_surfaces, inskin, true, true, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP | TEXF_COMPRESS);
8285 // no skins (most likely a player model)
8286 loadmodel->numskins = 1;
8287 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8288 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8289 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8290 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
8293 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8294 for (i = 0;i < loadmodel->numskins;i++)
8296 loadmodel->skinscenes[i].firstframe = i;
8297 loadmodel->skinscenes[i].framecount = 1;
8298 loadmodel->skinscenes[i].loop = true;
8299 loadmodel->skinscenes[i].framerate = 10;
8302 // load the triangles and stvert data
8303 inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
8304 intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
8305 md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
8306 md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
8307 // swap the triangle list
8308 loadmodel->surfmesh.num_vertices = 0;
8309 for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
8311 for (j = 0;j < 3;j++)
8313 xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
8314 st = (unsigned short) LittleShort (intri[i].index_st[j]);
8317 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
8322 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
8325 hashindex = (xyz * 256 + st) & 65535;
8326 for (hash = md2verthash[hashindex];hash;hash = hash->next)
8327 if (hash->xyz == xyz && hash->st == st)
8331 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
8334 hash->next = md2verthash[hashindex];
8335 md2verthash[hashindex] = hash;
8337 loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
8341 vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
8342 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));
8343 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
8344 loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
8345 for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
8348 hash = md2verthashdata + i;
8349 vertremap[i] = hash->xyz;
8350 sts = LittleShort(inst[hash->st*2+0]);
8351 stt = LittleShort(inst[hash->st*2+1]);
8352 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
8354 Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
8358 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
8359 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
8362 Mem_Free(md2verthash);
8363 Mem_Free(md2verthashdata);
8365 // generate ushort elements array if possible
8366 if (loadmodel->surfmesh.num_vertices <= 65536)
8367 loadmodel->surfmesh.data_element3s = (unsigned short *)Mem_Alloc(loadmodel->mempool, sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles);
8370 datapointer = (base + LittleLong(pinmodel->ofs_frames));
8371 for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
8376 pinframe = (md2frame_t *)datapointer;
8377 datapointer += sizeof(md2frame_t);
8378 // store the frame scale/translate into the appropriate array
8379 for (j = 0;j < 3;j++)
8381 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
8382 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
8384 // convert the vertices
8385 v = (trivertx_t *)datapointer;
8386 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
8387 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
8388 out[k] = v[vertremap[k]];
8389 datapointer += numxyz * sizeof(trivertx_t);
8391 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
8392 loadmodel->animscenes[i].firstframe = i;
8393 loadmodel->animscenes[i].framecount = 1;
8394 loadmodel->animscenes[i].framerate = 10;
8395 loadmodel->animscenes[i].loop = true;
8398 Mem_Free(vertremap);
8400 Mod_MakeSortedSurfaces(loadmodel);
8401 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8402 Mod_Alias_CalculateBoundingBox();
8403 Mod_Alias_MorphMesh_CompileFrames();
8405 surface = loadmodel->data_surfaces;
8406 surface->texture = loadmodel->data_textures;
8407 surface->num_firsttriangle = 0;
8408 surface->num_triangles = loadmodel->surfmesh.num_triangles;
8409 surface->num_firstvertex = 0;
8410 surface->num_vertices = loadmodel->surfmesh.num_vertices;
8412 loadmodel->surfmesh.isanimated = false;
8414 if (loadmodel->surfmesh.data_element3s)
8415 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8416 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8419 #endif // !OBJASMODEL
8421 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
8423 // we already have done PVS culling at this point...
8424 // so we don't need to do it again.
8427 vec3_t testorigin, mins, maxs;
8429 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
8430 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
8431 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
8433 if(model->brush.TraceLineOfSight(model, eye, testorigin))
8436 // expand the box a little
8437 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
8438 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
8439 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
8440 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
8441 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
8442 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
8444 for(i = 0; i != numsamples; ++i)
8446 testorigin[0] = lhrandom(mins[0], maxs[0]);
8447 testorigin[1] = lhrandom(mins[1], maxs[1]);
8448 testorigin[2] = lhrandom(mins[2], maxs[2]);
8450 if(model->brush.TraceLineOfSight(model, eye, testorigin))