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_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
50 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"};
51 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"};
53 static texture_t mod_q1bsp_texture_solid;
54 static texture_t mod_q1bsp_texture_sky;
55 static texture_t mod_q1bsp_texture_lava;
56 static texture_t mod_q1bsp_texture_slime;
57 static texture_t mod_q1bsp_texture_water;
59 void Mod_BrushInit(void)
61 // Cvar_RegisterVariable(&r_subdivide_size);
62 Cvar_RegisterVariable(&r_novis);
63 Cvar_RegisterVariable(&r_picmipworld);
64 Cvar_RegisterVariable(&r_nosurftextures);
65 Cvar_RegisterVariable(&r_subdivisions_tolerance);
66 Cvar_RegisterVariable(&r_subdivisions_mintess);
67 Cvar_RegisterVariable(&r_subdivisions_maxtess);
68 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
69 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
70 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
71 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
72 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
73 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
74 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
75 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
76 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
77 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
78 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
79 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
80 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
81 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
82 Cvar_RegisterVariable(&mod_collision_bih);
83 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
85 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
86 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
87 mod_q1bsp_texture_solid.surfaceflags = 0;
88 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
90 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
91 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
92 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
93 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
95 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
96 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
97 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
98 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
100 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
101 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
102 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
103 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
105 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
106 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
107 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
108 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
111 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
118 // LordHavoc: modified to start at first clip node,
119 // in other words: first node of the (sub)model
120 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
122 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
124 return (mleaf_t *)node;
127 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
131 leaf = Mod_Q1BSP_PointInLeaf(model, p);
134 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
137 memcpy(out, leaf->ambient_sound_level, i);
143 memset(out, 0, outsize);
146 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
149 int nodestackindex = 0;
150 mnode_t *node, *nodestack[1024];
151 if (!model->brush.num_pvsclusters)
153 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
159 // node - recurse down the BSP tree
160 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
164 return -1; // ERROR: NAN bounding box!
165 // box is on one side of plane, take that path
166 node = node->children[sides-1];
170 // box crosses plane, take one path and remember the other
171 if (nodestackindex < 1024)
172 nodestack[nodestackindex++] = node->children[0];
173 node = node->children[1];
179 // leaf - add clusterindex to list
180 if (numclusters < maxclusters)
181 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
185 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
189 if (nodestackindex < 1024)
190 nodestack[nodestackindex++] = node->children[0];
191 node = node->children[1];
196 // leaf - add clusterindex to list
197 if (numclusters < maxclusters)
198 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
203 // try another path we didn't take earlier
204 if (nodestackindex == 0)
206 node = nodestack[--nodestackindex];
208 // return number of clusters found (even if more than the maxclusters)
212 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
214 int nodestackindex = 0;
215 mnode_t *node, *nodestack[1024];
216 if (!model->brush.num_pvsclusters)
218 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
224 // node - recurse down the BSP tree
225 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
229 return -1; // ERROR: NAN bounding box!
230 // box is on one side of plane, take that path
231 node = node->children[sides-1];
235 // box crosses plane, take one path and remember the other
236 if (nodestackindex < 1024)
237 nodestack[nodestackindex++] = node->children[0];
238 node = node->children[1];
244 // leaf - check cluster bit
245 int clusterindex = ((mleaf_t *)node)->clusterindex;
246 if (CHECKPVSBIT(pvs, clusterindex))
248 // it is visible, return immediately with the news
253 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
257 if (nodestackindex < 1024)
258 nodestack[nodestackindex++] = node->children[0];
259 node = node->children[1];
264 // leaf - check cluster bit
265 int clusterindex = ((mleaf_t *)node)->clusterindex;
266 if (CHECKPVSBIT(pvs, clusterindex))
268 // it is visible, return immediately with the news
274 // nothing to see here, try another path we didn't take earlier
275 if (nodestackindex == 0)
277 node = nodestack[--nodestackindex];
283 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
285 int nodestackindex = 0;
286 mnode_t *node, *nodestack[1024];
287 if (!model->brush.num_leafs)
289 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
295 // node - recurse down the BSP tree
296 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
300 return -1; // ERROR: NAN bounding box!
301 // box is on one side of plane, take that path
302 node = node->children[sides-1];
306 // box crosses plane, take one path and remember the other
307 if (nodestackindex < 1024)
308 nodestack[nodestackindex++] = node->children[0];
309 node = node->children[1];
315 // leaf - check cluster bit
316 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
317 if (CHECKPVSBIT(pvs, clusterindex))
319 // it is visible, return immediately with the news
324 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
328 if (nodestackindex < 1024)
329 nodestack[nodestackindex++] = node->children[0];
330 node = node->children[1];
335 // leaf - check cluster bit
336 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
337 if (CHECKPVSBIT(pvs, clusterindex))
339 // it is visible, return immediately with the news
345 // nothing to see here, try another path we didn't take earlier
346 if (nodestackindex == 0)
348 node = nodestack[--nodestackindex];
354 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
356 int nodestackindex = 0;
357 mnode_t *node, *nodestack[1024];
358 if (!model->brush.num_leafs)
360 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
366 // node - recurse down the BSP tree
367 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
371 return -1; // ERROR: NAN bounding box!
372 // box is on one side of plane, take that path
373 node = node->children[sides-1];
377 // box crosses plane, take one path and remember the other
378 if (nodestackindex < 1024)
379 nodestack[nodestackindex++] = node->children[0];
380 node = node->children[1];
386 // leaf - check if it is visible
387 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
389 // it is visible, return immediately with the news
394 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
398 if (nodestackindex < 1024)
399 nodestack[nodestackindex++] = node->children[0];
400 node = node->children[1];
405 // leaf - check if it is visible
406 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
408 // it is visible, return immediately with the news
414 // nothing to see here, try another path we didn't take earlier
415 if (nodestackindex == 0)
417 node = nodestack[--nodestackindex];
423 typedef struct findnonsolidlocationinfo_s
426 vec3_t absmin, absmax;
432 findnonsolidlocationinfo_t;
434 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
437 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
439 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
440 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
441 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
442 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
443 VectorSubtract(vert[1], vert[0], edge[0]);
444 VectorSubtract(vert[2], vert[1], edge[1]);
445 CrossProduct(edge[1], edge[0], facenormal);
446 if (facenormal[0] || facenormal[1] || facenormal[2])
448 VectorNormalize(facenormal);
449 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
450 if (f <= info->bestdist && f >= -info->bestdist)
452 VectorSubtract(vert[0], vert[2], edge[2]);
453 VectorNormalize(edge[0]);
454 VectorNormalize(edge[1]);
455 VectorNormalize(edge[2]);
456 CrossProduct(facenormal, edge[0], edgenormal[0]);
457 CrossProduct(facenormal, edge[1], edgenormal[1]);
458 CrossProduct(facenormal, edge[2], edgenormal[2]);
460 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
461 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
462 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
464 // we got lucky, the center is within the face
465 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
469 if (info->bestdist > dist)
471 info->bestdist = dist;
472 VectorScale(facenormal, (info->radius - -dist), info->nudge);
477 if (info->bestdist > dist)
479 info->bestdist = dist;
480 VectorScale(facenormal, (info->radius - dist), info->nudge);
486 // check which edge or vertex the center is nearest
487 for (i = 0;i < 3;i++)
489 f = DotProduct(info->center, edge[i]);
490 if (f >= DotProduct(vert[0], edge[i])
491 && f <= DotProduct(vert[1], edge[i]))
494 VectorMA(info->center, -f, edge[i], point);
495 dist = sqrt(DotProduct(point, point));
496 if (info->bestdist > dist)
498 info->bestdist = dist;
499 VectorScale(point, (info->radius / dist), info->nudge);
501 // skip both vertex checks
502 // (both are further away than this edge)
507 // not on edge, check first vertex of edge
508 VectorSubtract(info->center, vert[i], point);
509 dist = sqrt(DotProduct(point, point));
510 if (info->bestdist > dist)
512 info->bestdist = dist;
513 VectorScale(point, (info->radius / dist), info->nudge);
522 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
524 int surfacenum, k, *mark;
526 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
528 surface = info->model->data_surfaces + *mark;
529 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
531 if(surface->deprecatedq3num_bboxstride > 0)
534 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
535 for(i = 0; i < cnt; ++i)
537 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
539 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
541 tri = i * surface->deprecatedq3num_bboxstride + k;
542 if(tri >= surface->num_triangles)
544 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
551 for (k = 0;k < surface->num_triangles;k++)
553 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
560 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
564 float f = PlaneDiff(info->center, node->plane);
565 if (f >= -info->bestdist)
566 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
567 if (f <= info->bestdist)
568 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
572 if (((mleaf_t *)node)->numleafsurfaces)
573 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
577 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
580 findnonsolidlocationinfo_t info;
586 VectorCopy(in, info.center);
587 info.radius = radius;
592 VectorClear(info.nudge);
593 info.bestdist = radius;
594 VectorCopy(info.center, info.absmin);
595 VectorCopy(info.center, info.absmax);
596 info.absmin[0] -= info.radius + 1;
597 info.absmin[1] -= info.radius + 1;
598 info.absmin[2] -= info.radius + 1;
599 info.absmax[0] += info.radius + 1;
600 info.absmax[1] += info.radius + 1;
601 info.absmax[2] += info.radius + 1;
602 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
603 VectorAdd(info.center, info.nudge, info.center);
605 while (info.bestdist < radius && ++i < 10);
606 VectorCopy(info.center, out);
609 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
611 switch(nativecontents)
616 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
618 return SUPERCONTENTS_WATER;
620 return SUPERCONTENTS_SLIME;
622 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
624 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
629 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
631 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
632 return CONTENTS_SOLID;
633 if (supercontents & SUPERCONTENTS_SKY)
635 if (supercontents & SUPERCONTENTS_LAVA)
636 return CONTENTS_LAVA;
637 if (supercontents & SUPERCONTENTS_SLIME)
638 return CONTENTS_SLIME;
639 if (supercontents & SUPERCONTENTS_WATER)
640 return CONTENTS_WATER;
641 return CONTENTS_EMPTY;
644 typedef struct RecursiveHullCheckTraceInfo_s
646 // the hull we're tracing through
649 // the trace structure to fill in
652 // start, end, and end - start (in model space)
657 RecursiveHullCheckTraceInfo_t;
659 // 1/32 epsilon to keep floating point happy
660 #define DIST_EPSILON (0.03125)
662 #define HULLCHECKSTATE_EMPTY 0
663 #define HULLCHECKSTATE_SOLID 1
664 #define HULLCHECKSTATE_DONE 2
666 extern cvar_t collision_prefernudgedfraction;
667 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
669 // status variables, these don't need to be saved on the stack when
670 // recursing... but are because this should be thread-safe
671 // (note: tracing against a bbox is not thread-safe, yet)
676 // variables that need to be stored on the stack when recursing
681 // LordHavoc: a goto! everyone flee in terror... :)
686 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
687 if (!t->trace->startfound)
689 t->trace->startfound = true;
690 t->trace->startsupercontents |= num;
692 if (num & SUPERCONTENTS_LIQUIDSMASK)
693 t->trace->inwater = true;
695 t->trace->inopen = true;
696 if (num & SUPERCONTENTS_SOLID)
697 t->trace->hittexture = &mod_q1bsp_texture_solid;
698 else if (num & SUPERCONTENTS_SKY)
699 t->trace->hittexture = &mod_q1bsp_texture_sky;
700 else if (num & SUPERCONTENTS_LAVA)
701 t->trace->hittexture = &mod_q1bsp_texture_lava;
702 else if (num & SUPERCONTENTS_SLIME)
703 t->trace->hittexture = &mod_q1bsp_texture_slime;
705 t->trace->hittexture = &mod_q1bsp_texture_water;
706 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
707 t->trace->hitsupercontents = num;
708 if (num & t->trace->hitsupercontentsmask)
710 // if the first leaf is solid, set startsolid
711 if (t->trace->allsolid)
712 t->trace->startsolid = true;
713 #if COLLISIONPARANOID >= 3
716 return HULLCHECKSTATE_SOLID;
720 t->trace->allsolid = false;
721 #if COLLISIONPARANOID >= 3
724 return HULLCHECKSTATE_EMPTY;
728 // find the point distances
729 node = t->hull->clipnodes + num;
731 plane = t->hull->planes + node->planenum;
734 t1 = p1[plane->type] - plane->dist;
735 t2 = p2[plane->type] - plane->dist;
739 t1 = DotProduct (plane->normal, p1) - plane->dist;
740 t2 = DotProduct (plane->normal, p2) - plane->dist;
747 #if COLLISIONPARANOID >= 3
750 num = node->children[1];
759 #if COLLISIONPARANOID >= 3
762 num = node->children[0];
768 // the line intersects, find intersection point
769 // LordHavoc: this uses the original trace for maximum accuracy
770 #if COLLISIONPARANOID >= 3
775 t1 = t->start[plane->type] - plane->dist;
776 t2 = t->end[plane->type] - plane->dist;
780 t1 = DotProduct (plane->normal, t->start) - plane->dist;
781 t2 = DotProduct (plane->normal, t->end) - plane->dist;
784 midf = t1 / (t1 - t2);
785 midf = bound(p1f, midf, p2f);
786 VectorMA(t->start, midf, t->dist, mid);
788 // recurse both sides, front side first
789 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
790 // if this side is not empty, return what it is (solid or done)
791 if (ret != HULLCHECKSTATE_EMPTY)
794 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
795 // if other side is not solid, return what it is (empty or done)
796 if (ret != HULLCHECKSTATE_SOLID)
799 // front is air and back is solid, this is the impact point...
802 t->trace->plane.dist = -plane->dist;
803 VectorNegate (plane->normal, t->trace->plane.normal);
807 t->trace->plane.dist = plane->dist;
808 VectorCopy (plane->normal, t->trace->plane.normal);
811 // calculate the true fraction
812 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
813 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
814 midf = t1 / (t1 - t2);
815 t->trace->realfraction = bound(0, midf, 1);
817 // calculate the return fraction which is nudged off the surface a bit
818 midf = (t1 - DIST_EPSILON) / (t1 - t2);
819 t->trace->fraction = bound(0, midf, 1);
821 if (collision_prefernudgedfraction.integer)
822 t->trace->realfraction = t->trace->fraction;
824 #if COLLISIONPARANOID >= 3
827 return HULLCHECKSTATE_DONE;
830 //#if COLLISIONPARANOID < 2
831 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
834 mclipnode_t *nodes = t->hull->clipnodes;
835 mplane_t *planes = t->hull->planes;
837 VectorCopy(t->start, point);
840 plane = planes + nodes[num].planenum;
841 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
843 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
844 t->trace->startsupercontents |= num;
845 if (num & SUPERCONTENTS_LIQUIDSMASK)
846 t->trace->inwater = true;
848 t->trace->inopen = true;
849 if (num & t->trace->hitsupercontentsmask)
851 t->trace->allsolid = t->trace->startsolid = true;
852 return HULLCHECKSTATE_SOLID;
856 t->trace->allsolid = t->trace->startsolid = false;
857 return HULLCHECKSTATE_EMPTY;
862 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)
864 RecursiveHullCheckTraceInfo_t rhc;
866 memset(&rhc, 0, sizeof(rhc));
867 memset(trace, 0, sizeof(trace_t));
869 rhc.trace->fraction = 1;
870 rhc.trace->realfraction = 1;
871 rhc.trace->allsolid = true;
872 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
873 VectorCopy(start, rhc.start);
874 VectorCopy(start, rhc.end);
875 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
878 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)
880 RecursiveHullCheckTraceInfo_t rhc;
882 if (VectorCompare(start, end))
884 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
888 memset(&rhc, 0, sizeof(rhc));
889 memset(trace, 0, sizeof(trace_t));
891 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
892 rhc.trace->fraction = 1;
893 rhc.trace->realfraction = 1;
894 rhc.trace->allsolid = true;
895 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
896 VectorCopy(start, rhc.start);
897 VectorCopy(end, rhc.end);
898 VectorSubtract(rhc.end, rhc.start, rhc.dist);
899 #if COLLISIONPARANOID >= 2
900 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]);
901 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
906 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
907 memset(&testtrace, 0, sizeof(trace_t));
908 rhc.trace = &testtrace;
909 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
910 rhc.trace->fraction = 1;
911 rhc.trace->realfraction = 1;
912 rhc.trace->allsolid = true;
913 VectorCopy(test, rhc.start);
914 VectorCopy(test, rhc.end);
915 VectorClear(rhc.dist);
916 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
917 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
918 if (!trace->startsolid && testtrace.startsolid)
919 Con_Printf(" - ended in solid!\n");
923 if (VectorLength2(rhc.dist))
924 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
926 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
930 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)
932 // this function currently only supports same size start and end
934 RecursiveHullCheckTraceInfo_t rhc;
936 if (VectorCompare(boxmins, boxmaxs))
938 if (VectorCompare(start, end))
939 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
941 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
945 memset(&rhc, 0, sizeof(rhc));
946 memset(trace, 0, sizeof(trace_t));
948 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
949 rhc.trace->fraction = 1;
950 rhc.trace->realfraction = 1;
951 rhc.trace->allsolid = true;
952 VectorSubtract(boxmaxs, boxmins, boxsize);
954 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
955 else if (model->brush.ishlbsp)
957 // LordHavoc: this has to have a minor tolerance (the .1) because of
958 // minor float precision errors from the box being transformed around
959 if (boxsize[0] < 32.1)
961 if (boxsize[2] < 54) // pick the nearest of 36 or 72
962 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
964 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
967 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
971 // LordHavoc: this has to have a minor tolerance (the .1) because of
972 // minor float precision errors from the box being transformed around
973 if (boxsize[0] < 32.1)
974 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
976 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
978 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
979 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
980 VectorSubtract(rhc.end, rhc.start, rhc.dist);
981 #if COLLISIONPARANOID >= 2
982 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]);
983 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
988 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
989 memset(&testtrace, 0, sizeof(trace_t));
990 rhc.trace = &testtrace;
991 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
992 rhc.trace->fraction = 1;
993 rhc.trace->realfraction = 1;
994 rhc.trace->allsolid = true;
995 VectorCopy(test, rhc.start);
996 VectorCopy(test, rhc.end);
997 VectorClear(rhc.dist);
998 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
999 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1000 if (!trace->startsolid && testtrace.startsolid)
1001 Con_Printf(" - ended in solid!\n");
1005 if (VectorLength2(rhc.dist))
1006 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1008 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1012 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1014 int num = model->brushq1.hulls[0].firstclipnode;
1016 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1017 mplane_t *planes = model->brushq1.hulls[0].planes;
1020 plane = planes + nodes[num].planenum;
1021 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1023 return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1026 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)
1030 colplanef_t cbox_planes[6];
1032 cbox.hasaabbplanes = true;
1033 cbox.supercontents = boxsupercontents;
1036 cbox.numtriangles = 0;
1037 cbox.planes = cbox_planes;
1039 cbox.elements = NULL;
1047 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];
1048 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];
1049 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];
1050 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];
1051 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];
1052 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];
1053 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1054 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1055 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1056 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1057 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1058 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1059 memset(trace, 0, sizeof(trace_t));
1060 trace->hitsupercontentsmask = hitsupercontentsmask;
1061 trace->fraction = 1;
1062 trace->realfraction = 1;
1063 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1065 RecursiveHullCheckTraceInfo_t rhc;
1066 static hull_t box_hull;
1067 static mclipnode_t box_clipnodes[6];
1068 static mplane_t box_planes[6];
1069 // fill in a default trace
1070 memset(&rhc, 0, sizeof(rhc));
1071 memset(trace, 0, sizeof(trace_t));
1072 //To keep everything totally uniform, bounding boxes are turned into small
1073 //BSP trees instead of being compared directly.
1074 // create a temp hull from bounding box sizes
1075 box_planes[0].dist = cmaxs[0] - mins[0];
1076 box_planes[1].dist = cmins[0] - maxs[0];
1077 box_planes[2].dist = cmaxs[1] - mins[1];
1078 box_planes[3].dist = cmins[1] - maxs[1];
1079 box_planes[4].dist = cmaxs[2] - mins[2];
1080 box_planes[5].dist = cmins[2] - maxs[2];
1081 #if COLLISIONPARANOID >= 3
1082 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]);
1085 if (box_hull.clipnodes == NULL)
1089 //Set up the planes and clipnodes so that the six floats of a bounding box
1090 //can just be stored out and get a proper hull_t structure.
1092 box_hull.clipnodes = box_clipnodes;
1093 box_hull.planes = box_planes;
1094 box_hull.firstclipnode = 0;
1095 box_hull.lastclipnode = 5;
1097 for (i = 0;i < 6;i++)
1099 box_clipnodes[i].planenum = i;
1103 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1105 box_clipnodes[i].children[side^1] = i + 1;
1107 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1109 box_planes[i].type = i>>1;
1110 box_planes[i].normal[i>>1] = 1;
1114 // trace a line through the generated clipping hull
1115 //rhc.boxsupercontents = boxsupercontents;
1116 rhc.hull = &box_hull;
1118 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1119 rhc.trace->fraction = 1;
1120 rhc.trace->realfraction = 1;
1121 rhc.trace->allsolid = true;
1122 VectorCopy(start, rhc.start);
1123 VectorCopy(end, rhc.end);
1124 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1125 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1126 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1127 if (rhc.trace->startsupercontents)
1128 rhc.trace->startsupercontents = boxsupercontents;
1132 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)
1134 memset(trace, 0, sizeof(trace_t));
1135 trace->fraction = 1;
1136 trace->realfraction = 1;
1137 if (BoxesOverlap(start, start, cmins, cmaxs))
1139 trace->startsupercontents |= boxsupercontents;
1140 if (hitsupercontentsmask & boxsupercontents)
1142 trace->startsolid = true;
1143 trace->allsolid = true;
1148 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1151 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1152 return trace.fraction == 1;
1155 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)
1159 float mid, distz = endz - startz;
1163 return false; // didn't hit anything
1165 switch (node->plane->type)
1168 node = node->children[x < node->plane->dist];
1171 node = node->children[y < node->plane->dist];
1174 side = startz < node->plane->dist;
1175 if ((endz < node->plane->dist) == side)
1177 node = node->children[side];
1180 // found an intersection
1181 mid = node->plane->dist;
1184 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1185 front += startz * node->plane->normal[2];
1186 back += endz * node->plane->normal[2];
1187 side = front < node->plane->dist;
1188 if ((back < node->plane->dist) == side)
1190 node = node->children[side];
1193 // found an intersection
1194 mid = startz + distz * (front - node->plane->dist) / (front - back);
1198 // go down front side
1199 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1200 return true; // hit something
1203 // check for impact on this node
1204 if (node->numsurfaces)
1206 int i, dsi, dti, lmwidth, lmheight;
1208 msurface_t *surface;
1209 unsigned char *lightmap;
1210 int maps, line3, size3;
1213 float scale, w, w00, w01, w10, w11;
1215 surface = model->data_surfaces + node->firstsurface;
1216 for (i = 0;i < node->numsurfaces;i++, surface++)
1218 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1219 continue; // no lightmaps
1221 // location we want to sample in the lightmap
1222 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;
1223 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;
1228 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1229 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1232 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1234 // calculate bilinear interpolation factors
1235 // and also multiply by fixedpoint conversion factors
1238 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1239 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1240 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1241 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 32768.0f);
1243 // values for pointer math
1244 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1245 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1247 // look up the pixel
1248 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1250 // bilinear filter each lightmap style, and sum them
1251 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1253 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1254 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1255 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1256 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1257 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1261 return true; // success
1266 // go down back side
1267 node = node->children[side ^ 1];
1269 distz = endz - startz;
1274 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1276 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1277 VectorSet(diffusenormal, 0, 0, 1);
1279 if (!model->brushq1.lightdata)
1281 VectorSet(ambientcolor, 1, 1, 1);
1282 VectorSet(diffusecolor, 0, 0, 0);
1286 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);
1289 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1292 unsigned char *outstart = out;
1293 while (out < outend)
1297 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));
1307 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));
1310 for (c = *in++;c > 0;c--)
1314 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));
1325 R_Q1BSP_LoadSplitSky
1327 A sky texture is 256*128, with the right side being a masked overlay
1330 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1335 unsigned *solidpixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1336 unsigned *alphapixels = Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1338 // allocate a texture pool if we need it
1339 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1340 loadmodel->texturepool = R_AllocTexturePool();
1342 if (bytesperpixel == 4)
1344 for (y = 0;y < h;y++)
1346 for (x = 0;x < w;x++)
1348 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1349 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1355 // make an average value for the back to avoid
1356 // a fringe on the top level
1365 for (y = 0;y < h;y++)
1367 for (x = 0;x < w;x++)
1369 p = src[x*width+y+w];
1370 r += palette_rgb[p][0];
1371 g += palette_rgb[p][1];
1372 b += palette_rgb[p][2];
1375 bgra.b[2] = r/(w*h);
1376 bgra.b[1] = g/(w*h);
1377 bgra.b[0] = b/(w*h);
1379 for (y = 0;y < h;y++)
1381 for (x = 0;x < w;x++)
1383 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1385 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1390 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h);
1391 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1392 Mem_Free(solidpixels);
1393 Mem_Free(alphapixels);
1396 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1398 int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1399 skinframe_t *skinframe;
1401 texture_t *tx, *tx2, *anims[10], *altanims[10];
1403 unsigned char *data, *mtdata;
1405 char mapname[MAX_QPATH], name[MAX_QPATH];
1406 unsigned char zero[4];
1408 memset(zero, 0, sizeof(zero));
1410 loadmodel->data_textures = NULL;
1412 // add two slots for notexture walls and notexture liquids
1415 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1416 m->nummiptex = LittleLong (m->nummiptex);
1417 loadmodel->num_textures = m->nummiptex + 2;
1418 loadmodel->num_texturesperskin = loadmodel->num_textures;
1423 loadmodel->num_textures = 2;
1424 loadmodel->num_texturesperskin = loadmodel->num_textures;
1427 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1429 // fill out all slots with notexture
1430 if (cls.state != ca_dedicated)
1431 skinframe = R_SkinFrame_LoadMissing();
1434 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1436 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1439 if (cls.state != ca_dedicated)
1441 tx->numskinframes = 1;
1442 tx->skinframerate = 1;
1443 tx->skinframes[0] = skinframe;
1444 tx->currentskinframe = tx->skinframes[0];
1446 tx->basematerialflags = MATERIALFLAG_WALL;
1447 if (i == loadmodel->num_textures - 1)
1449 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1450 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1451 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1455 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1456 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1458 tx->currentframe = tx;
1460 // clear water settings
1463 tx->refractfactor = 1;
1464 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1465 tx->reflectfactor = 1;
1466 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1467 tx->r_water_wateralpha = 1;
1468 tx->specularscalemod = 1;
1469 tx->specularpowermod = 1;
1474 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1478 s = loadmodel->name;
1479 if (!strncasecmp(s, "maps/", 5))
1481 FS_StripExtension(s, mapname, sizeof(mapname));
1483 // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1485 // LordHavoc: mostly rewritten map texture loader
1486 for (i = 0;i < m->nummiptex;i++)
1488 dofs[i] = LittleLong(dofs[i]);
1489 if (r_nosurftextures.integer)
1493 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1496 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1498 // copy name, but only up to 16 characters
1499 // (the output buffer can hold more than this, but the input buffer is
1501 for (j = 0;j < 16 && dmiptex->name[j];j++)
1502 name[j] = dmiptex->name[j];
1507 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1508 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1511 mtwidth = LittleLong(dmiptex->width);
1512 mtheight = LittleLong(dmiptex->height);
1514 j = LittleLong(dmiptex->offsets[0]);
1518 if (j < 40 || j + mtwidth * mtheight > l->filelen)
1520 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1523 mtdata = (unsigned char *)dmiptex + j;
1526 if ((mtwidth & 15) || (mtheight & 15))
1527 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1529 // LordHavoc: force all names to lowercase
1530 for (j = 0;name[j];j++)
1531 if (name[j] >= 'A' && name[j] <= 'Z')
1532 name[j] += 'a' - 'A';
1534 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1537 tx = loadmodel->data_textures + i;
1538 strlcpy(tx->name, name, sizeof(tx->name));
1539 tx->width = mtwidth;
1540 tx->height = mtheight;
1542 if (tx->name[0] == '*')
1544 if (!strncmp(tx->name, "*lava", 5))
1546 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1547 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1549 else if (!strncmp(tx->name, "*slime", 6))
1551 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1552 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1556 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1557 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1560 else if (!strncmp(tx->name, "sky", 3))
1562 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1563 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1567 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1568 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1571 if (cls.state != ca_dedicated)
1573 // LordHavoc: HL sky textures are entirely different than quake
1574 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1576 data = loadimagepixelsbgra(tx->name, false, false, r_texture_convertsRGB_skin.integer);
1577 if (data && image_width == image_height * 2)
1579 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1582 else if (mtdata != NULL)
1583 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1587 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);
1589 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);
1592 // did not find external texture, load it from the bsp or wad3
1593 if (loadmodel->brush.ishlbsp)
1595 // internal texture overrides wad
1596 unsigned char *pixels, *freepixels;
1597 pixels = freepixels = NULL;
1599 pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1601 pixels = freepixels = W_GetTextureBGRA(tx->name);
1604 tx->width = image_width;
1605 tx->height = image_height;
1606 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0), pixels, image_width, image_height);
1609 Mem_Free(freepixels);
1611 else if (mtdata) // texture included
1612 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0), false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1614 // if skinframe is still NULL the "missing" texture will be used
1616 tx->skinframes[0] = skinframe;
1619 tx->basematerialflags = MATERIALFLAG_WALL;
1620 if (tx->name[0] == '*')
1622 // LordHavoc: some turbulent textures should not be affected by wateralpha
1623 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1625 // replace the texture with transparent black
1626 Vector4Set(zero, 128, 128, 128, 128);
1627 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1628 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1630 else if (!strncmp(tx->name,"*lava",5)
1631 || !strncmp(tx->name,"*teleport",9)
1632 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1633 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1635 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1636 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1637 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1639 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1641 // replace the texture with black
1642 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1643 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1645 else if (!strncmp(tx->name, "sky", 3))
1646 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1647 else if (!strcmp(tx->name, "caulk"))
1648 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1649 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1650 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1652 // start out with no animation
1653 tx->currentframe = tx;
1654 tx->currentskinframe = tx->skinframes[0];
1658 // sequence the animations
1659 for (i = 0;i < m->nummiptex;i++)
1661 tx = loadmodel->data_textures + i;
1662 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1664 if (tx->anim_total[0] || tx->anim_total[1])
1665 continue; // already sequenced
1667 // find the number of frames in the animation
1668 memset(anims, 0, sizeof(anims));
1669 memset(altanims, 0, sizeof(altanims));
1671 for (j = i;j < m->nummiptex;j++)
1673 tx2 = loadmodel->data_textures + j;
1674 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1678 if (num >= '0' && num <= '9')
1679 anims[num - '0'] = tx2;
1680 else if (num >= 'a' && num <= 'j')
1681 altanims[num - 'a'] = tx2;
1683 Con_Printf("Bad animating texture %s\n", tx->name);
1687 for (j = 0;j < 10;j++)
1694 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1697 for (j = 0;j < max;j++)
1701 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1705 for (j = 0;j < altmax;j++)
1709 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1718 // if there is no alternate animation, duplicate the primary
1719 // animation into the alternate
1721 for (k = 0;k < 10;k++)
1722 altanims[k] = anims[k];
1725 // link together the primary animation
1726 for (j = 0;j < max;j++)
1729 tx2->animated = true;
1730 tx2->anim_total[0] = max;
1731 tx2->anim_total[1] = altmax;
1732 for (k = 0;k < 10;k++)
1734 tx2->anim_frames[0][k] = anims[k];
1735 tx2->anim_frames[1][k] = altanims[k];
1739 // if there really is an alternate anim...
1740 if (anims[0] != altanims[0])
1742 // link together the alternate animation
1743 for (j = 0;j < altmax;j++)
1746 tx2->animated = true;
1747 // the primary/alternate are reversed here
1748 tx2->anim_total[0] = altmax;
1749 tx2->anim_total[1] = max;
1750 for (k = 0;k < 10;k++)
1752 tx2->anim_frames[0][k] = altanims[k];
1753 tx2->anim_frames[1][k] = anims[k];
1760 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1763 unsigned char *in, *out, *data, d;
1764 char litfilename[MAX_QPATH];
1765 char dlitfilename[MAX_QPATH];
1766 fs_offset_t filesize;
1767 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1769 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1770 for (i=0; i<l->filelen; i++)
1771 loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1773 else // LordHavoc: bsp version 29 (normal white lighting)
1775 // LordHavoc: hope is not lost yet, check for a .lit file to load
1776 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1777 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1778 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1779 strlcat (litfilename, ".lit", sizeof (litfilename));
1780 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1781 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1784 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1786 i = LittleLong(((int *)data)[1]);
1789 if (developer_loading.integer)
1790 Con_Printf("loaded %s\n", litfilename);
1791 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1792 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1794 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1797 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1799 i = LittleLong(((int *)data)[1]);
1802 if (developer_loading.integer)
1803 Con_Printf("loaded %s\n", dlitfilename);
1804 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1805 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1806 loadmodel->brushq3.deluxemapping_modelspace = false;
1807 loadmodel->brushq3.deluxemapping = true;
1816 Con_Printf("Unknown .lit file version (%d)\n", i);
1818 else if (filesize == 8)
1819 Con_Print("Empty .lit file, ignoring\n");
1821 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
1828 // LordHavoc: oh well, expand the white lighting data
1831 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1832 in = mod_base + l->fileofs;
1833 out = loadmodel->brushq1.lightdata;
1834 for (i = 0;i < l->filelen;i++)
1844 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1846 loadmodel->brushq1.num_compressedpvs = 0;
1847 loadmodel->brushq1.data_compressedpvs = NULL;
1850 loadmodel->brushq1.num_compressedpvs = l->filelen;
1851 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1852 memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1855 // used only for HalfLife maps
1856 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1858 char key[128], value[4096];
1862 if (!COM_ParseToken_Simple(&data, false, false))
1864 if (com_token[0] != '{')
1868 if (!COM_ParseToken_Simple(&data, false, false))
1870 if (com_token[0] == '}')
1871 break; // end of worldspawn
1872 if (com_token[0] == '_')
1873 strlcpy(key, com_token + 1, sizeof(key));
1875 strlcpy(key, com_token, sizeof(key));
1876 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1877 key[strlen(key)-1] = 0;
1878 if (!COM_ParseToken_Simple(&data, false, false))
1880 dpsnprintf(value, sizeof(value), "%s", com_token);
1881 if (!strcmp("wad", key)) // for HalfLife maps
1883 if (loadmodel->brush.ishlbsp)
1886 for (i = 0;i < (int)sizeof(value);i++)
1887 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1891 for (;i < (int)sizeof(value);i++)
1893 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1894 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1896 else if (value[i] == ';' || value[i] == 0)
1900 W_LoadTextureWadFile(&value[j], false);
1912 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1914 loadmodel->brush.entities = NULL;
1917 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
1918 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1919 loadmodel->brush.entities[l->filelen] = 0;
1920 if (loadmodel->brush.ishlbsp)
1921 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1925 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1931 in = (dvertex_t *)(mod_base + l->fileofs);
1932 if (l->filelen % sizeof(*in))
1933 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1934 count = l->filelen / sizeof(*in);
1935 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1937 loadmodel->brushq1.vertexes = out;
1938 loadmodel->brushq1.numvertexes = count;
1940 for ( i=0 ; i<count ; i++, in++, out++)
1942 out->position[0] = LittleFloat(in->point[0]);
1943 out->position[1] = LittleFloat(in->point[1]);
1944 out->position[2] = LittleFloat(in->point[2]);
1948 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1949 // can be used for this
1951 int SB_ReadInt (unsigned char **buffer)
1954 i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1960 float SB_ReadFloat (unsigned char **buffer)
1968 u.i = SB_ReadInt (buffer);
1972 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1974 unsigned char *index;
1978 index = (unsigned char *)(mod_base + l->fileofs);
1979 if (l->filelen % (48+4*hullinfo->filehulls))
1980 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1982 count = l->filelen / (48+4*hullinfo->filehulls);
1983 out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1985 loadmodel->brushq1.submodels = out;
1986 loadmodel->brush.numsubmodels = count;
1988 for (i = 0; i < count; i++, out++)
1990 // spread out the mins / maxs by a pixel
1991 out->mins[0] = SB_ReadFloat (&index) - 1;
1992 out->mins[1] = SB_ReadFloat (&index) - 1;
1993 out->mins[2] = SB_ReadFloat (&index) - 1;
1994 out->maxs[0] = SB_ReadFloat (&index) + 1;
1995 out->maxs[1] = SB_ReadFloat (&index) + 1;
1996 out->maxs[2] = SB_ReadFloat (&index) + 1;
1997 out->origin[0] = SB_ReadFloat (&index);
1998 out->origin[1] = SB_ReadFloat (&index);
1999 out->origin[2] = SB_ReadFloat (&index);
2000 for (j = 0; j < hullinfo->filehulls; j++)
2001 out->headnode[j] = SB_ReadInt (&index);
2002 out->visleafs = SB_ReadInt (&index);
2003 out->firstface = SB_ReadInt (&index);
2004 out->numfaces = SB_ReadInt (&index);
2008 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2014 in = (dedge_t *)(mod_base + l->fileofs);
2015 if (l->filelen % sizeof(*in))
2016 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2017 count = l->filelen / sizeof(*in);
2018 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2020 loadmodel->brushq1.edges = out;
2021 loadmodel->brushq1.numedges = count;
2023 for ( i=0 ; i<count ; i++, in++, out++)
2025 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2026 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2027 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2029 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);
2030 if(!loadmodel->brushq1.numvertexes)
2031 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2039 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2043 int i, j, k, count, miptex;
2045 in = (texinfo_t *)(mod_base + l->fileofs);
2046 if (l->filelen % sizeof(*in))
2047 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2048 count = l->filelen / sizeof(*in);
2049 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2051 loadmodel->brushq1.texinfo = out;
2052 loadmodel->brushq1.numtexinfo = count;
2054 for (i = 0;i < count;i++, in++, out++)
2056 for (k = 0;k < 2;k++)
2057 for (j = 0;j < 4;j++)
2058 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2060 miptex = LittleLong(in->miptex);
2061 out->flags = LittleLong(in->flags);
2063 out->texture = NULL;
2064 if (loadmodel->data_textures)
2066 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2067 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2069 out->texture = loadmodel->data_textures + miptex;
2071 if (out->flags & TEX_SPECIAL)
2073 // if texture chosen is NULL or the shader needs a lightmap,
2074 // force to notexture water shader
2075 if (out->texture == NULL)
2076 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2080 // if texture chosen is NULL, force to notexture
2081 if (out->texture == NULL)
2082 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2088 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2093 mins[0] = mins[1] = mins[2] = 9999;
2094 maxs[0] = maxs[1] = maxs[2] = -9999;
2096 for (i = 0;i < numverts;i++)
2098 for (j = 0;j < 3;j++, v++)
2108 #define MAX_SUBDIVPOLYTRIANGLES 4096
2109 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2111 static int subdivpolyverts, subdivpolytriangles;
2112 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2113 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2115 static int subdivpolylookupvert(vec3_t v)
2118 for (i = 0;i < subdivpolyverts;i++)
2119 if (subdivpolyvert[i][0] == v[0]
2120 && subdivpolyvert[i][1] == v[1]
2121 && subdivpolyvert[i][2] == v[2])
2123 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2124 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2125 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2126 return subdivpolyverts++;
2129 static void SubdividePolygon(int numverts, float *verts)
2131 int i, i1, i2, i3, f, b, c, p;
2132 vec3_t mins, maxs, front[256], back[256];
2133 float m, *pv, *cv, dist[256], frac;
2136 Host_Error("SubdividePolygon: ran out of verts in buffer");
2138 BoundPoly(numverts, verts, mins, maxs);
2140 for (i = 0;i < 3;i++)
2142 m = (mins[i] + maxs[i]) * 0.5;
2143 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2144 if (maxs[i] - m < 8)
2146 if (m - mins[i] < 8)
2150 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2151 dist[c] = cv[i] - m;
2154 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2158 VectorCopy(pv, front[f]);
2163 VectorCopy(pv, back[b]);
2166 if (dist[p] == 0 || dist[c] == 0)
2168 if ((dist[p] > 0) != (dist[c] > 0) )
2171 frac = dist[p] / (dist[p] - dist[c]);
2172 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2173 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2174 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2180 SubdividePolygon(f, front[0]);
2181 SubdividePolygon(b, back[0]);
2185 i1 = subdivpolylookupvert(verts);
2186 i2 = subdivpolylookupvert(verts + 3);
2187 for (i = 2;i < numverts;i++)
2189 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2191 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2195 i3 = subdivpolylookupvert(verts + i * 3);
2196 subdivpolyindex[subdivpolytriangles][0] = i1;
2197 subdivpolyindex[subdivpolytriangles][1] = i2;
2198 subdivpolyindex[subdivpolytriangles][2] = i3;
2200 subdivpolytriangles++;
2204 //Breaks a polygon up along axial 64 unit
2205 //boundaries so that turbulent and sky warps
2206 //can be done reasonably.
2207 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2213 subdivpolytriangles = 0;
2214 subdivpolyverts = 0;
2215 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2216 if (subdivpolytriangles < 1)
2217 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2219 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2220 mesh->num_vertices = subdivpolyverts;
2221 mesh->num_triangles = subdivpolytriangles;
2222 mesh->vertex = (surfvertex_t *)(mesh + 1);
2223 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2224 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2226 for (i = 0;i < mesh->num_triangles;i++)
2227 for (j = 0;j < 3;j++)
2228 mesh->index[i*3+j] = subdivpolyindex[i][j];
2230 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2232 VectorCopy(subdivpolyvert[i], v->v);
2233 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2234 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2239 extern cvar_t gl_max_lightmapsize;
2240 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2243 msurface_t *surface;
2244 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2245 float texmins[2], texmaxs[2], val;
2246 rtexture_t *lightmaptexture, *deluxemaptexture;
2248 in = (dface_t *)(mod_base + l->fileofs);
2249 if (l->filelen % sizeof(*in))
2250 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2251 count = l->filelen / sizeof(*in);
2252 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2253 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2255 loadmodel->num_surfaces = count;
2257 loadmodel->brushq1.firstrender = true;
2258 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2262 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2264 numedges = (unsigned short)LittleShort(in->numedges);
2265 totalverts += numedges;
2266 totaltris += numedges - 2;
2269 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2271 lightmaptexture = NULL;
2272 deluxemaptexture = r_texture_blanknormalmap;
2274 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2275 totallightmapsamples = 0;
2279 for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2281 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2283 // FIXME: validate edges, texinfo, etc?
2284 firstedge = LittleLong(in->firstedge);
2285 numedges = (unsigned short)LittleShort(in->numedges);
2286 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)
2287 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2288 i = (unsigned short)LittleShort(in->texinfo);
2289 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2290 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2291 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2292 surface->texture = surface->lightmapinfo->texinfo->texture;
2294 planenum = (unsigned short)LittleShort(in->planenum);
2295 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2296 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2298 //surface->flags = surface->texture->flags;
2299 //if (LittleShort(in->side))
2300 // surface->flags |= SURF_PLANEBACK;
2301 //surface->plane = loadmodel->brush.data_planes + planenum;
2303 surface->num_firstvertex = totalverts;
2304 surface->num_vertices = numedges;
2305 surface->num_firsttriangle = totaltris;
2306 surface->num_triangles = numedges - 2;
2307 totalverts += numedges;
2308 totaltris += numedges - 2;
2310 // convert edges back to a normal polygon
2311 for (i = 0;i < surface->num_vertices;i++)
2313 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2315 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2317 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2319 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2320 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2321 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2322 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2323 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2324 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2325 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2326 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2329 for (i = 0;i < surface->num_triangles;i++)
2331 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2332 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2333 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2336 // compile additional data about the surface geometry
2337 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);
2338 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);
2339 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2341 // generate surface extents information
2342 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2343 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2344 for (i = 1;i < surface->num_vertices;i++)
2346 for (j = 0;j < 2;j++)
2348 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2349 texmins[j] = min(texmins[j], val);
2350 texmaxs[j] = max(texmaxs[j], val);
2353 for (i = 0;i < 2;i++)
2355 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2356 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2359 smax = surface->lightmapinfo->extents[0] >> 4;
2360 tmax = surface->lightmapinfo->extents[1] >> 4;
2361 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2362 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2365 for (i = 0;i < MAXLIGHTMAPS;i++)
2366 surface->lightmapinfo->styles[i] = in->styles[i];
2367 surface->lightmaptexture = NULL;
2368 surface->deluxemaptexture = r_texture_blanknormalmap;
2369 i = LittleLong(in->lightofs);
2372 surface->lightmapinfo->samples = NULL;
2374 // give non-lightmapped water a 1x white lightmap
2375 if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2377 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2378 surface->lightmapinfo->styles[0] = 0;
2379 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2383 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2384 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2385 else // LordHavoc: white lighting (bsp version 29)
2387 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2388 if (loadmodel->brushq1.nmaplightdata)
2389 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2392 // check if we should apply a lightmap to this
2393 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2395 if (ssize > 256 || tsize > 256)
2396 Host_Error("Bad surface extents");
2398 if (lightmapsize < ssize)
2399 lightmapsize = ssize;
2400 if (lightmapsize < tsize)
2401 lightmapsize = tsize;
2403 totallightmapsamples += ssize*tsize;
2405 // force lightmap upload on first time seeing the surface
2407 // additionally this is used by the later code to see if a
2408 // lightmap is needed on this surface (rather than duplicating the
2410 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2414 // small maps (such as ammo boxes especially) don't need big lightmap
2415 // textures, so this code tries to guess a good size based on
2416 // totallightmapsamples (size of the lightmaps lump basically), as well as
2417 // trying to max out the size if there is a lot of lightmap data to store
2418 // additionally, never choose a lightmapsize that is smaller than the
2419 // largest surface encountered (as it would fail)
2421 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2424 // now that we've decided the lightmap texture size, we can do the rest
2425 if (cls.state != ca_dedicated)
2427 int stainmapsize = 0;
2428 mod_alloclightmap_state_t allocState;
2430 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2431 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2433 int i, iu, iv, lightmapx = 0, lightmapy = 0;
2434 float u, v, ubase, vbase, uscale, vscale;
2436 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2439 smax = surface->lightmapinfo->extents[0] >> 4;
2440 tmax = surface->lightmapinfo->extents[1] >> 4;
2441 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2442 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2443 stainmapsize += ssize * tsize * 3;
2445 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2447 // allocate a texture pool if we need it
2448 if (loadmodel->texturepool == NULL)
2449 loadmodel->texturepool = R_AllocTexturePool();
2450 // could not find room, make a new lightmap
2451 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2452 loadmodel->brushq3.data_lightmaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2453 loadmodel->brushq3.data_deluxemaps = Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2454 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2455 if (loadmodel->brushq1.nmaplightdata)
2456 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, NULL);
2458 Mod_AllocLightmap_Reset(&allocState);
2459 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2461 surface->lightmaptexture = lightmaptexture;
2462 surface->deluxemaptexture = deluxemaptexture;
2463 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2464 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2466 uscale = 1.0f / (float)lightmapsize;
2467 vscale = 1.0f / (float)lightmapsize;
2468 ubase = lightmapx * uscale;
2469 vbase = lightmapy * vscale;
2471 for (i = 0;i < surface->num_vertices;i++)
2473 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);
2474 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);
2475 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2476 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2477 // LordHavoc: calc lightmap data offset for vertex lighting to use
2480 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2484 if (cl_stainmaps.integer)
2486 // allocate stainmaps for permanent marks on walls and clear white
2487 unsigned char *stainsamples = NULL;
2488 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2489 memset(stainsamples, 255, stainmapsize);
2491 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2493 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2495 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2496 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2497 surface->lightmapinfo->stainsamples = stainsamples;
2498 stainsamples += ssize * tsize * 3;
2503 // generate ushort elements array if possible
2504 if (loadmodel->surfmesh.data_element3s)
2505 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2506 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2509 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2512 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2513 node->parent = parent;
2516 // this is a node, recurse to children
2517 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2518 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2519 // combine supercontents of children
2520 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2525 mleaf_t *leaf = (mleaf_t *)node;
2526 // if this is a leaf, calculate supercontents mask from all collidable
2527 // primitives in the leaf (brushes and collision surfaces)
2528 // also flag if the leaf contains any collision surfaces
2529 leaf->combinedsupercontents = 0;
2530 // combine the supercontents values of all brushes in this leaf
2531 for (j = 0;j < leaf->numleafbrushes;j++)
2532 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2533 // check if this leaf contains any collision surfaces (q3 patches)
2534 for (j = 0;j < leaf->numleafsurfaces;j++)
2536 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2537 if (surface->num_collisiontriangles)
2539 leaf->containscollisionsurfaces = true;
2540 leaf->combinedsupercontents |= surface->texture->supercontents;
2546 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2552 in = (dnode_t *)(mod_base + l->fileofs);
2553 if (l->filelen % sizeof(*in))
2554 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2555 count = l->filelen / sizeof(*in);
2556 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2558 loadmodel->brush.data_nodes = out;
2559 loadmodel->brush.num_nodes = count;
2561 for ( i=0 ; i<count ; i++, in++, out++)
2563 for (j=0 ; j<3 ; j++)
2565 out->mins[j] = LittleShort(in->mins[j]);
2566 out->maxs[j] = LittleShort(in->maxs[j]);
2569 p = LittleLong(in->planenum);
2570 out->plane = loadmodel->brush.data_planes + p;
2572 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2573 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2575 for (j=0 ; j<2 ; j++)
2577 // LordHavoc: this code supports broken bsp files produced by
2578 // arguire qbsp which can produce more than 32768 nodes, any value
2579 // below count is assumed to be a node number, any other value is
2580 // assumed to be a leaf number
2581 p = (unsigned short)LittleShort(in->children[j]);
2584 if (p < loadmodel->brush.num_nodes)
2585 out->children[j] = loadmodel->brush.data_nodes + p;
2588 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2589 // map it to the solid leaf
2590 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2595 // note this uses 65535 intentionally, -1 is leaf 0
2597 if (p < loadmodel->brush.num_leafs)
2598 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2601 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2602 // map it to the solid leaf
2603 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2609 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2612 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2618 in = (dleaf_t *)(mod_base + l->fileofs);
2619 if (l->filelen % sizeof(*in))
2620 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2621 count = l->filelen / sizeof(*in);
2622 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2624 loadmodel->brush.data_leafs = out;
2625 loadmodel->brush.num_leafs = count;
2626 // get visleafs from the submodel data
2627 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2628 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2629 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2630 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2632 for ( i=0 ; i<count ; i++, in++, out++)
2634 for (j=0 ; j<3 ; j++)
2636 out->mins[j] = LittleShort(in->mins[j]);
2637 out->maxs[j] = LittleShort(in->maxs[j]);
2640 // FIXME: this function could really benefit from some error checking
2642 out->contents = LittleLong(in->contents);
2644 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2645 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2646 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2648 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);
2649 out->firstleafsurface = NULL;
2650 out->numleafsurfaces = 0;
2653 out->clusterindex = i - 1;
2654 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2655 out->clusterindex = -1;
2657 p = LittleLong(in->visofs);
2658 // ignore visofs errors on leaf 0 (solid)
2659 if (p >= 0 && out->clusterindex >= 0)
2661 if (p >= loadmodel->brushq1.num_compressedpvs)
2662 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2664 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);
2667 for (j = 0;j < 4;j++)
2668 out->ambient_sound_level[j] = in->ambient_level[j];
2670 // FIXME: Insert caustics here
2674 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2678 const unsigned char *pvs;
2679 // if there's no vis data, assume supported (because everything is visible all the time)
2680 if (!loadmodel->brush.data_pvsclusters)
2682 // check all liquid leafs to see if they can see into empty leafs, if any
2683 // can we can assume this map supports r_wateralpha
2684 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2686 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2688 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2689 for (j = 0;j < loadmodel->brush.num_leafs;j++)
2690 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2697 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2704 in = (dclipnode_t *)(mod_base + l->fileofs);
2705 if (l->filelen % sizeof(*in))
2706 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2707 count = l->filelen / sizeof(*in);
2708 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2710 loadmodel->brushq1.clipnodes = out;
2711 loadmodel->brushq1.numclipnodes = count;
2713 for (i = 1; i < MAX_MAP_HULLS; i++)
2715 hull = &loadmodel->brushq1.hulls[i];
2716 hull->clipnodes = out;
2717 hull->firstclipnode = 0;
2718 hull->lastclipnode = count-1;
2719 hull->planes = loadmodel->brush.data_planes;
2720 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2721 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2722 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2723 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2724 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2725 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2726 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2729 for (i=0 ; i<count ; i++, out++, in++)
2731 out->planenum = LittleLong(in->planenum);
2732 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2733 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2734 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2735 if (out->children[0] >= count)
2736 out->children[0] -= 65536;
2737 if (out->children[1] >= count)
2738 out->children[1] -= 65536;
2739 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2740 Host_Error("Corrupt clipping hull(out of range planenum)");
2744 //Duplicate the drawing hull structure as a clipping hull
2745 static void Mod_Q1BSP_MakeHull0(void)
2752 hull = &loadmodel->brushq1.hulls[0];
2754 in = loadmodel->brush.data_nodes;
2755 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2757 hull->clipnodes = out;
2758 hull->firstclipnode = 0;
2759 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2760 hull->planes = loadmodel->brush.data_planes;
2762 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2764 out->planenum = in->plane - loadmodel->brush.data_planes;
2765 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2766 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2770 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2775 in = (short *)(mod_base + l->fileofs);
2776 if (l->filelen % sizeof(*in))
2777 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2778 loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2779 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2781 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2783 j = (unsigned short) LittleShort(in[i]);
2784 if (j >= loadmodel->num_surfaces)
2785 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2786 loadmodel->brush.data_leafsurfaces[i] = j;
2790 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2795 in = (int *)(mod_base + l->fileofs);
2796 if (l->filelen % sizeof(*in))
2797 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2798 loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2799 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2801 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2802 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2806 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2812 in = (dplane_t *)(mod_base + l->fileofs);
2813 if (l->filelen % sizeof(*in))
2814 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2816 loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2817 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2819 for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2821 out->normal[0] = LittleFloat(in->normal[0]);
2822 out->normal[1] = LittleFloat(in->normal[1]);
2823 out->normal[2] = LittleFloat(in->normal[2]);
2824 out->dist = LittleFloat(in->dist);
2830 static void Mod_Q1BSP_LoadMapBrushes(void)
2834 int submodel, numbrushes;
2835 qboolean firstbrush;
2836 char *text, *maptext;
2837 char mapfilename[MAX_QPATH];
2838 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2839 strlcat (mapfilename, ".map", sizeof (mapfilename));
2840 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
2844 if (!COM_ParseToken_Simple(&data, false, false))
2849 if (!COM_ParseToken_Simple(&data, false, false))
2851 if (com_token[0] != '{')
2857 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2860 if (!COM_ParseToken_Simple(&data, false, false))
2862 if (com_token[0] == '}')
2863 break; // end of entity
2864 if (com_token[0] == '{')
2871 if (submodel > loadmodel->brush.numsubmodels)
2873 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2877 model = loadmodel->brush.submodels[submodel];
2884 if (!COM_ParseToken_Simple(&data, false, false))
2886 if (com_token[0] == '}')
2887 break; // end of brush
2888 // each brush face should be this format:
2889 // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2890 // FIXME: support hl .map format
2891 for (pointnum = 0;pointnum < 3;pointnum++)
2893 COM_ParseToken_Simple(&data, false, false);
2894 for (componentnum = 0;componentnum < 3;componentnum++)
2896 COM_ParseToken_Simple(&data, false, false);
2897 point[pointnum][componentnum] = atof(com_token);
2899 COM_ParseToken_Simple(&data, false, false);
2901 COM_ParseToken_Simple(&data, false, false);
2902 strlcpy(facetexture, com_token, sizeof(facetexture));
2903 COM_ParseToken_Simple(&data, false, false);
2904 //scroll_s = atof(com_token);
2905 COM_ParseToken_Simple(&data, false, false);
2906 //scroll_t = atof(com_token);
2907 COM_ParseToken_Simple(&data, false, false);
2908 //rotate = atof(com_token);
2909 COM_ParseToken_Simple(&data, false, false);
2910 //scale_s = atof(com_token);
2911 COM_ParseToken_Simple(&data, false, false);
2912 //scale_t = atof(com_token);
2913 TriangleNormal(point[0], point[1], point[2], planenormal);
2914 VectorNormalizeDouble(planenormal);
2915 planedist = DotProduct(point[0], planenormal);
2916 //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2926 #define MAX_PORTALPOINTS 64
2928 typedef struct portal_s
2931 mnode_t *nodes[2]; // [0] = front side of plane
2932 struct portal_s *next[2];
2934 double points[3*MAX_PORTALPOINTS];
2935 struct portal_s *chain; // all portals are linked into a list
2939 static memexpandablearray_t portalarray;
2941 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2943 // process only nodes (leafs already had their box calculated)
2947 // calculate children first
2948 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2949 Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2951 // make combined bounding box from children
2952 node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2953 node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2954 node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2955 node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2956 node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2957 node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2960 static void Mod_Q1BSP_FinalizePortals(void)
2962 int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
2966 mleaf_t *leaf, *endleaf;
2968 // tally up portal and point counts and recalculate bounding boxes for all
2969 // leafs (because qbsp is very sloppy)
2970 leaf = loadmodel->brush.data_leafs;
2971 endleaf = leaf + loadmodel->brush.num_leafs;
2972 if (mod_recalculatenodeboxes.integer)
2974 for (;leaf < endleaf;leaf++)
2976 VectorSet(leaf->mins, 2000000000, 2000000000, 2000000000);
2977 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2982 for (portalindex = 0;portalindex < portalrange;portalindex++)
2984 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
2987 // note: this check must match the one below or it will usually corrupt memory
2988 // 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
2989 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2992 numpoints += p->numpoints * 2;
2995 loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
2996 loadmodel->brush.num_portals = numportals;
2997 loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
2998 loadmodel->brush.num_portalpoints = numpoints;
2999 // clear all leaf portal chains
3000 for (i = 0;i < loadmodel->brush.num_leafs;i++)
3001 loadmodel->brush.data_leafs[i].portals = NULL;
3002 // process all portals in the global portal chain, while freeing them
3003 portal = loadmodel->brush.data_portals;
3004 point = loadmodel->brush.data_portalpoints;
3005 for (portalindex = 0;portalindex < portalrange;portalindex++)
3007 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3010 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3012 // note: this check must match the one above or it will usually corrupt memory
3013 // 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
3014 if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3016 // first make the back to front portal(forward portal)
3017 portal->points = point;
3018 portal->numpoints = p->numpoints;
3019 portal->plane.dist = p->plane.dist;
3020 VectorCopy(p->plane.normal, portal->plane.normal);
3021 portal->here = (mleaf_t *)p->nodes[1];
3022 portal->past = (mleaf_t *)p->nodes[0];
3024 for (j = 0;j < portal->numpoints;j++)
3026 VectorCopy(p->points + j*3, point->position);
3029 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3030 PlaneClassify(&portal->plane);
3032 // link into leaf's portal chain
3033 portal->next = portal->here->portals;
3034 portal->here->portals = portal;
3036 // advance to next portal
3039 // then make the front to back portal(backward portal)
3040 portal->points = point;
3041 portal->numpoints = p->numpoints;
3042 portal->plane.dist = -p->plane.dist;
3043 VectorNegate(p->plane.normal, portal->plane.normal);
3044 portal->here = (mleaf_t *)p->nodes[0];
3045 portal->past = (mleaf_t *)p->nodes[1];
3047 for (j = portal->numpoints - 1;j >= 0;j--)
3049 VectorCopy(p->points + j*3, point->position);
3052 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3053 PlaneClassify(&portal->plane);
3055 // link into leaf's portal chain
3056 portal->next = portal->here->portals;
3057 portal->here->portals = portal;
3059 // advance to next portal
3062 // add the portal's polygon points to the leaf bounding boxes
3063 if (mod_recalculatenodeboxes.integer)
3065 for (i = 0;i < 2;i++)
3067 leaf = (mleaf_t *)p->nodes[i];
3068 for (j = 0;j < p->numpoints;j++)
3070 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3071 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3072 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3073 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3074 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3075 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3081 // now recalculate the node bounding boxes from the leafs
3082 if (mod_recalculatenodeboxes.integer)
3083 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3091 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3094 Host_Error("AddPortalToNodes: NULL front node");
3096 Host_Error("AddPortalToNodes: NULL back node");
3097 if (p->nodes[0] || p->nodes[1])
3098 Host_Error("AddPortalToNodes: already included");
3099 // 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
3101 p->nodes[0] = front;
3102 p->next[0] = (portal_t *)front->portals;
3103 front->portals = (mportal_t *)p;
3106 p->next[1] = (portal_t *)back->portals;
3107 back->portals = (mportal_t *)p;
3112 RemovePortalFromNode
3115 static void RemovePortalFromNodes(portal_t *portal)
3119 void **portalpointer;
3121 for (i = 0;i < 2;i++)
3123 node = portal->nodes[i];
3125 portalpointer = (void **) &node->portals;
3128 t = (portal_t *)*portalpointer;
3130 Host_Error("RemovePortalFromNodes: portal not in leaf");
3134 if (portal->nodes[0] == node)
3136 *portalpointer = portal->next[0];
3137 portal->nodes[0] = NULL;
3139 else if (portal->nodes[1] == node)
3141 *portalpointer = portal->next[1];
3142 portal->nodes[1] = NULL;
3145 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3149 if (t->nodes[0] == node)
3150 portalpointer = (void **) &t->next[0];
3151 else if (t->nodes[1] == node)
3152 portalpointer = (void **) &t->next[1];
3154 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3159 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3160 static double *portalpointsbuffer;
3161 static int portalpointsbufferoffset;
3162 static int portalpointsbuffersize;
3163 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3166 mnode_t *front, *back, *other_node;
3167 mplane_t clipplane, *plane;
3168 portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3169 int numfrontpoints, numbackpoints;
3170 double *frontpoints, *backpoints;
3172 // if a leaf, we're done
3176 // get some space for our clipping operations to use
3177 if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3179 portalpointsbuffersize = portalpointsbufferoffset * 2;
3180 portalpointsbuffer = Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3182 frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3183 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3184 backpoints = portalpointsbuffer + portalpointsbufferoffset;
3185 portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3187 plane = node->plane;
3189 front = node->children[0];
3190 back = node->children[1];
3192 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3194 // create the new portal by generating a polygon for the node plane,
3195 // and clipping it by all of the other portals(which came from nodes above this one)
3196 nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3197 nodeportal->plane = *plane;
3199 // 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)
3200 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);
3201 nodeportal->numpoints = 4;
3202 side = 0; // shut up compiler warning
3203 for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3205 clipplane = portal->plane;
3206 if (portal->nodes[0] == portal->nodes[1])
3207 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3208 if (portal->nodes[0] == node)
3210 else if (portal->nodes[1] == node)
3212 clipplane.dist = -clipplane.dist;
3213 VectorNegate(clipplane.normal, clipplane.normal);
3217 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3219 for (i = 0;i < nodeportal->numpoints*3;i++)
3220 frontpoints[i] = nodeportal->points[i];
3221 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);
3222 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3226 if (nodeportal->numpoints < 3)
3228 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3229 nodeportal->numpoints = 0;
3231 else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3233 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3234 nodeportal->numpoints = 0;
3237 AddPortalToNodes(nodeportal, front, back);
3239 // split the portals of this node along this node's plane and assign them to the children of this node
3240 // (migrating the portals downward through the tree)
3241 for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3243 if (portal->nodes[0] == portal->nodes[1])
3244 Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3245 if (portal->nodes[0] == node)
3247 else if (portal->nodes[1] == node)
3250 Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3251 nextportal = portal->next[side];
3252 if (!portal->numpoints)
3255 other_node = portal->nodes[!side];
3256 RemovePortalFromNodes(portal);
3258 // cut the portal into two portals, one on each side of the node plane
3259 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);
3261 if (!numfrontpoints)
3264 AddPortalToNodes(portal, back, other_node);
3266 AddPortalToNodes(portal, other_node, back);
3272 AddPortalToNodes(portal, front, other_node);
3274 AddPortalToNodes(portal, other_node, front);
3278 // the portal is split
3279 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3280 temp = splitportal->chain;
3281 *splitportal = *portal;
3282 splitportal->chain = temp;
3283 for (i = 0;i < numbackpoints*3;i++)
3284 splitportal->points[i] = backpoints[i];
3285 splitportal->numpoints = numbackpoints;
3286 for (i = 0;i < numfrontpoints*3;i++)
3287 portal->points[i] = frontpoints[i];
3288 portal->numpoints = numfrontpoints;
3292 AddPortalToNodes(portal, front, other_node);
3293 AddPortalToNodes(splitportal, back, other_node);
3297 AddPortalToNodes(portal, other_node, front);
3298 AddPortalToNodes(splitportal, other_node, back);
3302 Mod_Q1BSP_RecursiveNodePortals(front);
3303 Mod_Q1BSP_RecursiveNodePortals(back);
3305 portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3308 static void Mod_Q1BSP_MakePortals(void)
3310 Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3311 portalpointsbufferoffset = 0;
3312 portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3313 portalpointsbuffer = Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3314 Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3315 Mem_Free(portalpointsbuffer);
3316 portalpointsbuffer = NULL;
3317 portalpointsbufferoffset = 0;
3318 portalpointsbuffersize = 0;
3319 Mod_Q1BSP_FinalizePortals();
3320 Mem_ExpandableArray_FreeArray(&portalarray);
3323 //Returns PVS data for a given point
3324 //(note: can return NULL)
3325 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3328 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3330 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3331 if (((mleaf_t *)node)->clusterindex >= 0)
3332 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3337 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)
3341 float d = PlaneDiff(org, node->plane);
3343 node = node->children[0];
3344 else if (d < -radius)
3345 node = node->children[1];
3348 // go down both sides
3349 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3350 node = node->children[1];
3353 // if this leaf is in a cluster, accumulate the pvs bits
3354 if (((mleaf_t *)node)->clusterindex >= 0)
3357 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3358 for (i = 0;i < pvsbytes;i++)
3359 pvsbuffer[i] |= pvs[i];
3363 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3364 //of the given point.
3365 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3367 int bytes = model->brush.num_pvsclusterbytes;
3368 bytes = min(bytes, pvsbufferlength);
3369 if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3371 memset(pvsbuffer, 0xFF, bytes);
3375 memset(pvsbuffer, 0, bytes);
3376 Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3380 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3385 VectorSubtract(inmaxs, inmins, size);
3386 if (cmodel->brush.ishlbsp)
3389 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3390 else if (size[0] <= 32)
3392 if (size[2] < 54) // pick the nearest of 36 or 72
3393 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3395 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3398 hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3403 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3404 else if (size[0] <= 32)
3405 hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3407 hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3409 VectorCopy(inmins, outmins);
3410 VectorAdd(inmins, hull->clip_size, outmaxs);
3413 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3418 float dist, modelyawradius, modelradius;
3419 msurface_t *surface;
3420 int numshadowmeshtriangles;
3421 hullinfo_t hullinfo;
3422 int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3423 model_brush_lightstyleinfo_t styleinfo[256];
3424 unsigned char *datapointer;
3426 mod->modeldatatypestring = "Q1BSP";
3428 mod->type = mod_brushq1;
3430 header = (dheader_t *)buffer;
3432 i = LittleLong(header->version);
3433 if (i != BSPVERSION && i != 30)
3434 Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3435 mod->brush.ishlbsp = i == 30;
3437 // fill in hull info
3438 VectorClear (hullinfo.hullsizes[0][0]);
3439 VectorClear (hullinfo.hullsizes[0][1]);
3440 if (mod->brush.ishlbsp)
3442 mod->modeldatatypestring = "HLBSP";
3444 hullinfo.filehulls = 4;
3445 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3446 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3447 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3448 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3449 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3450 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3454 hullinfo.filehulls = 4;
3455 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3456 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3457 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3458 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3462 mod_base = (unsigned char*)buffer;
3463 for (i = 0; i < HEADER_LUMPS; i++)
3465 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3466 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3469 mod->soundfromcenter = true;
3470 mod->TraceBox = Mod_Q1BSP_TraceBox;
3471 mod->TraceLine = Mod_Q1BSP_TraceLine;
3472 mod->TracePoint = Mod_Q1BSP_TracePoint;
3473 mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3474 mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3475 mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3476 mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3477 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3478 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3479 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3480 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3481 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3482 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3483 mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3484 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3485 mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3486 mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3487 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3488 mod->Draw = R_Q1BSP_Draw;
3489 mod->DrawDepth = R_Q1BSP_DrawDepth;
3490 mod->DrawDebug = R_Q1BSP_DrawDebug;
3491 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3492 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3493 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3494 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3495 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3496 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3497 mod->DrawLight = R_Q1BSP_DrawLight;
3501 mod->brush.qw_md4sum = 0;
3502 mod->brush.qw_md4sum2 = 0;
3503 for (i = 0;i < HEADER_LUMPS;i++)
3506 if (i == LUMP_ENTITIES)
3508 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3509 mod->brush.qw_md4sum ^= LittleLong(temp);
3510 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3512 temp = Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
3513 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3516 Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3517 Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3518 Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3519 Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3520 Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3521 Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3522 Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3523 Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3524 Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3525 Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3526 Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3527 // load submodels before leafs because they contain the number of vis leafs
3528 Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3529 Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3530 Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3531 Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3533 // check if the map supports transparent water rendering
3534 loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3536 if (mod->brushq1.data_compressedpvs)
3537 Mem_Free(mod->brushq1.data_compressedpvs);
3538 mod->brushq1.data_compressedpvs = NULL;
3539 mod->brushq1.num_compressedpvs = 0;
3541 Mod_Q1BSP_MakeHull0();
3542 Mod_Q1BSP_MakePortals();
3544 mod->numframes = 2; // regular and alternate animation
3547 // make a single combined shadow mesh to allow optimized shadow volume creation
3548 numshadowmeshtriangles = 0;
3549 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3551 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3552 numshadowmeshtriangles += surface->num_triangles;
3554 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3555 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3556 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));
3557 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true, false);
3558 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
3560 if (loadmodel->brush.numsubmodels)
3561 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3563 // LordHavoc: to clear the fog around the original quake submodel code, I
3565 // first of all, some background info on the submodels:
3566 // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3567 // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3568 // now the weird for loop itself:
3569 // the loop functions in an odd way, on each iteration it sets up the
3570 // current 'mod' model (which despite the confusing code IS the model of
3571 // the number i), at the end of the loop it duplicates the model to become
3572 // the next submodel, and loops back to set up the new submodel.
3574 // LordHavoc: now the explanation of my sane way (which works identically):
3575 // set up the world model, then on each submodel copy from the world model
3576 // and set up the submodel with the respective model info.
3577 totalstylesurfaces = 0;
3579 for (i = 0;i < mod->brush.numsubmodels;i++)
3581 memset(stylecounts, 0, sizeof(stylecounts));
3582 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3584 surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3585 for (j = 0;j < MAXLIGHTMAPS;j++)
3586 stylecounts[surface->lightmapinfo->styles[j]]++;
3588 for (k = 0;k < 255;k++)
3592 totalstylesurfaces += stylecounts[k];
3595 datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3596 for (i = 0;i < mod->brush.numsubmodels;i++)
3598 // LordHavoc: this code was originally at the end of this loop, but
3599 // has been transformed to something more readable at the start here.
3604 // duplicate the basic information
3605 dpsnprintf(name, sizeof(name), "*%i", i);
3606 mod = Mod_FindName(name, loadmodel->name);
3607 // copy the base model to this one
3609 // rename the clone back to its proper name
3610 strlcpy(mod->name, name, sizeof(mod->name));
3611 mod->brush.parentmodel = loadmodel;
3612 // textures and memory belong to the main model
3613 mod->texturepool = NULL;
3614 mod->mempool = NULL;
3615 mod->brush.GetPVS = NULL;
3616 mod->brush.FatPVS = NULL;
3617 mod->brush.BoxTouchingPVS = NULL;
3618 mod->brush.BoxTouchingLeafPVS = NULL;
3619 mod->brush.BoxTouchingVisibleLeafs = NULL;
3620 mod->brush.FindBoxClusters = NULL;
3621 mod->brush.LightPoint = NULL;
3622 mod->brush.AmbientSoundLevelsForPoint = NULL;
3625 mod->brush.submodel = i;
3627 if (loadmodel->brush.submodels)
3628 loadmodel->brush.submodels[i] = mod;
3630 bm = &mod->brushq1.submodels[i];
3632 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3633 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3635 mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3636 mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3639 mod->firstmodelsurface = bm->firstface;
3640 mod->nummodelsurfaces = bm->numfaces;
3642 // set node/leaf parents for this submodel
3643 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
3645 // make the model surface list (used by shadowing/lighting)
3646 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
3647 Mod_MakeSortedSurfaces(mod);
3649 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
3650 // (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)
3651 VectorCopy(bm->mins, mod->normalmins);
3652 VectorCopy(bm->maxs, mod->normalmaxs);
3653 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
3654 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
3655 modelyawradius = dist*dist+modelyawradius*modelyawradius;
3656 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
3657 modelradius = modelyawradius + modelradius * modelradius;
3658 modelyawradius = sqrt(modelyawradius);
3659 modelradius = sqrt(modelradius);
3660 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
3661 mod->yawmins[2] = mod->normalmins[2];
3662 mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius;
3663 mod->yawmaxs[2] = mod->normalmaxs[2];
3664 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3665 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3666 mod->radius = modelradius;
3667 mod->radius2 = modelradius * modelradius;
3669 // this gets altered below if sky or water is used
3670 mod->DrawSky = NULL;
3671 mod->DrawAddWaterPlanes = NULL;
3673 // scan surfaces for sky and water and flag the submodel as possessing these features or not
3674 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
3675 if (mod->nummodelsurfaces)
3677 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3678 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3680 if (j < mod->nummodelsurfaces)
3681 mod->DrawSky = R_Q1BSP_DrawSky;
3683 for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3684 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
3686 if (j < mod->nummodelsurfaces)
3687 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
3689 // build lightstyle update chains
3690 // (used to rapidly mark lightmapupdateflags on many surfaces
3691 // when d_lightstylevalue changes)
3692 memset(stylecounts, 0, sizeof(stylecounts));
3693 for (k = 0;k < mod->nummodelsurfaces;k++)
3695 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3696 for (j = 0;j < MAXLIGHTMAPS;j++)
3697 stylecounts[surface->lightmapinfo->styles[j]]++;
3699 mod->brushq1.num_lightstyles = 0;
3700 for (k = 0;k < 255;k++)
3704 styleinfo[mod->brushq1.num_lightstyles].style = k;
3705 styleinfo[mod->brushq1.num_lightstyles].value = 0;
3706 styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
3707 styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
3708 remapstyles[k] = mod->brushq1.num_lightstyles;
3709 mod->brushq1.num_lightstyles++;
3712 for (k = 0;k < mod->nummodelsurfaces;k++)
3714 surface = mod->data_surfaces + mod->firstmodelsurface + k;
3715 for (j = 0;j < MAXLIGHTMAPS;j++)
3717 if (surface->lightmapinfo->styles[j] != 255)
3719 int r = remapstyles[surface->lightmapinfo->styles[j]];
3720 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
3724 mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
3725 memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
3729 // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3730 Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3732 //mod->brushq1.num_visleafs = bm->visleafs;
3734 if (mod_q1bsp_polygoncollisions.integer)
3736 Mod_MakeCollisionBIH(mod, true);
3737 // point traces and contents checks still use the bsp tree
3738 mod->TraceLine = Mod_CollisionBIH_TraceLine;
3739 mod->TraceBox = Mod_CollisionBIH_TraceBox;
3742 // generate VBOs and other shared data before cloning submodels
3746 Mod_Q1BSP_LoadMapBrushes();
3747 //Mod_Q1BSP_ProcessLightList();
3751 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);
3754 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3758 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3765 in = (void *)(mod_base + l->fileofs);
3766 if (l->filelen % sizeof(*in))
3767 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3768 count = l->filelen / sizeof(*in);
3769 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3772 loadmodel->num = count;
3774 for (i = 0;i < count;i++, in++, out++)
3780 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3787 in = (void *)(mod_base + l->fileofs);
3788 if (l->filelen % sizeof(*in))
3789 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3790 count = l->filelen / sizeof(*in);
3791 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3794 loadmodel->num = count;
3796 for (i = 0;i < count;i++, in++, out++)
3802 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3809 in = (void *)(mod_base + l->fileofs);
3810 if (l->filelen % sizeof(*in))
3811 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3812 count = l->filelen / sizeof(*in);
3813 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3816 loadmodel->num = count;
3818 for (i = 0;i < count;i++, in++, out++)
3824 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3831 in = (void *)(mod_base + l->fileofs);
3832 if (l->filelen % sizeof(*in))
3833 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3834 count = l->filelen / sizeof(*in);
3835 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3838 loadmodel->num = count;
3840 for (i = 0;i < count;i++, in++, out++)
3846 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3853 in = (void *)(mod_base + l->fileofs);
3854 if (l->filelen % sizeof(*in))
3855 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3856 count = l->filelen / sizeof(*in);
3857 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3860 loadmodel->num = count;
3862 for (i = 0;i < count;i++, in++, out++)
3868 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3875 in = (void *)(mod_base + l->fileofs);
3876 if (l->filelen % sizeof(*in))
3877 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3878 count = l->filelen / sizeof(*in);
3879 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3882 loadmodel->num = count;
3884 for (i = 0;i < count;i++, in++, out++)
3890 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3897 in = (void *)(mod_base + l->fileofs);
3898 if (l->filelen % sizeof(*in))
3899 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3900 count = l->filelen / sizeof(*in);
3901 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3904 loadmodel->num = count;
3906 for (i = 0;i < count;i++, in++, out++)
3912 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3919 in = (void *)(mod_base + l->fileofs);
3920 if (l->filelen % sizeof(*in))
3921 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3922 count = l->filelen / sizeof(*in);
3923 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3926 loadmodel->num = count;
3928 for (i = 0;i < count;i++, in++, out++)
3934 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3941 in = (void *)(mod_base + l->fileofs);
3942 if (l->filelen % sizeof(*in))
3943 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3944 count = l->filelen / sizeof(*in);
3945 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3948 loadmodel->num = count;
3950 for (i = 0;i < count;i++, in++, out++)
3956 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3963 in = (void *)(mod_base + l->fileofs);
3964 if (l->filelen % sizeof(*in))
3965 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3966 count = l->filelen / sizeof(*in);
3967 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3970 loadmodel->num = count;
3972 for (i = 0;i < count;i++, in++, out++)
3978 static void Mod_Q2BSP_LoadEdges(lump_t *l)
3985 in = (void *)(mod_base + l->fileofs);
3986 if (l->filelen % sizeof(*in))
3987 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
3988 count = l->filelen / sizeof(*in);
3989 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3992 loadmodel->num = count;
3994 for (i = 0;i < count;i++, in++, out++)
4000 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4007 in = (void *)(mod_base + l->fileofs);
4008 if (l->filelen % sizeof(*in))
4009 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4010 count = l->filelen / sizeof(*in);
4011 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4014 loadmodel->num = count;
4016 for (i = 0;i < count;i++, in++, out++)
4022 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4029 in = (void *)(mod_base + l->fileofs);
4030 if (l->filelen % sizeof(*in))
4031 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4032 count = l->filelen / sizeof(*in);
4033 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4036 loadmodel->num = count;
4038 for (i = 0;i < count;i++, in++, out++)
4044 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4051 in = (void *)(mod_base + l->fileofs);
4052 if (l->filelen % sizeof(*in))
4053 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4054 count = l->filelen / sizeof(*in);
4055 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4058 loadmodel->num = count;
4060 for (i = 0;i < count;i++, in++, out++)
4066 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4073 in = (void *)(mod_base + l->fileofs);
4074 if (l->filelen % sizeof(*in))
4075 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4076 count = l->filelen / sizeof(*in);
4077 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4080 loadmodel->num = count;
4082 for (i = 0;i < count;i++, in++, out++)
4088 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4095 in = (void *)(mod_base + l->fileofs);
4096 if (l->filelen % sizeof(*in))
4097 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4098 count = l->filelen / sizeof(*in);
4099 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4102 loadmodel->num = count;
4104 for (i = 0;i < count;i++, in++, out++)
4110 static void Mod_Q2BSP_LoadModels(lump_t *l)
4117 in = (void *)(mod_base + l->fileofs);
4118 if (l->filelen % sizeof(*in))
4119 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4120 count = l->filelen / sizeof(*in);
4121 out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4124 loadmodel->num = count;
4126 for (i = 0;i < count;i++, in++, out++)
4132 void static Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4135 q2dheader_t *header;
4137 Host_Error("Mod_Q2BSP_Load: not yet implemented");
4139 mod->modeldatatypestring = "Q2BSP";
4141 mod->type = mod_brushq2;
4143 header = (q2dheader_t *)buffer;
4145 i = LittleLong(header->version);
4146 if (i != Q2BSPVERSION)
4147 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4149 mod_base = (unsigned char *)header;
4151 // swap all the lumps
4152 for (i = 0;i < (int) sizeof(*header) / 4;i++)
4153 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4155 mod->brush.qw_md4sum = 0;
4156 mod->brush.qw_md4sum2 = 0;
4157 for (i = 0;i < Q2HEADER_LUMPS;i++)
4159 if (i == Q2LUMP_ENTITIES)
4161 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4162 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4164 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4167 Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4168 Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4169 Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4170 Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4171 Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4172 Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4173 Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4174 Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4175 Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4176 Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4177 Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4178 Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4179 Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4180 Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4181 Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4182 Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4183 Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4184 // LordHavoc: must go last because this makes the submodels
4185 Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4188 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4189 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4191 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4194 char key[128], value[MAX_INPUTLINE];
4196 loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4197 loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4198 loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4201 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4202 memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4203 loadmodel->brush.entities[l->filelen] = 0;
4204 data = loadmodel->brush.entities;
4205 // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4206 // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4207 loadmodel->brushq3.deluxemapping = false;
4208 if (data && COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{')
4212 if (!COM_ParseToken_Simple(&data, false, false))
4214 if (com_token[0] == '}')
4215 break; // end of worldspawn
4216 if (com_token[0] == '_')
4217 strlcpy(key, com_token + 1, sizeof(key));
4219 strlcpy(key, com_token, sizeof(key));
4220 while (key[strlen(key)-1] == ' ') // remove trailing spaces
4221 key[strlen(key)-1] = 0;
4222 if (!COM_ParseToken_Simple(&data, false, false))
4224 strlcpy(value, com_token, sizeof(value));
4225 if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4227 #if _MSC_VER >= 1400
4228 #define sscanf sscanf_s
4231 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4232 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4234 VectorSet(v, 64, 64, 128);
4235 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4236 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]);
4237 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4238 VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4241 else if (!strcmp("deluxeMaps", key))
4243 if (!strcmp(com_token, "1"))
4245 loadmodel->brushq3.deluxemapping = true;
4246 loadmodel->brushq3.deluxemapping_modelspace = true;
4248 else if (!strcmp(com_token, "2"))
4250 loadmodel->brushq3.deluxemapping = true;
4251 loadmodel->brushq3.deluxemapping_modelspace = false;
4258 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4264 in = (q3dtexture_t *)(mod_base + l->fileofs);
4265 if (l->filelen % sizeof(*in))
4266 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4267 count = l->filelen / sizeof(*in);
4268 out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4270 loadmodel->data_textures = out;
4271 loadmodel->num_textures = count;
4272 loadmodel->num_texturesperskin = loadmodel->num_textures;
4274 for (i = 0;i < count;i++)
4276 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4277 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4278 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4279 if (cls.state != ca_dedicated)
4281 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS);
4282 // restore the surfaceflags and supercontents
4283 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4284 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4289 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4295 in = (q3dplane_t *)(mod_base + l->fileofs);
4296 if (l->filelen % sizeof(*in))
4297 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4298 count = l->filelen / sizeof(*in);
4299 out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4301 loadmodel->brush.data_planes = out;
4302 loadmodel->brush.num_planes = count;
4304 for (i = 0;i < count;i++, in++, out++)
4306 out->normal[0] = LittleFloat(in->normal[0]);
4307 out->normal[1] = LittleFloat(in->normal[1]);
4308 out->normal[2] = LittleFloat(in->normal[2]);
4309 out->dist = LittleFloat(in->dist);
4314 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4317 q3mbrushside_t *out;
4320 in = (q3dbrushside_t *)(mod_base + l->fileofs);
4321 if (l->filelen % sizeof(*in))
4322 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4323 count = l->filelen / sizeof(*in);
4324 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4326 loadmodel->brush.data_brushsides = out;
4327 loadmodel->brush.num_brushsides = count;
4329 for (i = 0;i < count;i++, in++, out++)
4331 n = LittleLong(in->planeindex);
4332 if (n < 0 || n >= loadmodel->brush.num_planes)
4333 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4334 out->plane = loadmodel->brush.data_planes + n;
4335 n = LittleLong(in->textureindex);
4336 if (n < 0 || n >= loadmodel->num_textures)
4337 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4338 out->texture = loadmodel->data_textures + n;
4342 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4344 q3dbrushside_ig_t *in;
4345 q3mbrushside_t *out;
4348 in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4349 if (l->filelen % sizeof(*in))
4350 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4351 count = l->filelen / sizeof(*in);
4352 out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4354 loadmodel->brush.data_brushsides = out;
4355 loadmodel->brush.num_brushsides = count;
4357 for (i = 0;i < count;i++, in++, out++)
4359 n = LittleLong(in->planeindex);
4360 if (n < 0 || n >= loadmodel->brush.num_planes)
4361 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4362 out->plane = loadmodel->brush.data_planes + n;
4363 n = LittleLong(in->textureindex);
4364 if (n < 0 || n >= loadmodel->num_textures)
4365 Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4366 out->texture = loadmodel->data_textures + n;
4370 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4374 int i, j, n, c, count, maxplanes, q3surfaceflags;
4375 colplanef_t *planes;
4377 in = (q3dbrush_t *)(mod_base + l->fileofs);
4378 if (l->filelen % sizeof(*in))
4379 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4380 count = l->filelen / sizeof(*in);
4381 out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4383 loadmodel->brush.data_brushes = out;
4384 loadmodel->brush.num_brushes = count;
4389 for (i = 0;i < count;i++, in++, out++)
4391 n = LittleLong(in->firstbrushside);
4392 c = LittleLong(in->numbrushsides);
4393 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4394 Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4395 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4396 out->numbrushsides = c;
4397 n = LittleLong(in->textureindex);
4398 if (n < 0 || n >= loadmodel->num_textures)
4399 Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4400 out->texture = loadmodel->data_textures + n;
4402 // make a list of mplane_t structs to construct a colbrush from
4403 if (maxplanes < out->numbrushsides)
4405 maxplanes = out->numbrushsides;
4408 planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4411 for (j = 0;j < out->numbrushsides;j++)
4413 VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4414 planes[j].dist = out->firstbrushside[j].plane->dist;
4415 planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4416 planes[j].texture = out->firstbrushside[j].texture;
4417 q3surfaceflags |= planes[j].q3surfaceflags;
4419 // make the colbrush from the planes
4420 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4422 // this whole loop can take a while (e.g. on redstarrepublic4)
4423 CL_KeepaliveMessage(false);
4429 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4435 in = (q3deffect_t *)(mod_base + l->fileofs);
4436 if (l->filelen % sizeof(*in))
4437 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4438 count = l->filelen / sizeof(*in);
4439 out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4441 loadmodel->brushq3.data_effects = out;
4442 loadmodel->brushq3.num_effects = count;
4444 for (i = 0;i < count;i++, in++, out++)
4446 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4447 n = LittleLong(in->brushindex);
4448 if (n >= loadmodel->brush.num_brushes)
4450 Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4453 out->brushindex = n;
4454 out->unknown = LittleLong(in->unknown);
4458 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4463 in = (q3dvertex_t *)(mod_base + l->fileofs);
4464 if (l->filelen % sizeof(*in))
4465 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4466 loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4467 loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4468 loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4469 loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4470 loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4471 loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4473 for (i = 0;i < count;i++, in++)
4475 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4476 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4477 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4478 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4479 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4480 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4481 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4482 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4483 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4484 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4485 // svector/tvector are calculated later in face loading
4486 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4487 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4488 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4489 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4493 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4499 in = (int *)(mod_base + l->fileofs);
4500 if (l->filelen % sizeof(int[3]))
4501 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4502 count = l->filelen / sizeof(*in);
4504 if(!loadmodel->brushq3.num_vertices)
4507 Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4508 loadmodel->brushq3.num_triangles = 0;
4512 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4513 loadmodel->brushq3.num_triangles = count / 3;
4514 loadmodel->brushq3.data_element3i = out;
4516 for (i = 0;i < count;i++, in++, out++)
4518 *out = LittleLong(*in);
4519 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4521 Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4527 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4529 q3dlightmap_t *input_pointer;
4530 int i, j, k, count, power, power2, endlightmap, mergewidth, mergeheight;
4533 unsigned char *convertedpixels;
4534 char mapname[MAX_QPATH];
4535 int size, bytesperpixel, rgbmap[3];
4537 unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4539 // defaults for q3bsp
4546 loadmodel->brushq3.lightmapsize = 128;
4548 if (cls.state == ca_dedicated)
4551 if(mod_q3bsp_nolightmaps.integer)
4557 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4558 if (developer_loading.integer)
4559 Con_Printf("Using internal lightmaps\n");
4560 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4561 if (l->filelen % sizeof(*input_pointer))
4562 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4563 count = l->filelen / sizeof(*input_pointer);
4564 for(i = 0; i < count; ++i)
4565 inpixels[i] = input_pointer[i].rgb;
4569 // no internal lightmaps
4570 // try external lightmaps
4571 if (developer_loading.integer)
4572 Con_Printf("Using external lightmaps\n");
4573 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4574 inpixels[0] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, 0), false, false, false);
4578 // using EXTERNAL lightmaps instead
4579 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4581 Mem_Free(inpixels[0]);
4582 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4592 for(count = 1; ; ++count)
4594 inpixels[count] = loadimagepixelsbgra(va("%s/lm_%04d", mapname, count), false, false, false);
4595 if(!inpixels[count])
4596 break; // we got all of them
4597 if(image_width != size || image_height != size)
4599 for(i = 0; i <= count; ++i)
4600 Mem_Free(inpixels[i]);
4601 Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4606 convertedpixels = (unsigned char *) Mem_Alloc(tempmempool, size*size*4);
4607 loadmodel->brushq3.lightmapsize = size;
4608 loadmodel->brushq3.num_originallightmaps = count;
4610 // now check the surfaces to see if any of them index an odd numbered
4611 // lightmap, if so this is not a deluxemapped bsp file
4613 // also check what lightmaps are actually used, because q3map2 sometimes
4614 // (always?) makes an unused one at the end, which
4615 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4616 // reason when only one lightmap is used, which can throw off the
4617 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4618 // to see if the second lightmap is blank, if so it is not deluxemapped.
4619 // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
4620 // in Mod_Q3BSP_LoadEntities was failed
4621 if (!loadmodel->brushq3.deluxemapping)
4623 loadmodel->brushq3.deluxemapping = !(count & 1);
4624 loadmodel->brushq3.deluxemapping_modelspace = true;
4626 if (loadmodel->brushq3.deluxemapping)
4628 int facecount = faceslump->filelen / sizeof(q3dface_t);
4629 q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
4630 for (i = 0;i < facecount;i++)
4632 j = LittleLong(faces[i].lightmapindex);
4635 endlightmap = max(endlightmap, j + 1);
4636 if ((j & 1) || j + 1 >= count)
4638 loadmodel->brushq3.deluxemapping = false;
4645 // q3map2 sometimes (or always?) makes a second blank lightmap for no
4646 // reason when only one lightmap is used, which can throw off the
4647 // deluxemapping detection method, so check 2-lightmap bsp's specifically
4648 // to see if the second lightmap is blank, if so it is not deluxemapped.
4650 // further research has shown q3map2 sometimes creates a deluxemap and two
4651 // blank lightmaps, which must be handled properly as well
4652 if (endlightmap == 1 && count > 1)
4655 for (i = 0;i < size*size;i++)
4657 if (c[bytesperpixel*i + rgbmap[0]])
4659 if (c[bytesperpixel*i + rgbmap[1]])
4661 if (c[bytesperpixel*i + rgbmap[2]])
4666 // all pixels in the unused lightmap were black...
4667 loadmodel->brushq3.deluxemapping = false;
4672 Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
4674 // figure out what the most reasonable merge power is within limits
4676 loadmodel->brushq3.num_lightmapmergepower = 0;
4678 for(i = 0; (128 << i) < size; ++i)
4680 // i is now 0 for 128, 1 for 256, etc
4682 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++)
4683 loadmodel->brushq3.num_lightmapmergepower = power;
4685 loadmodel->brushq3.num_lightmapmerge = 1 << loadmodel->brushq3.num_lightmapmergepower;
4687 loadmodel->brushq3.num_mergedlightmaps = ((count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) + (1 << (loadmodel->brushq3.num_lightmapmergepower * 2)) - 1) >> (loadmodel->brushq3.num_lightmapmergepower * 2);
4688 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4689 if (loadmodel->brushq3.deluxemapping)
4690 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4692 // allocate a texture pool if we need it
4693 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
4694 loadmodel->texturepool = R_AllocTexturePool();
4696 power = loadmodel->brushq3.num_lightmapmergepower;
4698 for (i = 0;i < count;i++)
4700 // figure out which merged lightmap texture this fits into
4701 int lightmapindex = i >> (loadmodel->brushq3.deluxemapping + power2);
4702 for (k = 0;k < size*size;k++)
4704 convertedpixels[k*4+0] = inpixels[i][k*bytesperpixel+rgbmap[0]];
4705 convertedpixels[k*4+1] = inpixels[i][k*bytesperpixel+rgbmap[1]];
4706 convertedpixels[k*4+2] = inpixels[i][k*bytesperpixel+rgbmap[2]];
4707 convertedpixels[k*4+3] = 255;
4709 if (loadmodel->brushq3.num_lightmapmergepower > 0)
4711 // if the lightmap has not been allocated yet, create it
4712 if (!loadmodel->brushq3.data_lightmaps[lightmapindex])
4714 // create a lightmap only as large as necessary to hold the
4715 // remaining size*size blocks
4716 // if there are multiple merged lightmap textures then they will
4717 // all be full size except the last one which may be smaller
4718 // because it only needs to the remaining blocks, and it will often
4719 // be odd sizes like 2048x512 due to only being 25% full or so.
4720 j = (count >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) - (lightmapindex << power2);
4721 for (mergewidth = 1;mergewidth < j && mergewidth < (1 << power);mergewidth *= 2)
4723 for (mergeheight = 1;mergewidth*mergeheight < j && mergeheight < (1 << power);mergeheight *= 2)
4725 if (developer_loading.integer)
4726 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);
4727 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);
4728 if (loadmodel->brushq3.data_deluxemaps)
4729 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);
4731 mergewidth = R_TextureWidth(loadmodel->brushq3.data_lightmaps[lightmapindex]) / size;
4732 mergeheight = R_TextureHeight(loadmodel->brushq3.data_lightmaps[lightmapindex]) / size;
4733 j = (i >> (loadmodel->brushq3.deluxemapping ? 1 : 0)) & ((1 << power2) - 1);
4734 if (loadmodel->brushq3.deluxemapping && (i & 1))
4735 R_UpdateTexture(loadmodel->brushq3.data_deluxemaps[lightmapindex], convertedpixels, (j % mergewidth) * size, (j / mergewidth) * size, size, size);
4737 R_UpdateTexture(loadmodel->brushq3.data_lightmaps [lightmapindex], convertedpixels, (j % mergewidth) * size, (j / mergewidth) * size, size, size);
4741 // figure out which merged lightmap texture this fits into
4742 if (loadmodel->brushq3.deluxemapping && (i & 1))
4743 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);
4745 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);
4749 Mem_Free(convertedpixels);
4752 for(i = 0; i < count; ++i)
4753 Mem_Free(inpixels[i]);
4757 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
4762 *collisionstride = stride;
4765 cnt = (num_triangles + stride - 1) / stride;
4766 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
4767 for(j = 0; j < cnt; ++j)
4769 mins = &((*collisionbbox6f)[6 * j + 0]);
4770 maxs = &((*collisionbbox6f)[6 * j + 3]);
4771 for(k = 0; k < stride; ++k)
4773 tri = j * stride + k;
4774 if(tri >= num_triangles)
4776 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
4777 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
4778 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
4779 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
4780 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
4781 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
4782 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
4783 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
4784 if(vert[0] < mins[0]) mins[0] = vert[0];
4785 if(vert[1] < mins[1]) mins[1] = vert[1];
4786 if(vert[2] < mins[2]) mins[2] = vert[2];
4787 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4788 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4789 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4790 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
4791 if(vert[0] < mins[0]) mins[0] = vert[0];
4792 if(vert[1] < mins[1]) mins[1] = vert[1];
4793 if(vert[2] < mins[2]) mins[2] = vert[2];
4794 if(vert[0] > maxs[0]) maxs[0] = vert[0];
4795 if(vert[1] > maxs[1]) maxs[1] = vert[1];
4796 if(vert[2] > maxs[2]) maxs[2] = vert[2];
4801 *collisionbbox6f = NULL;
4804 typedef struct patchtess_s
4808 // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
4811 float *originalvertex3f;
4814 #define PATCHTESS_SAME_LODGROUP(a,b) \
4816 (a).lodgroup[0] == (b).lodgroup[0] && \
4817 (a).lodgroup[1] == (b).lodgroup[1] && \
4818 (a).lodgroup[2] == (b).lodgroup[2] && \
4819 (a).lodgroup[3] == (b).lodgroup[3] && \
4820 (a).lodgroup[4] == (b).lodgroup[4] && \
4821 (a).lodgroup[5] == (b).lodgroup[5] \
4824 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4826 q3dface_t *in, *oldin;
4827 msurface_t *out, *oldout;
4828 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;
4829 float lightmaptcbase[2], lightmaptcscale[2];
4830 //int *originalelement3i;
4831 //int *originalneighbor3i;
4832 float *originalvertex3f;
4833 //float *originalsvector3f;
4834 //float *originaltvector3f;
4835 float *originalnormal3f;
4836 float *originalcolor4f;
4837 float *originaltexcoordtexture2f;
4838 float *originaltexcoordlightmap2f;
4839 float *surfacecollisionvertex3f;
4840 int *surfacecollisionelement3i;
4842 patchtess_t *patchtess = NULL;
4843 int patchtesscount = 0;
4846 in = (q3dface_t *)(mod_base + l->fileofs);
4847 if (l->filelen % sizeof(*in))
4848 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4849 count = l->filelen / sizeof(*in);
4850 out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4852 loadmodel->data_surfaces = out;
4853 loadmodel->num_surfaces = count;
4856 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
4864 for (;i < count;i++, in++, out++)
4866 // check face type first
4867 type = LittleLong(in->type);
4868 if (type != Q3FACETYPE_FLAT
4869 && type != Q3FACETYPE_PATCH
4870 && type != Q3FACETYPE_MESH
4871 && type != Q3FACETYPE_FLARE)
4873 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4877 n = LittleLong(in->textureindex);
4878 if (n < 0 || n >= loadmodel->num_textures)
4880 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4883 out->texture = loadmodel->data_textures + n;
4884 n = LittleLong(in->effectindex);
4885 if (n < -1 || n >= loadmodel->brushq3.num_effects)
4887 if (developer_extra.integer)
4888 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4894 out->effect = loadmodel->brushq3.data_effects + n;
4896 if (cls.state != ca_dedicated)
4898 out->lightmaptexture = NULL;
4899 out->deluxemaptexture = r_texture_blanknormalmap;
4900 n = LittleLong(in->lightmapindex);
4903 else if (n >= loadmodel->brushq3.num_originallightmaps)
4905 if(loadmodel->brushq3.num_originallightmaps != 0)
4906 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
4911 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> (loadmodel->brushq3.num_lightmapmergepower * 2 + loadmodel->brushq3.deluxemapping)];
4912 if (loadmodel->brushq3.deluxemapping)
4913 out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> (loadmodel->brushq3.num_lightmapmergepower * 2 + loadmodel->brushq3.deluxemapping)];
4917 firstvertex = LittleLong(in->firstvertex);
4918 numvertices = LittleLong(in->numvertices);
4919 firstelement = LittleLong(in->firstelement);
4920 numtriangles = LittleLong(in->numelements) / 3;
4921 if (numtriangles * 3 != LittleLong(in->numelements))
4923 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));
4926 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4928 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);
4931 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4933 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);
4938 case Q3FACETYPE_FLAT:
4939 case Q3FACETYPE_MESH:
4940 // no processing necessary
4942 case Q3FACETYPE_PATCH:
4943 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4944 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4945 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))
4947 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4950 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4952 // convert patch to Q3FACETYPE_MESH
4953 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4954 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4955 // bound to user settings
4956 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4957 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4958 // bound to sanity settings
4959 xtess = bound(0, xtess, 1024);
4960 ytess = bound(0, ytess, 1024);
4962 // lower quality collision patches! Same procedure as before, but different cvars
4963 // convert patch to Q3FACETYPE_MESH
4964 cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4965 cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4966 // bound to user settings
4967 cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
4968 cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
4969 // bound to sanity settings
4970 cxtess = bound(0, cxtess, 1024);
4971 cytess = bound(0, cytess, 1024);
4973 // store it for the LOD grouping step
4974 patchtess[patchtesscount].info.xsize = patchsize[0];
4975 patchtess[patchtesscount].info.ysize = patchsize[1];
4976 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
4977 patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
4978 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
4979 patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
4981 patchtess[patchtesscount].surface_id = i;
4982 patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
4983 patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
4984 patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
4985 patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
4986 patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
4987 patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
4988 patchtess[patchtesscount].originalvertex3f = originalvertex3f;
4991 case Q3FACETYPE_FLARE:
4992 if (developer_extra.integer)
4993 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
4997 out->num_vertices = numvertices;
4998 out->num_triangles = numtriangles;
4999 meshvertices += out->num_vertices;
5000 meshtriangles += out->num_triangles;
5003 // Fix patches tesselations so that they make no seams
5007 for(i = 0; i < patchtesscount; ++i)
5009 for(j = i+1; j < patchtesscount; ++j)
5011 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5014 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5021 // Calculate resulting number of triangles
5022 collisionvertices = 0;
5023 collisiontriangles = 0;
5024 for(i = 0; i < patchtesscount; ++i)
5026 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5027 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5028 numvertices = finalwidth * finalheight;
5029 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5031 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5032 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5033 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5034 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5036 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5037 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5038 numvertices = finalwidth * finalheight;
5039 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5041 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5042 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5043 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5044 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5050 Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5051 if (collisiontriangles)
5053 loadmodel->brush.data_collisionvertex3f = Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5054 loadmodel->brush.data_collisionelement3i = Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5058 collisionvertices = 0;
5059 collisiontriangles = 0;
5060 for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5062 if (out->num_vertices < 3 || out->num_triangles < 1)
5065 type = LittleLong(in->type);
5066 firstvertex = LittleLong(in->firstvertex);
5067 firstelement = LittleLong(in->firstelement);
5068 out->num_firstvertex = meshvertices;
5069 out->num_firsttriangle = meshtriangles;
5070 out->num_firstcollisiontriangle = collisiontriangles;
5073 case Q3FACETYPE_FLAT:
5074 case Q3FACETYPE_MESH:
5075 // no processing necessary, except for lightmap merging
5076 for (j = 0;j < out->num_vertices;j++)
5078 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5079 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5080 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5081 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5082 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5083 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5084 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5085 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5086 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5087 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5088 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5089 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5090 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5091 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5093 for (j = 0;j < out->num_triangles*3;j++)
5094 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5096 case Q3FACETYPE_PATCH:
5097 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5098 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5099 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5100 originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5101 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5102 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5103 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5105 xtess = ytess = cxtess = cytess = -1;
5106 for(j = 0; j < patchtesscount; ++j)
5107 if(patchtess[j].surface_id == i)
5109 xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5110 ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5111 cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5112 cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5117 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5118 xtess = ytess = cxtess = cytess = 0;
5121 finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5122 finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5123 finalvertices = finalwidth * finalheight;
5124 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5125 type = Q3FACETYPE_MESH;
5126 // generate geometry
5127 // (note: normals are skipped because they get recalculated)
5128 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5129 Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5130 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5131 Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5132 Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5133 Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5135 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);
5137 if (developer_extra.integer)
5139 if (out->num_triangles < finaltriangles)
5140 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);
5142 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);
5144 // q3map does not put in collision brushes for curves... ugh
5145 // build the lower quality collision geometry
5146 finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5147 finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5148 finalvertices = finalwidth * finalheight;
5149 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5151 // legacy collision geometry implementation
5152 out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5153 out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5154 out->num_collisionvertices = finalvertices;
5155 out->num_collisiontriangles = finaltriangles;
5156 Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5157 Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5159 //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5160 Mod_SnapVertices(3, out->num_collisionvertices, out->deprecatedq3data_collisionvertex3f, 1);
5162 oldnumtriangles = out->num_triangles;
5163 oldnumtriangles2 = out->num_collisiontriangles;
5164 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5166 // now optimize the collision mesh by finding triangle bboxes...
5167 Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5168 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);
5170 // store collision geometry for BIH collision tree
5171 surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5172 surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5173 Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5174 Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5175 Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5176 oldnumtriangles = out->num_triangles;
5177 oldnumtriangles2 = out->num_collisiontriangles;
5178 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5180 if (developer_extra.integer)
5181 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);
5183 collisionvertices += finalvertices;
5184 collisiontriangles += out->num_collisiontriangles;
5189 meshvertices += out->num_vertices;
5190 meshtriangles += out->num_triangles;
5191 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5192 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)
5194 if (invalidelements)
5196 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);
5197 for (j = 0;j < out->num_triangles * 3;j++)
5199 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5200 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)
5201 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5205 // calculate a bounding box
5206 VectorClear(out->mins);
5207 VectorClear(out->maxs);
5208 if (out->num_vertices)
5210 if (cls.state != ca_dedicated && out->lightmaptexture)
5212 // figure out which part of the merged lightmap this fits into
5213 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5214 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5215 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5216 lightmapindex &= mergewidth * mergeheight - 1;
5217 lightmaptcscale[0] = 1.0f / mergewidth;
5218 lightmaptcscale[1] = 1.0f / mergeheight;
5219 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5220 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5221 // modify the lightmap texcoords to match this region of the merged lightmap
5222 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5224 v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5225 v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5228 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5229 VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5230 for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5232 out->mins[0] = min(out->mins[0], v[0]);
5233 out->maxs[0] = max(out->maxs[0], v[0]);
5234 out->mins[1] = min(out->mins[1], v[1]);
5235 out->maxs[1] = max(out->maxs[1], v[1]);
5236 out->mins[2] = min(out->mins[2], v[2]);
5237 out->maxs[2] = max(out->maxs[2], v[2]);
5239 out->mins[0] -= 1.0f;
5240 out->mins[1] -= 1.0f;
5241 out->mins[2] -= 1.0f;
5242 out->maxs[0] += 1.0f;
5243 out->maxs[1] += 1.0f;
5244 out->maxs[2] += 1.0f;
5246 // set lightmap styles for consistency with q1bsp
5247 //out->lightmapinfo->styles[0] = 0;
5248 //out->lightmapinfo->styles[1] = 255;
5249 //out->lightmapinfo->styles[2] = 255;
5250 //out->lightmapinfo->styles[3] = 255;
5255 for (;i < count;i++, out++)
5257 if(out->num_vertices && out->num_triangles)
5259 if(out->num_vertices == 0)
5260 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no vertices, ignoring\n", i);
5261 if(out->num_triangles == 0)
5262 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d has no triangles, ignoring\n", i);
5265 // for per pixel lighting
5266 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);
5268 // generate ushort elements array if possible
5269 if (loadmodel->surfmesh.data_element3s)
5270 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5271 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5273 // free the no longer needed vertex data
5274 loadmodel->brushq3.num_vertices = 0;
5275 if (loadmodel->brushq3.data_vertex3f)
5276 Mem_Free(loadmodel->brushq3.data_vertex3f);
5277 loadmodel->brushq3.data_vertex3f = NULL;
5278 loadmodel->brushq3.data_normal3f = NULL;
5279 loadmodel->brushq3.data_texcoordtexture2f = NULL;
5280 loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5281 loadmodel->brushq3.data_color4f = NULL;
5282 // free the no longer needed triangle data
5283 loadmodel->brushq3.num_triangles = 0;
5284 if (loadmodel->brushq3.data_element3i)
5285 Mem_Free(loadmodel->brushq3.data_element3i);
5286 loadmodel->brushq3.data_element3i = NULL;
5289 Mem_Free(patchtess);
5292 static void Mod_Q3BSP_LoadModels(lump_t *l)
5296 int i, j, n, c, count;
5298 in = (q3dmodel_t *)(mod_base + l->fileofs);
5299 if (l->filelen % sizeof(*in))
5300 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5301 count = l->filelen / sizeof(*in);
5302 out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5304 loadmodel->brushq3.data_models = out;
5305 loadmodel->brushq3.num_models = count;
5307 for (i = 0;i < count;i++, in++, out++)
5309 for (j = 0;j < 3;j++)
5311 out->mins[j] = LittleFloat(in->mins[j]);
5312 out->maxs[j] = LittleFloat(in->maxs[j]);
5314 n = LittleLong(in->firstface);
5315 c = LittleLong(in->numfaces);
5316 if (n < 0 || n + c > loadmodel->num_surfaces)
5317 Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5320 n = LittleLong(in->firstbrush);
5321 c = LittleLong(in->numbrushes);
5322 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5323 Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5324 out->firstbrush = n;
5325 out->numbrushes = c;
5329 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5335 in = (int *)(mod_base + l->fileofs);
5336 if (l->filelen % sizeof(*in))
5337 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5338 count = l->filelen / sizeof(*in);
5339 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5341 loadmodel->brush.data_leafbrushes = out;
5342 loadmodel->brush.num_leafbrushes = count;
5344 for (i = 0;i < count;i++, in++, out++)
5346 n = LittleLong(*in);
5347 if (n < 0 || n >= loadmodel->brush.num_brushes)
5348 Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5353 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5359 in = (int *)(mod_base + l->fileofs);
5360 if (l->filelen % sizeof(*in))
5361 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5362 count = l->filelen / sizeof(*in);
5363 out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5365 loadmodel->brush.data_leafsurfaces = out;
5366 loadmodel->brush.num_leafsurfaces = count;
5368 for (i = 0;i < count;i++, in++, out++)
5370 n = LittleLong(*in);
5371 if (n < 0 || n >= loadmodel->num_surfaces)
5372 Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5377 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5381 int i, j, n, c, count;
5383 in = (q3dleaf_t *)(mod_base + l->fileofs);
5384 if (l->filelen % sizeof(*in))
5385 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5386 count = l->filelen / sizeof(*in);
5387 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5389 loadmodel->brush.data_leafs = out;
5390 loadmodel->brush.num_leafs = count;
5392 for (i = 0;i < count;i++, in++, out++)
5396 out->clusterindex = LittleLong(in->clusterindex);
5397 out->areaindex = LittleLong(in->areaindex);
5398 for (j = 0;j < 3;j++)
5400 // yes the mins/maxs are ints
5401 out->mins[j] = LittleLong(in->mins[j]) - 1;
5402 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5404 n = LittleLong(in->firstleafface);
5405 c = LittleLong(in->numleaffaces);
5406 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5407 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5408 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5409 out->numleafsurfaces = c;
5410 n = LittleLong(in->firstleafbrush);
5411 c = LittleLong(in->numleafbrushes);
5412 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5413 Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5414 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5415 out->numleafbrushes = c;
5419 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5425 in = (q3dnode_t *)(mod_base + l->fileofs);
5426 if (l->filelen % sizeof(*in))
5427 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5428 count = l->filelen / sizeof(*in);
5429 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5431 loadmodel->brush.data_nodes = out;
5432 loadmodel->brush.num_nodes = count;
5434 for (i = 0;i < count;i++, in++, out++)
5437 n = LittleLong(in->planeindex);
5438 if (n < 0 || n >= loadmodel->brush.num_planes)
5439 Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5440 out->plane = loadmodel->brush.data_planes + n;
5441 for (j = 0;j < 2;j++)
5443 n = LittleLong(in->childrenindex[j]);
5446 if (n >= loadmodel->brush.num_nodes)
5447 Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5448 out->children[j] = loadmodel->brush.data_nodes + n;
5453 if (n >= loadmodel->brush.num_leafs)
5454 Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5455 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5458 for (j = 0;j < 3;j++)
5460 // yes the mins/maxs are ints
5461 out->mins[j] = LittleLong(in->mins[j]) - 1;
5462 out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5466 // set the parent pointers
5467 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5470 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5473 q3dlightgrid_t *out;
5476 in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5477 if (l->filelen % sizeof(*in))
5478 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5479 loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5480 loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5481 loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5482 loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5483 loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5484 loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5485 loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5486 loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5487 loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5488 loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5489 loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5490 loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5491 count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5492 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]);
5493 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]);
5495 // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5498 if (l->filelen < count * (int)sizeof(*in))
5500 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]);
5501 return; // ignore the grid if we cannot understand it
5503 if (l->filelen != count * (int)sizeof(*in))
5504 Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5505 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5506 loadmodel->brushq3.data_lightgrid = out;
5507 loadmodel->brushq3.num_lightgrid = count;
5508 // no swapping or validation necessary
5509 memcpy(out, in, count * (int)sizeof(*out));
5513 static void Mod_Q3BSP_LoadPVS(lump_t *l)
5518 if (l->filelen == 0)
5521 // unvised maps often have cluster indices even without pvs, so check
5522 // leafs to find real number of clusters
5523 loadmodel->brush.num_pvsclusters = 1;
5524 for (i = 0;i < loadmodel->brush.num_leafs;i++)
5525 loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
5528 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
5529 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5530 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5531 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
5535 in = (q3dpvs_t *)(mod_base + l->fileofs);
5537 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
5539 loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
5540 loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
5541 if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
5542 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
5543 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
5544 if (l->filelen < totalchains + (int)sizeof(*in))
5545 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);
5547 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
5548 memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
5551 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
5553 int i, j, k, index[3];
5554 float transformed[3], blend1, blend2, blend, stylescale;
5555 q3dlightgrid_t *a, *s;
5557 // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
5558 stylescale = r_refdef.scene.rtlightstylevalue[0];
5560 if (!model->brushq3.num_lightgrid)
5562 ambientcolor[0] = stylescale;
5563 ambientcolor[1] = stylescale;
5564 ambientcolor[2] = stylescale;
5568 Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
5569 //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
5570 //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
5571 transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
5572 transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
5573 transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
5574 index[0] = (int)floor(transformed[0]);
5575 index[1] = (int)floor(transformed[1]);
5576 index[2] = (int)floor(transformed[2]);
5577 //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
5579 // now lerp the values
5580 VectorClear(diffusenormal);
5581 a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
5582 for (k = 0;k < 2;k++)
5584 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
5585 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
5587 for (j = 0;j < 2;j++)
5589 blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
5590 if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
5592 for (i = 0;i < 2;i++)
5594 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
5595 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
5597 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
5598 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
5599 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
5600 // this uses the mod_md3_sin table because the values are
5601 // already in the 0-255 range, the 64+ bias fetches a cosine
5602 // instead of a sine value
5603 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5604 diffusenormal[1] += blend * (mod_md3_sin[ s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
5605 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
5606 //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)));
5611 // normalize the light direction before turning
5612 VectorNormalize(diffusenormal);
5613 //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]);
5616 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
5619 double midf, mid[3];
5625 // find the point distances
5626 mplane_t *plane = node->plane;
5627 if (plane->type < 3)
5629 t1 = p1[plane->type] - plane->dist;
5630 t2 = p2[plane->type] - plane->dist;
5634 t1 = DotProduct (plane->normal, p1) - plane->dist;
5635 t2 = DotProduct (plane->normal, p2) - plane->dist;
5642 node = node->children[1];
5651 node = node->children[0];
5657 midf = t1 / (t1 - t2);
5658 VectorLerp(p1, midf, p2, mid);
5660 // recurse both sides, front side first
5661 // return 2 if empty is followed by solid (hit something)
5662 // do not return 2 if both are solid or both empty,
5663 // or if start is solid and end is empty
5664 // as these degenerate cases usually indicate the eye is in solid and
5665 // should see the target point anyway
5666 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ], p1, mid);
5669 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
5674 return ((mleaf_t *)node)->clusterindex < 0;
5677 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
5679 if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
5682 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
5683 return trace.fraction == 1;
5687 double tracestart[3], traceend[3];
5688 VectorCopy(start, tracestart);
5689 VectorCopy(end, traceend);
5690 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
5694 static void Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace_t *trace, dp_model_t *model, int nodenum, const vec3_t point)
5696 const bih_leaf_t *leaf;
5697 const bih_node_t *node;
5698 const colbrushf_t *brush;
5700 while (nodenum >= 0)
5702 node = model->collision_bih.nodes + nodenum;
5703 axis = node->type - BIH_SPLITX;
5704 if (point[axis] <= node->backmax)
5706 if (point[axis] >= node->frontmin)
5707 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, node->front, point);
5708 nodenum = node->back;
5710 else if (point[axis] >= node->frontmin)
5711 nodenum = node->front;
5712 else // no overlap with either child? just return
5715 if (!model->collision_bih.leafs)
5717 leaf = model->collision_bih.leafs + (-1-nodenum);
5722 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5723 Collision_TracePointBrushFloat(trace, point, brush);
5726 // collision triangle - skipped because they have no volume
5729 // render triangle - skipped because they have no volume
5736 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)
5738 const bih_leaf_t *leaf;
5739 const bih_node_t *node;
5740 const colbrushf_t *brush;
5742 const texture_t *texture;
5756 segmentmins[0] = min(start[0], end[0]);
5757 segmentmins[1] = min(start[1], end[1]);
5758 segmentmins[2] = min(start[2], end[2]);
5759 segmentmaxs[0] = max(start[0], end[0]);
5760 segmentmaxs[1] = max(start[1], end[1]);
5761 segmentmaxs[2] = max(start[2], end[2]);
5762 while (nodenum >= 0)
5764 node = model->collision_bih.nodes + nodenum;
5766 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
5769 axis = node->type - BIH_SPLITX;
5771 if (segmentmins[axis] <= node->backmax)
5773 if (segmentmaxs[axis] >= node->frontmin)
5774 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5775 nodenum = node->back;
5777 else if (segmentmaxs[axis] >= node->frontmin)
5778 nodenum = node->front;
5780 return; // trace falls between children
5782 frontdist1 = start[axis] - node->backmax;
5783 frontdist2 = end[axis] - node->backmax;
5784 backdist1 = start[axis] - node->frontmin;
5785 backdist2 = end[axis] - node->frontmin;
5798 // start end START END
5799 nodenum = node->front;
5802 // START end START END
5803 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5804 VectorLerp(start, frontfrac, end, clipped[0]);
5806 segmentmins[0] = min(start[0], end[0]);
5807 segmentmins[1] = min(start[1], end[1]);
5808 segmentmins[2] = min(start[2], end[2]);
5809 segmentmaxs[0] = max(start[0], end[0]);
5810 segmentmaxs[1] = max(start[1], end[1]);
5811 segmentmaxs[2] = max(start[2], end[2]);
5812 nodenum = node->front;
5815 // start END START END
5816 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5817 VectorLerp(start, frontfrac, end, clipped[0]);
5819 segmentmins[0] = min(start[0], end[0]);
5820 segmentmins[1] = min(start[1], end[1]);
5821 segmentmins[2] = min(start[2], end[2]);
5822 segmentmaxs[0] = max(start[0], end[0]);
5823 segmentmaxs[1] = max(start[1], end[1]);
5824 segmentmaxs[2] = max(start[2], end[2]);
5825 nodenum = node->front;
5828 // START END START END
5829 return; // line falls in gap between children
5831 // start end start END
5832 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5833 backfrac = backdist1 / (backdist1 - backdist2);
5834 VectorLerp(start, backfrac, end, clipped[0]);
5836 segmentmins[0] = min(start[0], end[0]);
5837 segmentmins[1] = min(start[1], end[1]);
5838 segmentmins[2] = min(start[2], end[2]);
5839 segmentmaxs[0] = max(start[0], end[0]);
5840 segmentmaxs[1] = max(start[1], end[1]);
5841 segmentmaxs[2] = max(start[2], end[2]);
5842 nodenum = node->back;
5845 // START end start END
5846 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5847 VectorLerp(start, frontfrac, end, clipped[1]);
5848 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5849 backfrac = backdist1 / (backdist1 - backdist2);
5850 VectorLerp(start, backfrac, end, clipped[0]);
5852 segmentmins[0] = min(start[0], end[0]);
5853 segmentmins[1] = min(start[1], end[1]);
5854 segmentmins[2] = min(start[2], end[2]);
5855 segmentmaxs[0] = max(start[0], end[0]);
5856 segmentmaxs[1] = max(start[1], end[1]);
5857 segmentmaxs[2] = max(start[2], end[2]);
5858 nodenum = node->back;
5861 // start END start END
5862 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5863 VectorLerp(start, frontfrac, end, clipped[1]);
5864 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5865 backfrac = backdist1 / (backdist1 - backdist2);
5866 VectorLerp(start, backfrac, end, clipped[0]);
5868 segmentmins[0] = min(start[0], end[0]);
5869 segmentmins[1] = min(start[1], end[1]);
5870 segmentmins[2] = min(start[2], end[2]);
5871 segmentmaxs[0] = max(start[0], end[0]);
5872 segmentmaxs[1] = max(start[1], end[1]);
5873 segmentmaxs[2] = max(start[2], end[2]);
5874 nodenum = node->back;
5877 // START END start END
5878 backfrac = backdist1 / (backdist1 - backdist2);
5879 VectorLerp(start, backfrac, end, clipped[0]);
5881 segmentmins[0] = min(start[0], end[0]);
5882 segmentmins[1] = min(start[1], end[1]);
5883 segmentmins[2] = min(start[2], end[2]);
5884 segmentmaxs[0] = max(start[0], end[0]);
5885 segmentmaxs[1] = max(start[1], end[1]);
5886 segmentmaxs[2] = max(start[2], end[2]);
5887 nodenum = node->back;
5890 // start end START end
5891 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5892 backfrac = backdist1 / (backdist1 - backdist2);
5893 VectorLerp(start, backfrac, end, clipped[0]);
5895 segmentmins[0] = min(start[0], end[0]);
5896 segmentmins[1] = min(start[1], end[1]);
5897 segmentmins[2] = min(start[2], end[2]);
5898 segmentmaxs[0] = max(start[0], end[0]);
5899 segmentmaxs[1] = max(start[1], end[1]);
5900 segmentmaxs[2] = max(start[2], end[2]);
5901 nodenum = node->back;
5904 // START end START end
5905 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5906 VectorLerp(start, frontfrac, end, clipped[1]);
5907 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5908 backfrac = backdist1 / (backdist1 - backdist2);
5909 VectorLerp(start, backfrac, end, clipped[0]);
5911 segmentmins[0] = min(start[0], end[0]);
5912 segmentmins[1] = min(start[1], end[1]);
5913 segmentmins[2] = min(start[2], end[2]);
5914 segmentmaxs[0] = max(start[0], end[0]);
5915 segmentmaxs[1] = max(start[1], end[1]);
5916 segmentmaxs[2] = max(start[2], end[2]);
5917 nodenum = node->back;
5920 // start END START end
5921 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5922 VectorLerp(start, frontfrac, end, clipped[1]);
5923 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5924 backfrac = backdist1 / (backdist1 - backdist2);
5925 VectorLerp(start, backfrac, end, clipped[0]);
5927 segmentmins[0] = min(start[0], end[0]);
5928 segmentmins[1] = min(start[1], end[1]);
5929 segmentmins[2] = min(start[2], end[2]);
5930 segmentmaxs[0] = max(start[0], end[0]);
5931 segmentmaxs[1] = max(start[1], end[1]);
5932 segmentmaxs[2] = max(start[2], end[2]);
5933 nodenum = node->back;
5936 // START END START end
5937 backfrac = backdist1 / (backdist1 - backdist2);
5938 VectorLerp(start, backfrac, end, clipped[0]);
5940 segmentmins[0] = min(start[0], end[0]);
5941 segmentmins[1] = min(start[1], end[1]);
5942 segmentmins[2] = min(start[2], end[2]);
5943 segmentmaxs[0] = max(start[0], end[0]);
5944 segmentmaxs[1] = max(start[1], end[1]);
5945 segmentmaxs[2] = max(start[2], end[2]);
5946 nodenum = node->back;
5949 // start end start end
5950 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, end, linestart, lineend);
5951 nodenum = node->back;
5954 // START end start end
5955 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5956 VectorLerp(start, frontfrac, end, clipped[1]);
5957 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, clipped[1], end, linestart, lineend);
5958 nodenum = node->back;
5961 // start END start end
5962 frontfrac = frontdist1 / (frontdist1 - frontdist2);
5963 VectorLerp(start, frontfrac, end, clipped[1]);
5964 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, node->front, start, clipped[1], linestart, lineend);
5965 nodenum = node->back;
5968 // START END start end
5969 nodenum = node->back;
5974 if (!model->collision_bih.leafs)
5976 leaf = model->collision_bih.leafs + (-1-nodenum);
5978 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
5985 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
5986 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
5989 // collision triangle
5990 if (!mod_q3bsp_curves_collisions.integer)
5992 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
5993 texture = model->data_textures + leaf->textureindex;
5994 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);
5998 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
5999 texture = model->data_textures + leaf->textureindex;
6000 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);
6007 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)
6009 const bih_leaf_t *leaf;
6010 const bih_node_t *node;
6011 const colbrushf_t *brush;
6013 const texture_t *texture;
6015 while (nodenum >= 0)
6017 node = model->collision_bih.nodes + nodenum;
6018 axis = node->type - BIH_SPLITX;
6021 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6024 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6025 nodenum = node->back;
6028 if (segmentmins[axis] <= node->backmax)
6030 if (segmentmaxs[axis] >= node->frontmin)
6031 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, node->front, thisbrush_start, thisbrush_end, segmentmins, segmentmaxs);
6032 nodenum = node->back;
6034 else if (segmentmaxs[axis] >= node->frontmin)
6035 nodenum = node->front;
6037 return; // trace falls between children
6039 if (!model->collision_bih.leafs)
6041 leaf = model->collision_bih.leafs + (-1-nodenum);
6043 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6050 brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6051 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6054 // collision triangle
6055 if (!mod_q3bsp_curves_collisions.integer)
6057 e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6058 texture = model->data_textures + leaf->textureindex;
6059 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);
6063 e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6064 texture = model->data_textures + leaf->textureindex;
6065 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);
6072 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)
6074 memset(trace, 0, sizeof(*trace));
6075 trace->fraction = 1;
6076 trace->realfraction = 1;
6077 trace->hitsupercontentsmask = hitsupercontentsmask;
6078 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6081 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)
6083 if (VectorCompare(start, end))
6085 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6089 memset(trace, 0, sizeof(*trace));
6090 trace->fraction = 1;
6091 trace->realfraction = 1;
6092 trace->hitsupercontentsmask = hitsupercontentsmask;
6093 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6096 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)
6098 float segmentmins[3], segmentmaxs[3];
6099 colboxbrushf_t thisbrush_start, thisbrush_end;
6100 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6102 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6104 vec3_t shiftstart, shiftend;
6105 VectorAdd(start, boxmins, shiftstart);
6106 VectorAdd(end, boxmins, shiftend);
6107 if (VectorCompare(start, end))
6108 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6111 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6112 VectorSubtract(trace->endpos, boxmins, trace->endpos);
6117 // box trace, performed as brush trace
6118 memset(trace, 0, sizeof(*trace));
6119 trace->fraction = 1;
6120 trace->realfraction = 1;
6121 trace->hitsupercontentsmask = hitsupercontentsmask;
6122 segmentmins[0] = min(start[0], end[0]) + boxmins[0] - 1;
6123 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6124 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6125 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6126 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6127 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6128 VectorAdd(start, boxmins, boxstartmins);
6129 VectorAdd(start, boxmaxs, boxstartmaxs);
6130 VectorAdd(end, boxmins, boxendmins);
6131 VectorAdd(end, boxmaxs, boxendmaxs);
6132 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6133 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6134 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6137 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6140 Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6141 return trace.startsupercontents;
6144 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)
6147 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6149 int hitsupercontents;
6150 VectorSet(end, start[0], start[1], model->normalmins[2]);
6152 memset(trace, 0, sizeof(*trace));
6153 trace->fraction = 1;
6154 trace->realfraction = 1;
6155 trace->hitsupercontentsmask = hitsupercontentsmask;
6157 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6158 hitsupercontents = trace->hitsupercontents;
6159 memset(trace, 0, sizeof(*trace));
6160 trace->fraction = 1;
6161 trace->realfraction = 1;
6162 trace->hitsupercontentsmask = hitsupercontentsmask;
6163 trace->startsupercontents = hitsupercontents;
6167 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6170 // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6173 VectorSet(end, start[0], start[1], model->normalmins[2]);
6174 memset(&trace, 0, sizeof(trace));
6176 trace.realfraction = 1;
6177 trace.hitsupercontentsmask = 0;
6178 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(&trace, model, model->collision_bih.rootnode, start, end, start, end);
6179 return trace.hitsupercontents;
6185 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6190 // find which leaf the point is in
6192 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6193 // point trace the brushes
6194 leaf = (mleaf_t *)node;
6195 for (i = 0;i < leaf->numleafbrushes;i++)
6197 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6198 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6200 brush->markframe = markframe;
6201 Collision_TracePointBrushFloat(trace, point, brush);
6204 // can't do point traces on curves (they have no thickness)
6207 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)
6209 int i, startside, endside;
6210 float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6212 msurface_t *surface;
6215 // walk the tree until we hit a leaf, recursing for any split cases
6219 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6221 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6222 node = node->children[1];
6224 // abort if this part of the bsp tree can not be hit by this trace
6225 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6227 plane = node->plane;
6228 // axial planes are much more common than non-axial, so an optimized
6229 // axial case pays off here
6230 if (plane->type < 3)
6232 dist1 = start[plane->type] - plane->dist;
6233 dist2 = end[plane->type] - plane->dist;
6237 dist1 = DotProduct(start, plane->normal) - plane->dist;
6238 dist2 = DotProduct(end, plane->normal) - plane->dist;
6240 startside = dist1 < 0;
6241 endside = dist2 < 0;
6242 if (startside == endside)
6244 // most of the time the line fragment is on one side of the plane
6245 node = node->children[startside];
6249 // line crosses node plane, split the line
6250 dist1 = PlaneDiff(linestart, plane);
6251 dist2 = PlaneDiff(lineend, plane);
6252 midfrac = dist1 / (dist1 - dist2);
6253 VectorLerp(linestart, midfrac, lineend, mid);
6254 // take the near side first
6255 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6256 // if we found an impact on the front side, don't waste time
6257 // exploring the far side
6258 if (midfrac <= trace->realfraction)
6259 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6264 // abort if this part of the bsp tree can not be hit by this trace
6265 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6268 nodesegmentmins[0] = min(start[0], end[0]) - 1;
6269 nodesegmentmins[1] = min(start[1], end[1]) - 1;
6270 nodesegmentmins[2] = min(start[2], end[2]) - 1;
6271 nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6272 nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6273 nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6274 // line trace the brushes
6275 leaf = (mleaf_t *)node;
6277 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6280 for (i = 0;i < leaf->numleafbrushes;i++)
6282 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6283 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6285 brush->markframe = markframe;
6286 Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6289 // can't do point traces on curves (they have no thickness)
6290 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6292 // line trace the curves
6293 for (i = 0;i < leaf->numleafsurfaces;i++)
6295 surface = model->data_surfaces + leaf->firstleafsurface[i];
6296 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6298 surface->deprecatedq3collisionmarkframe = markframe;
6299 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);
6305 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)
6311 msurface_t *surface;
6313 float nodesegmentmins[3], nodesegmentmaxs[3];
6314 // walk the tree until we hit a leaf, recursing for any split cases
6318 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6320 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6321 node = node->children[1];
6323 // abort if this part of the bsp tree can not be hit by this trace
6324 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6326 plane = node->plane;
6327 // axial planes are much more common than non-axial, so an optimized
6328 // axial case pays off here
6329 if (plane->type < 3)
6331 // this is an axial plane, compare bounding box directly to it and
6332 // recurse sides accordingly
6333 // recurse down node sides
6334 // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6335 //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6336 //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6337 sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6341 // this is a non-axial plane, so check if the start and end boxes
6342 // are both on one side of the plane to handle 'diagonal' cases
6343 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6347 // segment crosses plane
6348 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6351 // if sides == 0 then the trace itself is bogus (Not A Number values),
6352 // in this case we simply pretend the trace hit nothing
6354 return; // ERROR: NAN bounding box!
6355 // take whichever side the segment box is on
6356 node = node->children[sides - 1];
6359 // abort if this part of the bsp tree can not be hit by this trace
6360 // if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6362 nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6363 nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6364 nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6365 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6366 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6367 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6369 leaf = (mleaf_t *)node;
6371 if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6374 for (i = 0;i < leaf->numleafbrushes;i++)
6376 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6377 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6379 brush->markframe = markframe;
6380 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6383 if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6385 for (i = 0;i < leaf->numleafsurfaces;i++)
6387 surface = model->data_surfaces + leaf->firstleafsurface[i];
6388 if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6390 surface->deprecatedq3collisionmarkframe = markframe;
6391 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);
6398 static int markframe = 0;
6400 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)
6404 memset(trace, 0, sizeof(*trace));
6405 trace->fraction = 1;
6406 trace->realfraction = 1;
6407 trace->hitsupercontentsmask = hitsupercontentsmask;
6408 if (mod_collision_bih.integer)
6409 Mod_CollisionBIH_TracePoint_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start);
6410 else if (model->brush.submodel)
6412 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6413 if (brush->colbrushf)
6414 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6417 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6420 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)
6423 float segmentmins[3], segmentmaxs[3];
6424 msurface_t *surface;
6427 if (VectorCompare(start, end))
6429 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6433 memset(trace, 0, sizeof(*trace));
6434 trace->fraction = 1;
6435 trace->realfraction = 1;
6436 trace->hitsupercontentsmask = hitsupercontentsmask;
6437 segmentmins[0] = min(start[0], end[0]) - 1;
6438 segmentmins[1] = min(start[1], end[1]) - 1;
6439 segmentmins[2] = min(start[2], end[2]) - 1;
6440 segmentmaxs[0] = max(start[0], end[0]) + 1;
6441 segmentmaxs[1] = max(start[1], end[1]) + 1;
6442 segmentmaxs[2] = max(start[2], end[2]) + 1;
6443 if (mod_collision_bih.integer)
6444 Mod_CollisionBIH_TraceLine_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, start, end, start, end);
6445 else if (model->brush.submodel)
6447 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6448 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6449 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6450 if (mod_q3bsp_curves_collisions.integer)
6451 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6452 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6453 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);
6456 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6459 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)
6462 float segmentmins[3], segmentmaxs[3];
6463 msurface_t *surface;
6465 colboxbrushf_t thisbrush_start, thisbrush_end;
6466 vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6468 if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxmins, boxmaxs))
6470 vec3_t shiftstart, shiftend;
6471 VectorAdd(start, boxmins, shiftstart);
6472 VectorAdd(end, boxmins, shiftend);
6473 if (VectorCompare(start, end))
6474 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, shiftstart, hitsupercontentsmask);
6477 Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, shiftstart, shiftend, hitsupercontentsmask);
6478 VectorSubtract(trace->endpos, boxmins, trace->endpos);
6483 // box trace, performed as brush trace
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]) + boxmins[0] - 1;
6489 segmentmins[1] = min(start[1], end[1]) + boxmins[1] - 1;
6490 segmentmins[2] = min(start[2], end[2]) + boxmins[2] - 1;
6491 segmentmaxs[0] = max(start[0], end[0]) + boxmaxs[0] + 1;
6492 segmentmaxs[1] = max(start[1], end[1]) + boxmaxs[1] + 1;
6493 segmentmaxs[2] = max(start[2], end[2]) + boxmaxs[2] + 1;
6494 VectorAdd(start, boxmins, boxstartmins);
6495 VectorAdd(start, boxmaxs, boxstartmaxs);
6496 VectorAdd(end, boxmins, boxendmins);
6497 VectorAdd(end, boxmaxs, boxendmaxs);
6498 Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6499 Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6500 if (mod_collision_bih.integer)
6501 Mod_CollisionBIH_TraceBrush_RecursiveBIHNode(trace, model, model->collision_bih.rootnode, &thisbrush_start.brush, &thisbrush_end.brush, segmentmins, segmentmaxs);
6502 else if (model->brush.submodel)
6504 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6505 if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6506 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, brush->colbrushf, brush->colbrushf);
6507 if (mod_q3bsp_curves_collisions.integer)
6508 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6509 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6510 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);
6513 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, &thisbrush_start.brush, &thisbrush_end.brush, ++markframe, segmentmins, segmentmaxs);
6516 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6519 int supercontents = 0;
6521 if (mod_collision_bih.integer)
6524 Mod_Q3BSP_TracePoint(model, NULL, NULL, &trace, point, 0);
6525 supercontents = trace.startsupercontents;
6527 // test if the point is inside each brush
6528 else if (model->brush.submodel)
6530 // submodels are effectively one leaf
6531 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6532 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6533 supercontents |= brush->colbrushf->supercontents;
6537 mnode_t *node = model->brush.data_nodes;
6539 // find which leaf the point is in
6541 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6542 leaf = (mleaf_t *)node;
6543 // now check the brushes in the leaf
6544 for (i = 0;i < leaf->numleafbrushes;i++)
6546 brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6547 if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6548 supercontents |= brush->colbrushf->supercontents;
6551 return supercontents;
6554 void Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces)
6562 int nummodelbrushes = model->nummodelbrushes;
6563 int nummodelsurfaces = model->nummodelsurfaces;
6565 const int *collisionelement3i;
6566 const float *collisionvertex3f;
6567 const int *renderelement3i;
6568 const float *rendervertex3f;
6569 bih_leaf_t *bihleafs;
6570 bih_node_t *bihnodes;
6572 int *temp_leafsortscratch;
6573 const msurface_t *surface;
6574 const q3mbrush_t *brush;
6576 // find out how many BIH leaf nodes we need
6578 if (userendersurfaces)
6580 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6581 bihnumleafs += surface->num_triangles;
6585 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6586 if (brush->colbrushf)
6588 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6589 bihnumleafs += surface->num_collisiontriangles;
6595 // allocate the memory for the BIH leaf nodes
6596 bihleafs = Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
6598 // now populate the BIH leaf nodes
6600 if (userendersurfaces)
6602 // add render surfaces
6603 renderelement3i = model->surfmesh.data_element3i;
6604 rendervertex3f = model->surfmesh.data_vertex3f;
6605 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6607 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
6609 bihleafs[bihleafindex].type = BIH_LEAF + 2;
6610 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6611 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
6612 bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
6613 bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
6614 bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
6615 bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
6616 bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
6617 bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
6624 // add collision brushes
6625 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
6627 if (!brush->colbrushf)
6629 bihleafs[bihleafindex].type = BIH_LEAF;
6630 bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
6631 bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
6632 VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
6633 VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
6637 // add collision surfaces
6638 collisionelement3i = model->brush.data_collisionelement3i;
6639 collisionvertex3f = model->brush.data_collisionvertex3f;
6640 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6642 for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
6644 bihleafs[bihleafindex].type = BIH_LEAF + 1;
6645 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
6646 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
6647 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
6648 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
6649 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
6650 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
6651 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
6652 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
6658 // allocate buffers for the produced and temporary data
6659 bihmaxnodes = bihnumleafs - 1;
6660 bihnodes = Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
6661 temp_leafsort = Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
6662 temp_leafsortscratch = temp_leafsort + bihnumleafs;
6665 BIH_Build(&model->collision_bih, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
6667 // we're done with the temporary data
6668 Mem_Free(temp_leafsort);
6670 // resize the BIH nodes array if it over-allocated
6671 if (model->collision_bih.maxnodes > model->collision_bih.numnodes)
6673 model->collision_bih.maxnodes = model->collision_bih.numnodes;
6674 model->collision_bih.nodes = Mem_Realloc(loadmodel->mempool, model->collision_bih.nodes, model->collision_bih.numnodes * sizeof(bih_node_t));
6678 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
6680 int supercontents = 0;
6681 if (nativecontents & CONTENTSQ3_SOLID)
6682 supercontents |= SUPERCONTENTS_SOLID;
6683 if (nativecontents & CONTENTSQ3_WATER)
6684 supercontents |= SUPERCONTENTS_WATER;
6685 if (nativecontents & CONTENTSQ3_SLIME)
6686 supercontents |= SUPERCONTENTS_SLIME;
6687 if (nativecontents & CONTENTSQ3_LAVA)
6688 supercontents |= SUPERCONTENTS_LAVA;
6689 if (nativecontents & CONTENTSQ3_BODY)
6690 supercontents |= SUPERCONTENTS_BODY;
6691 if (nativecontents & CONTENTSQ3_CORPSE)
6692 supercontents |= SUPERCONTENTS_CORPSE;
6693 if (nativecontents & CONTENTSQ3_NODROP)
6694 supercontents |= SUPERCONTENTS_NODROP;
6695 if (nativecontents & CONTENTSQ3_PLAYERCLIP)
6696 supercontents |= SUPERCONTENTS_PLAYERCLIP;
6697 if (nativecontents & CONTENTSQ3_MONSTERCLIP)
6698 supercontents |= SUPERCONTENTS_MONSTERCLIP;
6699 if (nativecontents & CONTENTSQ3_DONOTENTER)
6700 supercontents |= SUPERCONTENTS_DONOTENTER;
6701 if (nativecontents & CONTENTSQ3_BOTCLIP)
6702 supercontents |= SUPERCONTENTS_BOTCLIP;
6703 if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
6704 supercontents |= SUPERCONTENTS_OPAQUE;
6705 return supercontents;
6708 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
6710 int nativecontents = 0;
6711 if (supercontents & SUPERCONTENTS_SOLID)
6712 nativecontents |= CONTENTSQ3_SOLID;
6713 if (supercontents & SUPERCONTENTS_WATER)
6714 nativecontents |= CONTENTSQ3_WATER;
6715 if (supercontents & SUPERCONTENTS_SLIME)
6716 nativecontents |= CONTENTSQ3_SLIME;
6717 if (supercontents & SUPERCONTENTS_LAVA)
6718 nativecontents |= CONTENTSQ3_LAVA;
6719 if (supercontents & SUPERCONTENTS_BODY)
6720 nativecontents |= CONTENTSQ3_BODY;
6721 if (supercontents & SUPERCONTENTS_CORPSE)
6722 nativecontents |= CONTENTSQ3_CORPSE;
6723 if (supercontents & SUPERCONTENTS_NODROP)
6724 nativecontents |= CONTENTSQ3_NODROP;
6725 if (supercontents & SUPERCONTENTS_PLAYERCLIP)
6726 nativecontents |= CONTENTSQ3_PLAYERCLIP;
6727 if (supercontents & SUPERCONTENTS_MONSTERCLIP)
6728 nativecontents |= CONTENTSQ3_MONSTERCLIP;
6729 if (supercontents & SUPERCONTENTS_DONOTENTER)
6730 nativecontents |= CONTENTSQ3_DONOTENTER;
6731 if (supercontents & SUPERCONTENTS_BOTCLIP)
6732 nativecontents |= CONTENTSQ3_BOTCLIP;
6733 if (!(supercontents & SUPERCONTENTS_OPAQUE))
6734 nativecontents |= CONTENTSQ3_TRANSLUCENT;
6735 return nativecontents;
6738 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
6743 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
6744 node = node->children[1];
6746 numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
6747 if (loadmodel->brush.num_leafs < numleafs)
6748 loadmodel->brush.num_leafs = numleafs;
6751 void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
6753 int i, j, numshadowmeshtriangles, lumps;
6754 q3dheader_t *header;
6755 float corner[3], yawradius, modelradius;
6756 msurface_t *surface;
6758 mod->modeldatatypestring = "Q3BSP";
6760 mod->type = mod_brushq3;
6761 mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
6764 header = (q3dheader_t *)buffer;
6765 if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
6766 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
6768 i = LittleLong(header->version);
6769 if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
6770 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
6772 mod->soundfromcenter = true;
6773 mod->TraceBox = Mod_Q3BSP_TraceBox;
6774 mod->TraceLine = Mod_Q3BSP_TraceLine;
6775 mod->TracePoint = Mod_Q3BSP_TracePoint;
6776 mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
6777 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
6778 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
6779 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
6780 mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
6781 mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
6782 mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
6783 mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
6784 mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
6785 mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
6786 mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
6787 mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
6788 mod->brush.AmbientSoundLevelsForPoint = NULL;
6789 mod->brush.RoundUpToHullSize = NULL;
6790 mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
6791 mod->Draw = R_Q1BSP_Draw;
6792 mod->DrawDepth = R_Q1BSP_DrawDepth;
6793 mod->DrawDebug = R_Q1BSP_DrawDebug;
6794 mod->DrawPrepass = R_Q1BSP_DrawPrepass;
6795 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
6796 mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
6797 mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
6798 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
6799 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
6800 mod->DrawLight = R_Q1BSP_DrawLight;
6802 mod_base = (unsigned char *)header;
6804 // swap all the lumps
6805 header->ident = LittleLong(header->ident);
6806 header->version = LittleLong(header->version);
6807 lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
6808 for (i = 0;i < lumps;i++)
6810 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
6811 if((char *) bufferend < (char *) buffer + j)
6812 Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
6813 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
6814 if((char *) bufferend < (char *) buffer + j)
6815 Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
6818 * NO, do NOT clear them!
6819 * they contain actual data referenced by other stuff.
6820 * Instead, before using the advertisements lump, check header->versio
6822 * Sorry, but otherwise it breaks memory of the first lump.
6823 for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
6825 header->lumps[i].fileofs = 0;
6826 header->lumps[i].filelen = 0;
6830 mod->brush.qw_md4sum = 0;
6831 mod->brush.qw_md4sum2 = 0;
6832 for (i = 0;i < lumps;i++)
6834 if (i == Q3LUMP_ENTITIES)
6836 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6837 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
6839 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
6841 // all this checksumming can take a while, so let's send keepalives here too
6842 CL_KeepaliveMessage(false);
6845 Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
6846 Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
6847 Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
6848 if (header->version == Q3BSPVERSION_IG)
6849 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
6851 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
6852 Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
6853 Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
6854 Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
6855 Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
6856 Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
6857 Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
6858 Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
6859 Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
6860 Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
6861 Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
6862 Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
6863 Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
6864 Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
6865 loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
6867 // the MakePortals code works fine on the q3bsp data as well
6868 Mod_Q1BSP_MakePortals();
6870 // FIXME: shader alpha should replace r_wateralpha support in q3bsp
6871 loadmodel->brush.supportwateralpha = true;
6873 // make a single combined shadow mesh to allow optimized shadow volume creation
6874 numshadowmeshtriangles = 0;
6875 if (cls.state != ca_dedicated)
6877 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
6879 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
6880 numshadowmeshtriangles += surface->num_triangles;
6882 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
6883 for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
6884 if (surface->num_triangles > 0)
6885 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));
6886 loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true, false);
6887 if (loadmodel->brush.shadowmesh)
6888 Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
6891 loadmodel->brush.num_leafs = 0;
6892 Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
6894 if (loadmodel->brush.numsubmodels)
6895 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
6898 for (i = 0;i < loadmodel->brush.numsubmodels;i++)
6903 // duplicate the basic information
6904 dpsnprintf(name, sizeof(name), "*%i", i);
6905 mod = Mod_FindName(name, loadmodel->name);
6906 // copy the base model to this one
6908 // rename the clone back to its proper name
6909 strlcpy(mod->name, name, sizeof(mod->name));
6910 mod->brush.parentmodel = loadmodel;
6911 // textures and memory belong to the main model
6912 mod->texturepool = NULL;
6913 mod->mempool = NULL;
6914 mod->brush.GetPVS = NULL;
6915 mod->brush.FatPVS = NULL;
6916 mod->brush.BoxTouchingPVS = NULL;
6917 mod->brush.BoxTouchingLeafPVS = NULL;
6918 mod->brush.BoxTouchingVisibleLeafs = NULL;
6919 mod->brush.FindBoxClusters = NULL;
6920 mod->brush.LightPoint = NULL;
6921 mod->brush.AmbientSoundLevelsForPoint = NULL;
6923 mod->brush.submodel = i;
6924 if (loadmodel->brush.submodels)
6925 loadmodel->brush.submodels[i] = mod;
6927 // make the model surface list (used by shadowing/lighting)
6928 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
6929 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
6930 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
6931 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
6932 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
6933 Mod_MakeSortedSurfaces(mod);
6935 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
6936 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
6937 // enlarge the bounding box to enclose all geometry of this model,
6938 // because q3map2 sometimes lies (mostly to affect the lightgrid),
6939 // which can in turn mess up the farclip (as well as culling when
6940 // outside the level - an unimportant concern)
6942 //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]);
6943 for (j = 0;j < mod->nummodelsurfaces;j++)
6945 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
6946 const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
6948 if (!surface->num_vertices)
6950 for (k = 0;k < surface->num_vertices;k++, v += 3)
6952 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
6953 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
6954 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
6955 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
6956 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
6957 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
6960 //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]);
6961 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
6962 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
6963 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
6964 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
6965 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
6966 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
6967 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
6968 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
6969 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
6970 mod->yawmins[2] = mod->normalmins[2];
6971 mod->yawmaxs[2] = mod->normalmaxs[2];
6972 mod->radius = modelradius;
6973 mod->radius2 = modelradius * modelradius;
6975 // this gets altered below if sky or water is used
6976 mod->DrawSky = NULL;
6977 mod->DrawAddWaterPlanes = NULL;
6979 for (j = 0;j < mod->nummodelsurfaces;j++)
6980 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
6982 if (j < mod->nummodelsurfaces)
6983 mod->DrawSky = R_Q1BSP_DrawSky;
6985 for (j = 0;j < mod->nummodelsurfaces;j++)
6986 if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
6988 if (j < mod->nummodelsurfaces)
6989 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
6991 Mod_MakeCollisionBIH(mod, false);
6993 // generate VBOs and other shared data before cloning submodels
6998 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);
7001 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7003 int i = LittleLong(((int *)buffer)[1]);
7004 if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7005 Mod_Q3BSP_Load(mod,buffer, bufferend);
7006 else if (i == Q2BSPVERSION)
7007 Mod_Q2BSP_Load(mod,buffer, bufferend);
7009 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7012 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7014 Host_Error("Mod_MAP_Load: not yet implemented");
7020 typedef struct objvertex_s
7030 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7032 const char *textbase = (char *)buffer, *text = textbase;
7036 char materialname[MAX_QPATH];
7037 int i, j, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, numsurfaces, surfacevertices, surfacetriangles, surfaceelements;
7038 int index1, index2, index3;
7039 objvertex_t vfirst, vprev, vcurrent;
7042 int numtriangles = 0;
7043 int maxtriangles = 0;
7044 objvertex_t *vertices = NULL;
7046 int maxtextures = 0, numtextures = 0, textureindex = 0;
7047 int maxv = 0, numv = 1;
7048 int maxvt = 0, numvt = 1;
7049 int maxvn = 0, numvn = 1;
7050 char *texturenames = NULL;
7051 float dist, modelradius, modelyawradius;
7057 objvertex_t *thisvertex = NULL;
7058 int vertexhashindex;
7059 int *vertexhashtable = NULL;
7060 objvertex_t *vertexhashdata = NULL;
7061 objvertex_t *vdata = NULL;
7062 int vertexhashsize = 0;
7063 int vertexhashcount = 0;
7064 skinfile_t *skinfiles = NULL;
7065 unsigned char *data = NULL;
7067 memset(&vfirst, 0, sizeof(vfirst));
7068 memset(&vprev, 0, sizeof(vprev));
7069 memset(&vcurrent, 0, sizeof(vcurrent));
7071 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7073 loadmodel->modeldatatypestring = "OBJ";
7075 loadmodel->type = mod_obj;
7076 loadmodel->soundfromcenter = true;
7077 loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7078 loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7079 loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7080 loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7081 loadmodel->brush.TraceLineOfSight = NULL;
7082 loadmodel->brush.SuperContentsFromNativeContents = NULL;
7083 loadmodel->brush.NativeContentsFromSuperContents = NULL;
7084 loadmodel->brush.GetPVS = NULL;
7085 loadmodel->brush.FatPVS = NULL;
7086 loadmodel->brush.BoxTouchingPVS = NULL;
7087 loadmodel->brush.BoxTouchingLeafPVS = NULL;
7088 loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7089 loadmodel->brush.FindBoxClusters = NULL;
7090 loadmodel->brush.LightPoint = NULL;
7091 loadmodel->brush.FindNonSolidLocation = NULL;
7092 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7093 loadmodel->brush.RoundUpToHullSize = NULL;
7094 loadmodel->brush.PointInLeaf = NULL;
7095 loadmodel->Draw = R_Q1BSP_Draw;
7096 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7097 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7098 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7099 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7100 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7101 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7102 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7103 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7104 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7106 skinfiles = Mod_LoadSkinFiles();
7107 if (loadmodel->numskins < 1)
7108 loadmodel->numskins = 1;
7110 // make skinscenes for the skins (no groups)
7111 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7112 for (i = 0;i < loadmodel->numskins;i++)
7114 loadmodel->skinscenes[i].firstframe = i;
7115 loadmodel->skinscenes[i].framecount = 1;
7116 loadmodel->skinscenes[i].loop = true;
7117 loadmodel->skinscenes[i].framerate = 10;
7123 // parse the OBJ text now
7130 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7131 line[linelen] = text[linelen];
7133 for (argc = 0;argc < 4;argc++)
7137 while (*s == ' ' || *s == '\t')
7147 while (*s == ' ' || *s == '\t')
7157 if (argv[0][0] == '#')
7159 if (!strcmp(argv[0], "v"))
7163 maxv = max(maxv * 2, 1024);
7164 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7166 v[numv*3+0] = atof(argv[1]);
7167 v[numv*3+2] = atof(argv[2]);
7168 v[numv*3+1] = atof(argv[3]);
7171 else if (!strcmp(argv[0], "vt"))
7175 maxvt = max(maxvt * 2, 1024);
7176 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7178 vt[numvt*2+0] = atof(argv[1]);
7179 vt[numvt*2+1] = 1-atof(argv[2]);
7182 else if (!strcmp(argv[0], "vn"))
7186 maxvn = max(maxvn * 2, 1024);
7187 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7189 vn[numvn*3+0] = atof(argv[1]);
7190 vn[numvn*3+2] = atof(argv[2]);
7191 vn[numvn*3+1] = atof(argv[3]);
7194 else if (!strcmp(argv[0], "f"))
7198 if (maxtextures <= numtextures)
7200 maxtextures = max(maxtextures * 2, 256);
7201 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7203 textureindex = numtextures++;
7204 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7206 for (j = 1;j < argc;j++)
7208 index1 = atoi(argv[j]);
7209 while(argv[j][0] && argv[j][0] != '/')
7213 index2 = atoi(argv[j]);
7214 while(argv[j][0] && argv[j][0] != '/')
7218 index3 = atoi(argv[j]);
7219 // negative refers to a recent vertex
7220 // zero means not specified
7221 // positive means an absolute vertex index
7223 index1 = numv - index1;
7225 index2 = numvt - index2;
7227 index3 = numvn - index3;
7228 vcurrent.nextindex = -1;
7229 vcurrent.textureindex = textureindex;
7230 VectorCopy(v + 3*index1, vcurrent.v);
7231 Vector2Copy(vt + 2*index2, vcurrent.vt);
7232 VectorCopy(vn + 3*index3, vcurrent.vn);
7233 if (numtriangles == 0)
7235 VectorCopy(vcurrent.v, mins);
7236 VectorCopy(vcurrent.v, maxs);
7240 mins[0] = min(mins[0], vcurrent.v[0]);
7241 mins[1] = min(mins[1], vcurrent.v[1]);
7242 mins[2] = min(mins[2], vcurrent.v[2]);
7243 maxs[0] = max(maxs[0], vcurrent.v[0]);
7244 maxs[1] = max(maxs[1], vcurrent.v[1]);
7245 maxs[2] = max(maxs[2], vcurrent.v[2]);
7251 if (maxtriangles <= numtriangles)
7253 maxtriangles = max(maxtriangles * 2, 32768);
7254 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7256 vertices[numtriangles*3+0] = vfirst;
7257 vertices[numtriangles*3+1] = vprev;
7258 vertices[numtriangles*3+2] = vcurrent;
7264 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7266 else if (!strcmp(argv[0], "usemtl"))
7268 for (i = 0;i < numtextures;i++)
7269 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7271 if (i < numtextures)
7275 if (maxtextures <= numtextures)
7277 maxtextures = max(maxtextures * 2, 256);
7278 texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7280 textureindex = numtextures++;
7281 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7286 // now that we have the OBJ data loaded as-is, we can convert it
7288 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7289 VectorCopy(mins, loadmodel->normalmins);
7290 VectorCopy(maxs, loadmodel->normalmaxs);
7291 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7292 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7293 modelyawradius = dist*dist+modelyawradius*modelyawradius;
7294 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7295 modelradius = modelyawradius + modelradius * modelradius;
7296 modelyawradius = sqrt(modelyawradius);
7297 modelradius = sqrt(modelradius);
7298 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7299 loadmodel->yawmins[2] = loadmodel->normalmins[2];
7300 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
7301 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7302 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7303 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
7304 loadmodel->radius = modelradius;
7305 loadmodel->radius2 = modelradius * modelradius;
7307 // allocate storage for triangles
7308 loadmodel->num_surfaces = loadmodel->nummodelsurfaces = numsurfaces = numtextures;
7309 loadmodel->surfmesh.data_element3i = Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7310 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(msurface_t));
7311 // allocate vertex hash structures to build an optimal vertex subset
7312 vertexhashsize = numtriangles*2;
7313 vertexhashtable = Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7314 memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7315 vertexhashdata = Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7316 vertexhashcount = 0;
7318 // gather surface stats for assigning vertex/triangle ranges
7322 for (textureindex = 0;textureindex < numtextures;textureindex++)
7324 msurface_t *surface = loadmodel->data_surfaces + textureindex;
7325 // copy the mins/maxs of the model backwards so that the first vertex
7326 // added will set the surface bounds to a point
7327 VectorCopy(loadmodel->normalmaxs, surface->mins);
7328 VectorCopy(loadmodel->normalmins, surface->maxs);
7329 surfacevertices = 0;
7330 surfaceelements = 0;
7331 for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7333 thisvertex = vertices + vertexindex;
7334 if (thisvertex->textureindex != textureindex)
7336 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7337 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7338 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7339 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7340 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7341 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7342 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7343 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7345 vdata = vertexhashdata + i;
7346 if (vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7351 i = vertexhashcount++;
7352 vdata = vertexhashdata + i;
7353 *vdata = *thisvertex;
7354 vdata->nextindex = vertexhashtable[vertexhashindex];
7355 vertexhashtable[vertexhashindex] = i;
7358 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7361 surfacetriangles = surfaceelements / 3;
7362 surface->num_vertices = surfacevertices;
7363 surface->num_triangles = surfacetriangles;
7364 surface->num_firstvertex = firstvertex;
7365 surface->num_firsttriangle = firsttriangle;
7366 firstvertex += surface->num_vertices;
7367 firsttriangle += surface->num_triangles;
7369 numvertices = firstvertex;
7371 // allocate storage for final mesh data
7372 loadmodel->num_textures = numtextures * loadmodel->numskins;
7373 loadmodel->num_texturesperskin = numtextures;
7374 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]));
7375 loadmodel->sortedmodelsurfaces = (int *)data;data += numsurfaces * sizeof(int);
7376 loadmodel->data_textures = (texture_t *)data;data += numsurfaces * loadmodel->numskins * sizeof(texture_t);
7377 loadmodel->surfmesh.num_vertices = numvertices;
7378 loadmodel->surfmesh.num_triangles = numtriangles;
7379 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7380 loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7381 loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7382 loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7383 loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7384 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7385 if (loadmodel->surfmesh.num_vertices <= 65536)
7386 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7388 for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7390 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7391 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7392 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7395 // load the textures
7396 for (textureindex = 0;textureindex < numtextures;textureindex++)
7397 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7398 Mod_FreeSkinFiles(skinfiles);
7400 // set the surface textures
7401 for (textureindex = 0;textureindex < numtextures;textureindex++)
7403 msurface_t *surface = loadmodel->data_surfaces + textureindex;
7404 surface->texture = loadmodel->data_textures + textureindex;
7409 Mem_Free(texturenames);
7413 Mem_Free(vertexhashtable);
7414 Mem_Free(vertexhashdata);
7416 // compute all the mesh information that was not loaded from the file
7417 Mod_MakeSortedSurfaces(loadmodel);
7418 if (loadmodel->surfmesh.data_element3s)
7419 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7420 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7421 Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7422 // generate normals if the file did not have them
7423 if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7424 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, true);
7425 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);
7426 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7428 Mod_MakeCollisionBIH(loadmodel, true);
7443 typedef struct objvertex_s
7451 typedef struct objtriangle_s
7453 objvertex_t vertex[3];
7455 // these fields are used only in conversion to surfaces
7458 int surfacevertexindex[3];
7459 float edgeplane[3][4];
7465 struct objnode_s *children[2];
7466 struct objnode_s *parent;
7467 objtriangle_t *triangles;
7476 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)
7482 float bestnormal[3];
7487 int numfronttriangles;
7488 int numbacktriangles;
7493 float outfrontpoints[5][3];
7494 float outbackpoints[5][3];
7495 int neededfrontpoints;
7496 int neededbackpoints;
7500 node = (objnode_t *)Mem_ExpandableArray_AllocRecord(array);
7501 node->parent = parent;
7504 VectorCopy(triangles[0].vertex[0].v, mins);
7505 VectorCopy(triangles[0].vertex[0].v, maxs);
7507 else if (parent && parent->children[0] == node)
7509 VectorCopy(parent->mins, mins);
7510 Vectorcopy(parent->maxs, maxs);
7512 else if (parent && parent->children[1] == node)
7514 VectorCopy(parent->mins, mins);
7515 Vectorcopy(parent->maxs, maxs);
7522 for (i = 0;i < numtriangles;i++)
7524 for (j = 0;j < 3;j++)
7526 mins[0] = min(mins[0], triangles[i].vertex[j].v[0]);
7527 mins[1] = min(mins[1], triangles[i].vertex[j].v[1]);
7528 mins[2] = min(mins[2], triangles[i].vertex[j].v[2]);
7529 maxs[0] = max(maxs[0], triangles[i].vertex[j].v[0]);
7530 maxs[1] = max(maxs[1], triangles[i].vertex[j].v[1]);
7531 maxs[2] = max(maxs[2], triangles[i].vertex[j].v[2]);
7534 VectorCopy(mins, node->mins);
7535 VectorCopy(maxs, node->maxs);
7536 if (numtriangles <= mod_obj_leaftriangles.integer)
7539 loadmodel->brush.num_leafs++;
7540 node->triangles = triangles;
7541 node->numtriangles = numtriangles;
7546 loadmodel->brush.num_nodes++;
7547 // pick a splitting plane from the various choices available to us...
7548 // early splits simply halve the interval
7550 VectorClear(bestnormal);
7552 if (numtriangles <= mod_obj_splitterlimit.integer)
7553 limit = numtriangles;
7556 for (i = -3;i < limit;i++)
7560 // first we try 3 axial splits (kdtree-like)
7562 VectorClear(normal);
7564 dist = (mins[j] + maxs[j]) * 0.5f;
7568 // then we try each triangle plane
7569 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7570 VectorNormalize(normal);
7571 dist = DotProduct(normal, triangles[i].vertex[0].v);
7572 // use positive axial values whenever possible
7573 if (normal[0] == -1)
7575 if (normal[1] == -1)
7577 if (normal[2] == -1)
7579 // skip planes that match the current best
7580 if (VectorCompare(normal, bestnormal) && dist == bestdist)
7587 for (j = 0;j < numtriangles;j++)
7589 dists[0] = DotProduct(normal, triangles[j].vertex[0].v) - dist;
7590 dists[1] = DotProduct(normal, triangles[j].vertex[1].v) - dist;
7591 dists[2] = DotProduct(normal, triangles[j].vertex[2].v) - dist;
7592 if (dists[0] < -DIST_EPSILON || dists[1] < -DIST_EPSILON || dists[2] < -DIST_EPSILON)
7594 if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7599 else if (dists[0] > DIST_EPSILON || dists[1] > DIST_EPSILON || dists[2] > DIST_EPSILON)
7604 // score is supposed to:
7605 // prefer axial splits
7606 // prefer evenly dividing the input triangles
7607 // prefer triangles on the plane
7608 // avoid triangles crossing the plane
7609 score = count_on*count_on - count_both*count_both + min(count_front, count_back)*(count_front+count_back);
7610 if (normal[0] == 1 || normal[1] == 1 || normal[2] == 1)
7612 if (i == -3 || bestscore < score)
7614 VectorCopy(normal, bestnormal);
7620 // now we have chosen an optimal split plane...
7622 // divide triangles by the splitting plane
7623 numfronttriangles = 0;
7624 numbacktriangles = 0;
7625 for (i = 0;i < numtriangles;i++)
7627 neededfrontpoints = 0;
7628 neededbackpoints = 0;
7630 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);
7631 if (countonpoints > 1)
7633 // triangle lies on plane, assign it to one child only
7634 TriangleNormal(triangles[i].vertex[0].v, triangles[i].vertex[1].v, triangles[i].vertex[2].v, normal);
7635 if (DotProduct(bestnormal, normal) >= 0)
7637 // assign to front side child
7638 obj_fronttriangles[numfronttriangles++] = triangles[i];
7642 // assign to back side child
7643 obj_backtriangles[numbacktriangles++] = triangles[i];
7648 // convert clipped polygons to triangles
7649 for (j = 0;j < neededfrontpoints-2;j++)
7651 obj_fronttriangles[numfronttriangles] = triangles[i];
7652 VectorCopy(outfrontpoints[0], obj_fronttriangles[numfronttriangles].vertex[0].v);
7653 VectorCopy(outfrontpoints[j+1], obj_fronttriangles[numfronttriangles].vertex[1].v);
7654 VectorCopy(outfrontpoints[j+2], obj_fronttriangles[numfronttriangles].vertex[2].v);
7655 numfronttriangles++;
7657 for (j = 0;j < neededbackpoints-2;j++)
7659 obj_backtriangles[numbacktriangles] = triangles[i];
7660 VectorCopy(outbackpoints[0], obj_backtriangles[numbacktriangles].vertex[0].v);
7661 VectorCopy(outbackpoints[j+1], obj_backtriangles[numbacktriangles].vertex[1].v);
7662 VectorCopy(outbackpoints[j+2], obj_backtriangles[numbacktriangles].vertex[2].v);
7668 // now copy the triangles out of the big buffer
7669 if (numfronttriangles)
7671 fronttriangles = Mem_Alloc(loadmodel->mempool, fronttriangles * sizeof(*fronttriangles));
7672 memcpy(fronttriangles, obj_fronttriangles, numfronttriangles * sizeof(*fronttriangles));
7675 fronttriangles = NULL;
7676 if (numbacktriangles)
7678 backtriangles = Mem_Alloc(loadmodel->mempool, backtriangles * sizeof(*backtriangles));
7679 memcpy(backtriangles, obj_backtriangles, numbacktriangles * sizeof(*backtriangles));
7682 backtriangles = NULL;
7684 // free the original triangles we were given
7686 Mem_Free(triangles);
7690 // now create the children...
7691 node->children[0] = Mod_OBJ_BSPNodeForTriangles(node, fronttriangles, numfronttriangles, frontmins, frontmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
7692 node->children[1] = Mod_OBJ_BSPNodeForTriangles(node, backtriangles, numbacktriangles, backmins, backmaxs, nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
7696 void Mod_OBJ_SnapVertex(float *v)
7699 float a = mod_obj_vertexprecision.value;
7701 v[0] -= floor(v[0] * a + 0.5f) * b;
7702 v[1] -= floor(v[1] * a + 0.5f) * b;
7703 v[2] -= floor(v[2] * a + 0.5f) * b;
7706 void Mod_OBJ_ConvertBSPNode(objnode_t *objnode, mnode_t *mnodeparent)
7708 if (objnode->children[0])
7710 // convert to mnode_t
7711 mnode_t *mnode = loadmodel->brush.data_nodes + loadmodel->brush.num_nodes++;
7712 mnode->parent = mnodeparent;
7713 mnode->plane = loadmodel->brush.data_planes + loadmodel->brush.num_planes++;
7714 VectorCopy(objnode->normal, mnode->plane->normal);
7715 mnode->plane->dist = objnode->dist;
7716 PlaneClassify(mnode->plane);
7717 VectorCopy(objnode->mins, mnode->mins);
7718 VectorCopy(objnode->maxs, mnode->maxs);
7719 // push combinedsupercontents up to the parent
7721 mnodeparent->combinedsupercontents |= mnode->combinedsupercontents;
7722 mnode->children[0] = Mod_OBJ_ConvertBSPNode(objnode->children[0], mnode);
7723 mnode->children[1] = Mod_OBJ_ConvertBSPNode(objnode->children[1], mnode);
7727 // convert to mleaf_t
7728 mleaf_t *mleaf = loadmodel->brush.data_leafs + loadmodel->brush.num_leafs++;
7729 mleaf->parent = mnodeparent;
7730 VectorCopy(objnode->mins, mleaf->mins);
7731 VectorCopy(objnode->maxs, mleaf->maxs);
7732 mleaf->clusterindex = loadmodel->brush.num_leafs - 1;
7733 if (objnode->numtriangles)
7735 objtriangle_t *triangles = objnode->triangles;
7736 int numtriangles = objnode->numtriangles;
7740 objvertex_t vertex[3];
7742 maxsurfaces = numtriangles;
7744 // calculate some more data on each triangle for surface gathering
7745 for (i = 0;i < numtriangles;i++)
7747 triangle = triangles + i;
7748 texture = loadmodel->data_textures + triangle->textureindex;
7749 Mod_OBJ_SnapVertex(triangle->vertex[0].v);
7750 Mod_OBJ_SnapVertex(triangle->vertex[1].v);
7751 Mod_OBJ_SnapVertex(triangle->vertex[2].v);
7752 TriangleNormal(triangle->vertex[0].v, triangle->vertex[1].v, triangle->vertex[2].v, normal);
7754 if (fabs(normal[axis]) < fabs(normal[1]))
7756 if (fabs(normal[axis]) < fabs(normal[2]))
7758 VectorClear(normal);
7760 triangle->axis = axis;
7761 VectorSubtract(triangle->vertex[1].v, triangle->vertex[0].v, edge[0]);
7762 VectorSubtract(triangle->vertex[2].v, triangle->vertex[1].v, edge[1]);
7763 VectorSubtract(triangle->vertex[0].v, triangle->vertex[2].v, edge[2]);
7764 CrossProduct(edge[0], normal, triangle->edgeplane[0]);
7765 CrossProduct(edge[1], normal, triangle->edgeplane[1]);
7766 CrossProduct(edge[2], normal, triangle->edgeplane[2]);
7767 VectorNormalize(triangle->edgeplane[0]);
7768 VectorNormalize(triangle->edgeplane[1]);
7769 VectorNormalize(triangle->edgeplane[2]);
7770 triangle->edgeplane[0][3] = DotProduct(triangle->edgeplane[0], triangle->vertex[0].v);
7771 triangle->edgeplane[1][3] = DotProduct(triangle->edgeplane[1], triangle->vertex[1].v);
7772 triangle->edgeplane[2][3] = DotProduct(triangle->edgeplane[2], triangle->vertex[2].v);
7773 triangle->surfaceindex = 0;
7774 // add to the combined supercontents while we're here...
7775 mleaf->combinedsupercontents |= texture->supercontents;
7778 for (i = 0;i < numtriangles;i++)
7780 // skip already-assigned triangles
7781 if (triangles[i].surfaceindex)
7783 texture = loadmodel->data_textures + triangles[i].textureindex;
7784 // assign a new surface to this triangle
7785 triangles[i].surfaceindex = surfaceindex++;
7786 axis = triangles[i].axis;
7788 // find the triangle's neighbors, this can take multiple passes
7793 for (j = i+1;j < numtriangles;j++)
7795 if (triangles[j].surfaceindex || triangles[j].axis != axis || triangles[j].texture != texture)
7797 triangle = triangles + j;
7798 for (k = i;k < j;k++)
7800 if (triangles[k].surfaceindex != surfaceindex)
7802 if (VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[0].v)
7803 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[1].v)
7804 || VectorCompare(triangles[k].vertex[0].v, triangles[j].vertex[2].v)
7805 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[0].v)
7806 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[1].v)
7807 || VectorCompare(triangles[k].vertex[1].v, triangles[j].vertex[2].v)
7808 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[0].v)
7809 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[1].v)
7810 || VectorCompare(triangles[k].vertex[2].v, triangles[j].vertex[2].v))
7812 // shares a vertex position
7816 for (k = 0;k < numvertices;k++)
7817 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))
7819 if (k == numvertices)
7820 break; // not a neighbor
7821 // this triangle is a neighbor and has the same axis and texture
7822 // check now if it overlaps in lightmap projection space
7823 triangles[j].surfaceindex;
7827 //triangles[i].surfaceindex = surfaceindex++;
7828 for (surfaceindex = 0;surfaceindex < numsurfaces;surfaceindex++)
7830 if (surfaces[surfaceindex].texture != texture)
7832 // check if any triangles already in this surface overlap in lightmap projection space
7839 // let the collision code simply use the surfaces
7840 mleaf->containscollisionsurfaces = mleaf->combinedsupercontents != 0;
7841 mleaf->numleafsurfaces = ?;
7842 mleaf->firstleafsurface = ?;
7844 // push combinedsupercontents up to the parent
7846 mnodeparent->combinedsupercontents |= mleaf->combinedsupercontents;
7851 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7854 const char *textbase = (char *)buffer, *text = textbase;
7858 char materialname[MAX_QPATH];
7859 int j, index1, index2, index3, first, prev, index;
7862 int numtriangles = 0;
7863 int maxtriangles = 131072;
7864 objtriangle_t *triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
7866 int maxtextures = 256, numtextures = 0, textureindex = 0;
7867 int maxv = 1024, numv = 0;
7868 int maxvt = 1024, numvt = 0;
7869 int maxvn = 1024, numvn = 0;
7870 char **texturenames;
7871 float *v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
7872 float *vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
7873 float *vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
7874 objvertex_t vfirst, vprev, vcurrent;
7879 int maxverthash = 65536, numverthash = 0;
7880 int numhashindex = 65536;
7881 struct objverthash_s
7883 struct objverthash_s *next;
7889 *hash, **verthash = Mem_Alloc(tempmempool, numhashindex * sizeof(*verthash)), *verthashdata = Mem_Alloc(tempmempool, maxverthash * sizeof(*verthashdata)), *oldverthashdata;
7892 dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7894 loadmodel->modeldatatypestring = "OBJ";
7896 loadmodel->type = mod_obj;
7897 loadmodel->soundfromcenter = true;
7898 loadmodel->TraceBox = Mod_OBJ_TraceBox;
7899 loadmodel->TraceLine = Mod_OBJ_TraceLine;
7900 loadmodel->TracePoint = Mod_OBJ_TracePoint;
7901 loadmodel->PointSuperContents = Mod_OBJ_PointSuperContents;
7902 loadmodel->brush.TraceLineOfSight = Mod_OBJ_TraceLineOfSight;
7903 loadmodel->brush.SuperContentsFromNativeContents = Mod_OBJ_SuperContentsFromNativeContents;
7904 loadmodel->brush.NativeContentsFromSuperContents = Mod_OBJ_NativeContentsFromSuperContents;
7905 loadmodel->brush.GetPVS = Mod_OBJ_GetPVS;
7906 loadmodel->brush.FatPVS = Mod_OBJ_FatPVS;
7907 loadmodel->brush.BoxTouchingPVS = Mod_OBJ_BoxTouchingPVS;
7908 loadmodel->brush.BoxTouchingLeafPVS = Mod_OBJ_BoxTouchingLeafPVS;
7909 loadmodel->brush.BoxTouchingVisibleLeafs = Mod_OBJ_BoxTouchingVisibleLeafs;
7910 loadmodel->brush.FindBoxClusters = Mod_OBJ_FindBoxClusters;
7911 loadmodel->brush.LightPoint = Mod_OBJ_LightPoint;
7912 loadmodel->brush.FindNonSolidLocation = Mod_OBJ_FindNonSolidLocation;
7913 loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7914 loadmodel->brush.RoundUpToHullSize = NULL;
7915 loadmodel->brush.PointInLeaf = Mod_OBJ_PointInLeaf;
7916 loadmodel->Draw = R_Q1BSP_Draw;
7917 loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7918 loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7919 loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7920 loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7921 loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7922 loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7923 loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7924 loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7925 loadmodel->DrawLight = R_Q1BSP_DrawLight;
7930 // parse the OBJ text now
7937 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7938 line[linelen] = text[linelen];
7940 for (argc = 0;argc < (int)(sizeof(argv)/sizeof(argv[0]));argc++)
7944 while (*s == ' ' || *s == '\t')
7954 while (*s == ' ' || *s == '\t')
7959 if (argv[0][0] == '#')
7961 if (!strcmp(argv[0], "v"))
7967 v = Mem_Alloc(tempmempool, maxv * sizeof(float[3]));
7970 memcpy(v, oldv, numv * sizeof(float[3]));
7974 v[numv*3+0] = atof(argv[1]);
7975 v[numv*3+1] = atof(argv[2]);
7976 v[numv*3+2] = atof(argv[3]);
7979 else if (!strcmp(argv[0], "vt"))
7985 vt = Mem_Alloc(tempmempool, maxvt * sizeof(float[2]));
7988 memcpy(vt, oldvt, numvt * sizeof(float[2]));
7992 vt[numvt*2+0] = atof(argv[1]);
7993 vt[numvt*2+1] = atof(argv[2]);
7996 else if (!strcmp(argv[0], "vn"))
8002 vn = Mem_Alloc(tempmempool, maxvn * sizeof(float[3]));
8005 memcpy(vn, oldvn, numvn * sizeof(float[3]));
8009 vn[numvn*3+0] = atof(argv[1]);
8010 vn[numvn*3+1] = atof(argv[2]);
8011 vn[numvn*3+2] = atof(argv[3]);
8014 else if (!strcmp(argv[0], "f"))
8016 for (j = 1;j < argc;j++)
8018 index1 = atoi(argv[j]);
8019 while(argv[j][0] && argv[j][0] != '/')
8023 index2 = atoi(argv[j]);
8024 while(argv[j][0] && argv[j][0] != '/')
8028 index3 = atoi(argv[j]);
8029 // negative refers to a recent vertex
8030 // zero means not specified
8031 // positive means an absolute vertex index
8033 index1 = numv - index1;
8035 index2 = numvt - index2;
8037 index3 = numvn - index3;
8038 VectorCopy(v + 3*index1, vcurrent.v);
8039 Vector2Copy(vt + 2*index2, vcurrent.vt);
8040 VectorCopy(vn + 3*index3, vcurrent.vn);
8041 if (numtriangles == 0)
8043 VectorCopy(vcurrent.v, mins);
8044 VectorCopy(vcurrent.v, maxs);
8048 mins[0] = min(mins[0], vcurrent.v[0]);
8049 mins[1] = min(mins[1], vcurrent.v[1]);
8050 mins[2] = min(mins[2], vcurrent.v[2]);
8051 maxs[0] = max(maxs[0], vcurrent.v[0]);
8052 maxs[1] = max(maxs[1], vcurrent.v[1]);
8053 maxs[2] = max(maxs[2], vcurrent.v[2]);
8059 if (maxtriangles <= numtriangles)
8061 objtriangle_t *oldtriangles = triangles;
8063 triangles = Mem_Alloc(tempmempool, maxtriangles * sizeof(*triangles));
8066 memcpy(triangles, oldtriangles, maxtriangles * sizeof(*triangles));
8067 Mem_Free(oldtriangles);
8070 triangles[numtriangles].textureindex = textureindex;
8071 triangles[numtriangles].vertex[0] = vfirst;
8072 triangles[numtriangles].vertex[1] = vprev;
8073 triangles[numtriangles].vertex[2] = vcurrent;
8080 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8082 else if (!!strcmp(argv[0], "usemtl"))
8084 for (i = 0;i < numtextures;i++)
8085 if (!strcmp(texturenames[numtextures], argv[1]))
8087 if (i < numtextures)
8088 texture = textures + i;
8091 if (maxtextures <= numtextures)
8093 texture_t *oldtextures = textures;
8095 textures = Mem_Alloc(tempmempool, maxtextures * sizeof(*textures));
8098 memcpy(textures, oldtextures, numtextures * sizeof(*textures));
8099 Mem_Free(oldtextures);
8102 textureindex = numtextures++;
8103 texturenames[textureindex] = Mem_Alloc(tempmempool, strlen(argv[1]) + 1);
8104 memcpy(texturenames[textureindex], argv[1], strlen(argv[1]) + 1);
8114 // now that we have the OBJ data loaded as-is, we can convert it
8116 // load the textures
8117 loadmodel->num_textures = numtextures;
8118 loadmodel->data_textures = Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
8119 for (i = 0;i < numtextures;i++)
8120 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, texturenames[i], true, true, TEXF_MIPMAP | TEXF_ALPHA | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS);
8122 // free the texturenames array since we are now done with it
8123 for (i = 0;i < numtextures;i++)
8125 Mem_Free(texturenames[i]);
8126 texturenames[i] = NULL;
8128 Mem_Free(texturenames);
8129 texturenames = NULL;
8131 // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8132 VectorCopy(mins, loadmodel->normalmins);
8133 VectorCopy(maxs, loadmodel->normalmaxs);
8134 dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8135 modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8136 modelyawradius = dist*dist+modelyawradius*modelyawradius;
8137 modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8138 modelradius = modelyawradius + modelradius * modelradius;
8139 modelyawradius = sqrt(modelyawradius);
8140 modelradius = sqrt(modelradius);
8141 loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8142 loadmodel->yawmins[2] = loadmodel->normalmins[2];
8143 loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] = modelyawradius;
8144 loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8145 loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8146 loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] = modelradius;
8147 loadmodel->radius = modelradius;
8148 loadmodel->radius2 = modelradius * modelradius;
8150 // make sure the temp triangle buffer is big enough for BSP building
8151 maxclippedtriangles = numtriangles*4;
8152 if (numtriangles > 0)
8154 clippedfronttriangles = Mem_Alloc(loadmodel->mempool, maxclippedtriangles * 2 * sizeof(objtriangle_t));
8155 clippedbacktriangles = clippedfronttriangles + maxclippedtriangles;
8158 // 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
8159 loadmodel->brush.num_leafs = 0;
8160 loadmodel->brush.num_nodes = 0;
8161 Mem_ExpandableArray_NewArray(&nodesarray, loadmodel->mempool, sizeof(objnode_t), 1024);
8162 rootnode = Mod_OBJ_BSPNodeForTriangles(triangles, numtriangles, mins, maxs, &nodesarray, maxclippedtriangles, clippedfronttriangles, clippedbacktriangles);
8164 // convert the BSP tree to mnode_t and mleaf_t structures and convert the triangles to msurface_t...
8165 loadmodel->brush.data_leafs = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8166 loadmodel->brush.data_nodes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mnode_t));
8167 loadmodel->brush.data_planes = Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(mplane_t));
8168 loadmodel->brush.num_leafs = 0;
8169 loadmodel->brush.num_nodes = 0;
8170 loadmodel->brush.num_planes = 0;
8171 Mod_OBJ_ConvertAndFreeBSPNode(rootnode);
8173 if (clippedfronttriangles)
8174 Mem_Free(clippedfronttriangles);
8175 maxclippedtriangles = 0;
8176 clippedfronttriangles = NULL;
8177 clippedbacktriangles = NULL;
8179 --- NOTHING DONE PAST THIS POINT ---
8181 loadmodel->numskins = LittleLong(pinmodel->num_skins);
8182 numxyz = LittleLong(pinmodel->num_xyz);
8183 numst = LittleLong(pinmodel->num_st);
8184 loadmodel->surfmesh.num_triangles = LittleLong(pinmodel->num_tris);
8185 loadmodel->numframes = LittleLong(pinmodel->num_frames);
8186 loadmodel->surfmesh.num_morphframes = loadmodel->numframes;
8187 loadmodel->num_poses = loadmodel->surfmesh.num_morphframes;
8188 skinwidth = LittleLong(pinmodel->skinwidth);
8189 skinheight = LittleLong(pinmodel->skinheight);
8190 iskinwidth = 1.0f / skinwidth;
8191 iskinheight = 1.0f / skinheight;
8193 loadmodel->num_surfaces = 1;
8194 loadmodel->nummodelsurfaces = loadmodel->num_surfaces;
8195 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]));
8196 loadmodel->data_surfaces = (msurface_t *)data;data += loadmodel->num_surfaces * sizeof(msurface_t);
8197 loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8198 loadmodel->sortedmodelsurfaces[0] = 0;
8199 loadmodel->animscenes = (animscene_t *)data;data += loadmodel->numframes * sizeof(animscene_t);
8200 loadmodel->surfmesh.data_morphmd2framesize6f = (float *)data;data += loadmodel->numframes * sizeof(float[6]);
8201 loadmodel->surfmesh.data_element3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8202 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += loadmodel->surfmesh.num_triangles * sizeof(int[3]);
8204 loadmodel->synctype = ST_RAND;
8207 inskin = (char *)(base + LittleLong(pinmodel->ofs_skins));
8208 skinfiles = Mod_LoadSkinFiles();
8211 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8212 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8213 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8214 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures, skinfiles, "default", "");
8215 Mod_FreeSkinFiles(skinfiles);
8217 else if (loadmodel->numskins)
8219 // skins found (most likely not a player model)
8220 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8221 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8222 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8223 for (i = 0;i < loadmodel->numskins;i++, inskin += MD2_SKINNAME)
8224 Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i * loadmodel->num_surfaces, inskin, true, true, (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_ALPHA | TEXF_PICMIP | TEXF_COMPRESS);
8228 // no skins (most likely a player model)
8229 loadmodel->numskins = 1;
8230 loadmodel->num_textures = loadmodel->num_surfaces * loadmodel->numskins;
8231 loadmodel->num_texturesperskin = loadmodel->num_surfaces;
8232 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t));
8233 Mod_BuildAliasSkinFromSkinFrame(loadmodel->data_textures, NULL);
8236 loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8237 for (i = 0;i < loadmodel->numskins;i++)
8239 loadmodel->skinscenes[i].firstframe = i;
8240 loadmodel->skinscenes[i].framecount = 1;
8241 loadmodel->skinscenes[i].loop = true;
8242 loadmodel->skinscenes[i].framerate = 10;
8245 // load the triangles and stvert data
8246 inst = (unsigned short *)(base + LittleLong(pinmodel->ofs_st));
8247 intri = (md2triangle_t *)(base + LittleLong(pinmodel->ofs_tris));
8248 md2verthash = (struct md2verthash_s **)Mem_Alloc(tempmempool, 65536 * sizeof(hash));
8249 md2verthashdata = (struct md2verthash_s *)Mem_Alloc(tempmempool, loadmodel->surfmesh.num_triangles * 3 * sizeof(*hash));
8250 // swap the triangle list
8251 loadmodel->surfmesh.num_vertices = 0;
8252 for (i = 0;i < loadmodel->surfmesh.num_triangles;i++)
8254 for (j = 0;j < 3;j++)
8256 xyz = (unsigned short) LittleShort (intri[i].index_xyz[j]);
8257 st = (unsigned short) LittleShort (intri[i].index_st[j]);
8260 Con_Printf("%s has an invalid xyz index (%i) on triangle %i, resetting to 0\n", loadmodel->name, xyz, i);
8265 Con_Printf("%s has an invalid st index (%i) on triangle %i, resetting to 0\n", loadmodel->name, st, i);
8268 hashindex = (xyz * 256 + st) & 65535;
8269 for (hash = md2verthash[hashindex];hash;hash = hash->next)
8270 if (hash->xyz == xyz && hash->st == st)
8274 hash = md2verthashdata + loadmodel->surfmesh.num_vertices++;
8277 hash->next = md2verthash[hashindex];
8278 md2verthash[hashindex] = hash;
8280 loadmodel->surfmesh.data_element3i[i*3+j] = (hash - md2verthashdata);
8284 vertremap = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->surfmesh.num_vertices * sizeof(int));
8285 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));
8286 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
8287 loadmodel->surfmesh.data_morphmdlvertex = (trivertx_t *)data;data += loadmodel->surfmesh.num_vertices * loadmodel->surfmesh.num_morphframes * sizeof(trivertx_t);
8288 for (i = 0;i < loadmodel->surfmesh.num_vertices;i++)
8291 hash = md2verthashdata + i;
8292 vertremap[i] = hash->xyz;
8293 sts = LittleShort(inst[hash->st*2+0]);
8294 stt = LittleShort(inst[hash->st*2+1]);
8295 if (sts < 0 || sts >= skinwidth || stt < 0 || stt >= skinheight)
8297 Con_Printf("%s has an invalid skin coordinate (%i %i) on vert %i, changing to 0 0\n", loadmodel->name, sts, stt, i);
8301 loadmodel->surfmesh.data_texcoordtexture2f[i*2+0] = sts * iskinwidth;
8302 loadmodel->surfmesh.data_texcoordtexture2f[i*2+1] = stt * iskinheight;
8305 Mem_Free(md2verthash);
8306 Mem_Free(md2verthashdata);
8308 // generate ushort elements array if possible
8309 if (loadmodel->surfmesh.num_vertices <= 65536)
8310 loadmodel->surfmesh.data_element3s = (unsigned short *)Mem_Alloc(loadmodel->mempool, sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles);
8313 datapointer = (base + LittleLong(pinmodel->ofs_frames));
8314 for (i = 0;i < loadmodel->surfmesh.num_morphframes;i++)
8319 pinframe = (md2frame_t *)datapointer;
8320 datapointer += sizeof(md2frame_t);
8321 // store the frame scale/translate into the appropriate array
8322 for (j = 0;j < 3;j++)
8324 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+j] = LittleFloat(pinframe->scale[j]);
8325 loadmodel->surfmesh.data_morphmd2framesize6f[i*6+3+j] = LittleFloat(pinframe->translate[j]);
8327 // convert the vertices
8328 v = (trivertx_t *)datapointer;
8329 out = loadmodel->surfmesh.data_morphmdlvertex + i * loadmodel->surfmesh.num_vertices;
8330 for (k = 0;k < loadmodel->surfmesh.num_vertices;k++)
8331 out[k] = v[vertremap[k]];
8332 datapointer += numxyz * sizeof(trivertx_t);
8334 strlcpy(loadmodel->animscenes[i].name, pinframe->name, sizeof(loadmodel->animscenes[i].name));
8335 loadmodel->animscenes[i].firstframe = i;
8336 loadmodel->animscenes[i].framecount = 1;
8337 loadmodel->animscenes[i].framerate = 10;
8338 loadmodel->animscenes[i].loop = true;
8341 Mem_Free(vertremap);
8343 Mod_MakeSortedSurfaces(loadmodel);
8344 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
8345 Mod_Alias_CalculateBoundingBox();
8346 Mod_Alias_MorphMesh_CompileFrames();
8348 surface = loadmodel->data_surfaces;
8349 surface->texture = loadmodel->data_textures;
8350 surface->num_firsttriangle = 0;
8351 surface->num_triangles = loadmodel->surfmesh.num_triangles;
8352 surface->num_firstvertex = 0;
8353 surface->num_vertices = loadmodel->surfmesh.num_vertices;
8355 loadmodel->surfmesh.isanimated = false;
8357 if (loadmodel->surfmesh.data_element3s)
8358 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8359 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8362 #endif // !OBJASMODEL
8364 qboolean Mod_CanSeeBox_Trace(int numsamples, float t, dp_model_t *model, vec3_t eye, vec3_t minsX, vec3_t maxsX)
8366 // we already have done PVS culling at this point...
8367 // so we don't need to do it again.
8370 vec3_t testorigin, mins, maxs;
8372 testorigin[0] = (minsX[0] + maxsX[0]) * 0.5;
8373 testorigin[1] = (minsX[1] + maxsX[1]) * 0.5;
8374 testorigin[2] = (minsX[2] + maxsX[2]) * 0.5;
8376 if(model->brush.TraceLineOfSight(model, eye, testorigin))
8379 // expand the box a little
8380 mins[0] = (t+1) * minsX[0] - t * maxsX[0];
8381 maxs[0] = (t+1) * maxsX[0] - t * minsX[0];
8382 mins[1] = (t+1) * minsX[1] - t * maxsX[1];
8383 maxs[1] = (t+1) * maxsX[1] - t * minsX[1];
8384 mins[2] = (t+1) * minsX[2] - t * maxsX[2];
8385 maxs[2] = (t+1) * maxsX[2] - t * minsX[2];
8387 for(i = 0; i != numsamples; ++i)
8389 testorigin[0] = lhrandom(mins[0], maxs[0]);
8390 testorigin[1] = lhrandom(mins[1], maxs[1]);
8391 testorigin[2] = lhrandom(mins[2], maxs[2]);
8393 if(model->brush.TraceLineOfSight(model, eye, testorigin))