2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
31 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
42 cvar_t r_fxaa = {CVAR_SAVE, "r_fxaa", "0", "fast approximate anti aliasing"};
43 cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
44 cvar_t mod_obj_orientation = {0, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
45 cvar_t mod_q2bsp_littransparentsurfaces = {0, "mod_q2bsp_littransparentsurfaces", "0", "allows lighting on rain in 3v3gloom3 and other cases of transparent surfaces that have lightmaps that were ignored by quake2"};
46 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
47 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)"};
48 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)"};
49 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
50 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
51 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, ..."};
52 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)"};
53 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
54 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
55 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
56 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
57 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
58 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
59 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
60 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
61 cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
63 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)"};
64 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"};
65 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"};
67 static texture_t mod_q1bsp_texture_solid;
68 static texture_t mod_q1bsp_texture_sky;
69 static texture_t mod_q1bsp_texture_lava;
70 static texture_t mod_q1bsp_texture_slime;
71 static texture_t mod_q1bsp_texture_water;
73 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs);
75 void Mod_BrushInit(void)
77 // Cvar_RegisterVariable(&r_subdivide_size);
78 Cvar_RegisterVariable(&mod_bsp_portalize);
79 Cvar_RegisterVariable(&r_novis);
80 Cvar_RegisterVariable(&r_nosurftextures);
81 Cvar_RegisterVariable(&r_subdivisions_tolerance);
82 Cvar_RegisterVariable(&r_subdivisions_mintess);
83 Cvar_RegisterVariable(&r_subdivisions_maxtess);
84 Cvar_RegisterVariable(&r_subdivisions_maxvertices);
85 Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
86 Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
87 Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
88 Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
89 Cvar_RegisterVariable(&r_trippy);
90 Cvar_RegisterVariable(&r_fxaa);
91 Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
92 Cvar_RegisterVariable(&mod_obj_orientation);
93 Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
94 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
95 Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
96 Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
97 Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
98 Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
99 Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
100 Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
101 Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
102 Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
103 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
104 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
105 Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
106 Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
107 Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
108 Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
109 Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
110 Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
111 Cvar_RegisterVariable(&mod_collision_bih);
112 Cvar_RegisterVariable(&mod_recalculatenodeboxes);
114 // these games were made for older DP engines and are no longer
115 // maintained; use this hack to show their textures properly
116 if(gamemode == GAME_NEXUIZ)
117 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
119 memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
120 strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
121 mod_q1bsp_texture_solid.surfaceflags = 0;
122 mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
124 mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
125 strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
126 mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
127 mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
129 mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
130 strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
131 mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
132 mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
134 mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
135 strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
136 mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
137 mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
139 mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
140 strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
141 mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
142 mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
145 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
152 // LordHavoc: modified to start at first clip node,
153 // in other words: first node of the (sub)model
154 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
156 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
158 return (mleaf_t *)node;
161 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
165 leaf = Mod_Q1BSP_PointInLeaf(model, p);
168 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
171 memcpy(out, leaf->ambient_sound_level, i);
177 memset(out, 0, outsize);
180 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
183 int nodestackindex = 0;
184 mnode_t *node, *nodestack[1024];
185 if (!model->brush.num_pvsclusters)
187 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
193 // node - recurse down the BSP tree
194 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
198 return -1; // ERROR: NAN bounding box!
199 // box is on one side of plane, take that path
200 node = node->children[sides-1];
204 // box crosses plane, take one path and remember the other
205 if (nodestackindex < 1024)
206 nodestack[nodestackindex++] = node->children[0];
207 node = node->children[1];
213 // leaf - add clusterindex to list
214 if (numclusters < maxclusters)
215 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
219 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
223 if (nodestackindex < 1024)
224 nodestack[nodestackindex++] = node->children[0];
225 node = node->children[1];
230 // leaf - add clusterindex to list
231 if (numclusters < maxclusters)
232 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
237 // try another path we didn't take earlier
238 if (nodestackindex == 0)
240 node = nodestack[--nodestackindex];
242 // return number of clusters found (even if more than the maxclusters)
246 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
248 int nodestackindex = 0;
249 mnode_t *node, *nodestack[1024];
250 if (!model->brush.num_pvsclusters)
252 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
258 // node - recurse down the BSP tree
259 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
263 return -1; // ERROR: NAN bounding box!
264 // box is on one side of plane, take that path
265 node = node->children[sides-1];
269 // box crosses plane, take one path and remember the other
270 if (nodestackindex < 1024)
271 nodestack[nodestackindex++] = node->children[0];
272 node = node->children[1];
278 // leaf - check cluster bit
279 int clusterindex = ((mleaf_t *)node)->clusterindex;
280 if (CHECKPVSBIT(pvs, clusterindex))
282 // it is visible, return immediately with the news
287 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
291 if (nodestackindex < 1024)
292 nodestack[nodestackindex++] = node->children[0];
293 node = node->children[1];
298 // leaf - check cluster bit
299 int clusterindex = ((mleaf_t *)node)->clusterindex;
300 if (CHECKPVSBIT(pvs, clusterindex))
302 // it is visible, return immediately with the news
308 // nothing to see here, try another path we didn't take earlier
309 if (nodestackindex == 0)
311 node = nodestack[--nodestackindex];
317 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
319 int nodestackindex = 0;
320 mnode_t *node, *nodestack[1024];
321 if (!model->brush.num_leafs)
323 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
329 // node - recurse down the BSP tree
330 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
334 return -1; // ERROR: NAN bounding box!
335 // box is on one side of plane, take that path
336 node = node->children[sides-1];
340 // box crosses plane, take one path and remember the other
341 if (nodestackindex < 1024)
342 nodestack[nodestackindex++] = node->children[0];
343 node = node->children[1];
349 // leaf - check cluster bit
350 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
351 if (CHECKPVSBIT(pvs, clusterindex))
353 // it is visible, return immediately with the news
358 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
362 if (nodestackindex < 1024)
363 nodestack[nodestackindex++] = node->children[0];
364 node = node->children[1];
369 // leaf - check cluster bit
370 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
371 if (CHECKPVSBIT(pvs, clusterindex))
373 // it is visible, return immediately with the news
379 // nothing to see here, try another path we didn't take earlier
380 if (nodestackindex == 0)
382 node = nodestack[--nodestackindex];
388 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
390 int nodestackindex = 0;
391 mnode_t *node, *nodestack[1024];
392 if (!model->brush.num_leafs)
394 node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
400 // node - recurse down the BSP tree
401 int sides = BoxOnPlaneSide(mins, maxs, node->plane);
405 return -1; // ERROR: NAN bounding box!
406 // box is on one side of plane, take that path
407 node = node->children[sides-1];
411 // box crosses plane, take one path and remember the other
412 if (nodestackindex < 1024)
413 nodestack[nodestackindex++] = node->children[0];
414 node = node->children[1];
420 // leaf - check if it is visible
421 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
423 // it is visible, return immediately with the news
428 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
432 if (nodestackindex < 1024)
433 nodestack[nodestackindex++] = node->children[0];
434 node = node->children[1];
439 // leaf - check if it is visible
440 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
442 // it is visible, return immediately with the news
448 // nothing to see here, try another path we didn't take earlier
449 if (nodestackindex == 0)
451 node = nodestack[--nodestackindex];
457 typedef struct findnonsolidlocationinfo_s
460 vec3_t absmin, absmax;
466 findnonsolidlocationinfo_t;
468 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
471 float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
473 tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
474 VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
475 VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
476 VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
477 VectorSubtract(vert[1], vert[0], edge[0]);
478 VectorSubtract(vert[2], vert[1], edge[1]);
479 CrossProduct(edge[1], edge[0], facenormal);
480 if (facenormal[0] || facenormal[1] || facenormal[2])
482 VectorNormalize(facenormal);
483 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
484 if (f <= info->bestdist && f >= -info->bestdist)
486 VectorSubtract(vert[0], vert[2], edge[2]);
487 VectorNormalize(edge[0]);
488 VectorNormalize(edge[1]);
489 VectorNormalize(edge[2]);
490 CrossProduct(facenormal, edge[0], edgenormal[0]);
491 CrossProduct(facenormal, edge[1], edgenormal[1]);
492 CrossProduct(facenormal, edge[2], edgenormal[2]);
494 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
495 && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
496 && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
498 // we got lucky, the center is within the face
499 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
503 if (info->bestdist > dist)
505 info->bestdist = dist;
506 VectorScale(facenormal, (info->radius - -dist), info->nudge);
511 if (info->bestdist > dist)
513 info->bestdist = dist;
514 VectorScale(facenormal, (info->radius - dist), info->nudge);
520 // check which edge or vertex the center is nearest
521 for (i = 0;i < 3;i++)
523 f = DotProduct(info->center, edge[i]);
524 if (f >= DotProduct(vert[0], edge[i])
525 && f <= DotProduct(vert[1], edge[i]))
528 VectorMA(info->center, -f, edge[i], point);
529 dist = sqrt(DotProduct(point, point));
530 if (info->bestdist > dist)
532 info->bestdist = dist;
533 VectorScale(point, (info->radius / dist), info->nudge);
535 // skip both vertex checks
536 // (both are further away than this edge)
541 // not on edge, check first vertex of edge
542 VectorSubtract(info->center, vert[i], point);
543 dist = sqrt(DotProduct(point, point));
544 if (info->bestdist > dist)
546 info->bestdist = dist;
547 VectorScale(point, (info->radius / dist), info->nudge);
556 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
558 int surfacenum, k, *mark;
560 for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
562 surface = info->model->data_surfaces + *mark;
563 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
565 if(surface->deprecatedq3num_bboxstride > 0)
568 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
569 for(i = 0; i < cnt; ++i)
571 if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
573 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
575 tri = i * surface->deprecatedq3num_bboxstride + k;
576 if(tri >= surface->num_triangles)
578 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
585 for (k = 0;k < surface->num_triangles;k++)
587 Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
594 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
598 float f = PlaneDiff(info->center, node->plane);
599 if (f >= -info->bestdist)
600 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
601 if (f <= info->bestdist)
602 Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
606 if (((mleaf_t *)node)->numleafsurfaces)
607 Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
611 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
614 findnonsolidlocationinfo_t info;
620 VectorCopy(in, info.center);
621 info.radius = radius;
626 VectorClear(info.nudge);
627 info.bestdist = radius;
628 VectorCopy(info.center, info.absmin);
629 VectorCopy(info.center, info.absmax);
630 info.absmin[0] -= info.radius + 1;
631 info.absmin[1] -= info.radius + 1;
632 info.absmin[2] -= info.radius + 1;
633 info.absmax[0] += info.radius + 1;
634 info.absmax[1] += info.radius + 1;
635 info.absmax[2] += info.radius + 1;
636 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
637 VectorAdd(info.center, info.nudge, info.center);
639 while (info.bestdist < radius && ++i < 10);
640 VectorCopy(info.center, out);
643 int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
645 switch(nativecontents)
650 return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
652 return SUPERCONTENTS_WATER;
654 return SUPERCONTENTS_SLIME;
656 return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
658 return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
663 int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
665 if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
666 return CONTENTS_SOLID;
667 if (supercontents & SUPERCONTENTS_SKY)
669 if (supercontents & SUPERCONTENTS_LAVA)
670 return CONTENTS_LAVA;
671 if (supercontents & SUPERCONTENTS_SLIME)
672 return CONTENTS_SLIME;
673 if (supercontents & SUPERCONTENTS_WATER)
674 return CONTENTS_WATER;
675 return CONTENTS_EMPTY;
678 typedef struct RecursiveHullCheckTraceInfo_s
680 // the hull we're tracing through
683 // the trace structure to fill in
686 // start, end, and end - start (in model space)
691 RecursiveHullCheckTraceInfo_t;
693 // 1/32 epsilon to keep floating point happy
694 #define DIST_EPSILON (0.03125)
696 #define HULLCHECKSTATE_EMPTY 0
697 #define HULLCHECKSTATE_SOLID 1
698 #define HULLCHECKSTATE_DONE 2
700 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
702 // status variables, these don't need to be saved on the stack when
703 // recursing... but are because this should be thread-safe
704 // (note: tracing against a bbox is not thread-safe, yet)
709 // variables that need to be stored on the stack when recursing
714 // keep looping until we hit a leaf
717 // find the point distances
718 node = t->hull->clipnodes + num;
719 plane = t->hull->planes + node->planenum;
721 // axial planes can be calculated more quickly without the DotProduct
724 t1 = p1[plane->type] - plane->dist;
725 t2 = p2[plane->type] - plane->dist;
729 t1 = DotProduct (plane->normal, p1) - plane->dist;
730 t2 = DotProduct (plane->normal, p2) - plane->dist;
733 // negative plane distances indicate children[1] (behind plane)
737 // if the line starts and ends on the same side of the plane, recurse
738 // into that child instantly
739 if (p1side == p2side)
741 #if COLLISIONPARANOID >= 3
747 // loop back and process the start child
748 num = node->children[p1side];
752 // find the midpoint where the line crosses the plane, use the
753 // original line for best accuracy
754 #if COLLISIONPARANOID >= 3
759 t1 = t->start[plane->type] - plane->dist;
760 t2 = t->end[plane->type] - plane->dist;
764 t1 = DotProduct (plane->normal, t->start) - plane->dist;
765 t2 = DotProduct (plane->normal, t->end) - plane->dist;
767 midf = t1 / (t1 - t2);
768 midf = bound(p1f, midf, p2f);
769 VectorMA(t->start, midf, t->dist, mid);
771 // we now have a mid point, essentially splitting the line into
772 // the segments in the near child and the far child, we can now
773 // recurse those in order and get their results
775 // recurse both sides, front side first
776 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
777 // if this side is not empty, return what it is (solid or done)
778 if (ret != HULLCHECKSTATE_EMPTY)
781 ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
782 // if other side is not solid, return what it is (empty or done)
783 if (ret != HULLCHECKSTATE_SOLID)
786 // front is air and back is solid, this is the impact point...
788 // copy the plane information, flipping it if needed
791 t->trace->plane.dist = -plane->dist;
792 VectorNegate (plane->normal, t->trace->plane.normal);
796 t->trace->plane.dist = plane->dist;
797 VectorCopy (plane->normal, t->trace->plane.normal);
800 // calculate the return fraction which is nudged off the surface a bit
801 t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
802 t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
803 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
804 t->trace->fraction = bound(0, midf, 1);
806 #if COLLISIONPARANOID >= 3
809 return HULLCHECKSTATE_DONE;
813 // we reached a leaf contents
816 num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
817 if (!t->trace->startfound)
819 t->trace->startfound = true;
820 t->trace->startsupercontents |= num;
822 if (num & SUPERCONTENTS_LIQUIDSMASK)
823 t->trace->inwater = true;
825 t->trace->inopen = true;
826 if (num & SUPERCONTENTS_SOLID)
827 t->trace->hittexture = &mod_q1bsp_texture_solid;
828 else if (num & SUPERCONTENTS_SKY)
829 t->trace->hittexture = &mod_q1bsp_texture_sky;
830 else if (num & SUPERCONTENTS_LAVA)
831 t->trace->hittexture = &mod_q1bsp_texture_lava;
832 else if (num & SUPERCONTENTS_SLIME)
833 t->trace->hittexture = &mod_q1bsp_texture_slime;
835 t->trace->hittexture = &mod_q1bsp_texture_water;
836 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
837 t->trace->hitsupercontents = num;
838 if (num & t->trace->hitsupercontentsmask)
840 // if the first leaf is solid, set startsolid
841 if (t->trace->allsolid)
842 t->trace->startsolid = true;
843 #if COLLISIONPARANOID >= 3
846 return HULLCHECKSTATE_SOLID;
850 t->trace->allsolid = false;
851 #if COLLISIONPARANOID >= 3
854 return HULLCHECKSTATE_EMPTY;
858 //#if COLLISIONPARANOID < 2
859 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
862 mclipnode_t *nodes = t->hull->clipnodes;
863 mplane_t *planes = t->hull->planes;
865 VectorCopy(t->start, point);
868 plane = planes + nodes[num].planenum;
869 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
871 num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
872 t->trace->startsupercontents |= num;
873 if (num & SUPERCONTENTS_LIQUIDSMASK)
874 t->trace->inwater = true;
876 t->trace->inopen = true;
877 if (num & t->trace->hitsupercontentsmask)
879 t->trace->allsolid = t->trace->startsolid = true;
880 return HULLCHECKSTATE_SOLID;
884 t->trace->allsolid = t->trace->startsolid = false;
885 return HULLCHECKSTATE_EMPTY;
890 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
892 RecursiveHullCheckTraceInfo_t rhc;
894 memset(&rhc, 0, sizeof(rhc));
895 memset(trace, 0, sizeof(trace_t));
897 rhc.trace->fraction = 1;
898 rhc.trace->allsolid = true;
899 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
900 VectorCopy(start, rhc.start);
901 VectorCopy(start, rhc.end);
902 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
905 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask);
907 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, int skipsupercontentsmask, int skipmaterialflagsmask)
909 RecursiveHullCheckTraceInfo_t rhc;
911 if (VectorCompare(start, end))
913 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
917 // sometimes we want to traceline against polygons so we can report the texture that was hit rather than merely a contents, but using this method breaks one of negke's maps so it must be a cvar check...
918 if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
920 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
924 memset(&rhc, 0, sizeof(rhc));
925 memset(trace, 0, sizeof(trace_t));
927 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
928 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
929 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
930 rhc.trace->fraction = 1;
931 rhc.trace->allsolid = true;
932 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
933 VectorCopy(start, rhc.start);
934 VectorCopy(end, rhc.end);
935 VectorSubtract(rhc.end, rhc.start, rhc.dist);
936 #if COLLISIONPARANOID >= 2
937 Con_Printf("t(%f %f %f,%f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2]);
938 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
943 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
944 memset(&testtrace, 0, sizeof(trace_t));
945 rhc.trace = &testtrace;
946 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
947 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
948 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
949 rhc.trace->fraction = 1;
950 rhc.trace->allsolid = true;
951 VectorCopy(test, rhc.start);
952 VectorCopy(test, rhc.end);
953 VectorClear(rhc.dist);
954 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
955 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
956 if (!trace->startsolid && testtrace.startsolid)
957 Con_Printf(" - ended in solid!\n");
961 if (VectorLength2(rhc.dist))
962 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
964 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
968 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, int skipsupercontentsmask, int skipmaterialflagsmask)
970 // this function currently only supports same size start and end
972 RecursiveHullCheckTraceInfo_t rhc;
974 if (VectorCompare(boxmins, boxmaxs))
976 if (VectorCompare(start, end))
977 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
979 Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
983 memset(&rhc, 0, sizeof(rhc));
984 memset(trace, 0, sizeof(trace_t));
986 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
987 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
988 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
989 rhc.trace->fraction = 1;
990 rhc.trace->allsolid = true;
991 VectorSubtract(boxmaxs, boxmins, boxsize);
993 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
994 else if (model->brush.ishlbsp)
996 // LordHavoc: this has to have a minor tolerance (the .1) because of
997 // minor float precision errors from the box being transformed around
998 if (boxsize[0] < 32.1)
1000 if (boxsize[2] < 54) // pick the nearest of 36 or 72
1001 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
1003 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1006 rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1010 // LordHavoc: this has to have a minor tolerance (the .1) because of
1011 // minor float precision errors from the box being transformed around
1012 if (boxsize[0] < 32.1)
1013 rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1015 rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1017 VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1018 VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1019 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1020 #if COLLISIONPARANOID >= 2
1021 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]);
1022 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1027 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1028 memset(&testtrace, 0, sizeof(trace_t));
1029 rhc.trace = &testtrace;
1030 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1031 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1032 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1033 rhc.trace->fraction = 1;
1034 rhc.trace->allsolid = true;
1035 VectorCopy(test, rhc.start);
1036 VectorCopy(test, rhc.end);
1037 VectorClear(rhc.dist);
1038 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1039 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1040 if (!trace->startsolid && testtrace.startsolid)
1041 Con_Printf(" - ended in solid!\n");
1045 if (VectorLength2(rhc.dist))
1046 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1048 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1052 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1054 int num = model->brushq1.hulls[0].firstclipnode;
1056 mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1057 mplane_t *planes = model->brushq1.hulls[0].planes;
1060 plane = planes + nodes[num].planenum;
1061 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1063 return Mod_Q1BSP_SuperContentsFromNativeContents(num);
1066 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 skipsupercontentsmask, int skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1070 colplanef_t cbox_planes[6];
1072 cbox.hasaabbplanes = true;
1073 cbox.supercontents = boxsupercontents;
1076 cbox.numtriangles = 0;
1077 cbox.planes = cbox_planes;
1079 cbox.elements = NULL;
1087 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];
1088 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];
1089 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];
1090 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];
1091 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];
1092 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];
1093 cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1094 cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1095 cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1096 cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1097 cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1098 cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1099 memset(trace, 0, sizeof(trace_t));
1100 trace->hitsupercontentsmask = hitsupercontentsmask;
1101 trace->skipsupercontentsmask = skipsupercontentsmask;
1102 trace->skipmaterialflagsmask = skipmaterialflagsmask;
1103 trace->fraction = 1;
1104 Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1106 RecursiveHullCheckTraceInfo_t rhc;
1107 static hull_t box_hull;
1108 static mclipnode_t box_clipnodes[6];
1109 static mplane_t box_planes[6];
1110 // fill in a default trace
1111 memset(&rhc, 0, sizeof(rhc));
1112 memset(trace, 0, sizeof(trace_t));
1113 //To keep everything totally uniform, bounding boxes are turned into small
1114 //BSP trees instead of being compared directly.
1115 // create a temp hull from bounding box sizes
1116 box_planes[0].dist = cmaxs[0] - mins[0];
1117 box_planes[1].dist = cmins[0] - maxs[0];
1118 box_planes[2].dist = cmaxs[1] - mins[1];
1119 box_planes[3].dist = cmins[1] - maxs[1];
1120 box_planes[4].dist = cmaxs[2] - mins[2];
1121 box_planes[5].dist = cmins[2] - maxs[2];
1122 #if COLLISIONPARANOID >= 3
1123 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]);
1126 if (box_hull.clipnodes == NULL)
1130 //Set up the planes and clipnodes so that the six floats of a bounding box
1131 //can just be stored out and get a proper hull_t structure.
1133 box_hull.clipnodes = box_clipnodes;
1134 box_hull.planes = box_planes;
1135 box_hull.firstclipnode = 0;
1136 box_hull.lastclipnode = 5;
1138 for (i = 0;i < 6;i++)
1140 box_clipnodes[i].planenum = i;
1144 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1146 box_clipnodes[i].children[side^1] = i + 1;
1148 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1150 box_planes[i].type = i>>1;
1151 box_planes[i].normal[i>>1] = 1;
1155 // trace a line through the generated clipping hull
1156 //rhc.boxsupercontents = boxsupercontents;
1157 rhc.hull = &box_hull;
1159 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1160 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1161 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1162 rhc.trace->fraction = 1;
1163 rhc.trace->allsolid = true;
1164 VectorCopy(start, rhc.start);
1165 VectorCopy(end, rhc.end);
1166 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1167 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1168 //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1169 if (rhc.trace->startsupercontents)
1170 rhc.trace->startsupercontents = boxsupercontents;
1174 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1176 memset(trace, 0, sizeof(trace_t));
1177 trace->fraction = 1;
1178 trace->hitsupercontentsmask = hitsupercontentsmask;
1179 trace->skipsupercontentsmask = skipsupercontentsmask;
1180 trace->skipmaterialflagsmask = skipmaterialflagsmask;
1181 if (BoxesOverlap(start, start, cmins, cmaxs))
1183 trace->startsupercontents |= boxsupercontents;
1184 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1186 trace->startsolid = true;
1187 trace->allsolid = true;
1192 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
1195 Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
1196 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
1199 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)
1203 float mid, distz = endz - startz;
1207 switch (node->plane->type)
1210 node = node->children[x < node->plane->dist];
1211 continue; // loop back and process the new node
1213 node = node->children[y < node->plane->dist];
1214 continue; // loop back and process the new node
1216 side = startz < node->plane->dist;
1217 if ((endz < node->plane->dist) == side)
1219 node = node->children[side];
1220 continue; // loop back and process the new node
1222 // found an intersection
1223 mid = node->plane->dist;
1226 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1227 front += startz * node->plane->normal[2];
1228 back += endz * node->plane->normal[2];
1229 side = front < node->plane->dist;
1230 if ((back < node->plane->dist) == side)
1232 node = node->children[side];
1233 continue; // loop back and process the new node
1235 // found an intersection
1236 mid = startz + distz * (front - node->plane->dist) / (front - back);
1240 // go down front side
1241 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1242 return true; // hit something
1244 // check for impact on this node
1245 if (node->numsurfaces)
1248 int dsi, dti, lmwidth, lmheight;
1250 msurface_t *surface;
1251 unsigned char *lightmap;
1252 int maps, line3, size3;
1255 float scale, w, w00, w01, w10, w11;
1257 surface = model->data_surfaces + node->firstsurface;
1258 for (i = 0;i < node->numsurfaces;i++, surface++)
1260 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1261 continue; // no lightmaps
1263 // location we want to sample in the lightmap
1264 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;
1265 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;
1268 // thanks to jitspoe for pointing out that this int cast was
1269 // rounding toward zero, so we floor it
1270 dsi = (int)floor(ds);
1271 dti = (int)floor(dt);
1272 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1273 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1276 // we have to tolerate a position of lmwidth-1 for some rare
1277 // cases - in which case the sampling position still gets
1278 // clamped but the color gets interpolated to that edge.
1279 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1281 // in the rare cases where we're sampling slightly off
1282 // the polygon, clamp the sampling position (we can still
1283 // interpolate outside it, where it becomes extrapolation)
1288 if (dsi > lmwidth-2)
1290 if (dti > lmheight-2)
1293 // calculate bilinear interpolation factors
1294 // and also multiply by fixedpoint conversion factors to
1295 // compensate for lightmaps being 0-255 (as 0-2), we use
1296 // r_refdef.scene.rtlightstylevalue here which is already
1297 // 0.000-2.148 range
1298 // (if we used r_refdef.scene.lightstylevalue this
1299 // divisor would be 32768 rather than 128)
1302 w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1303 w01 = ( dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1304 w10 = (1 - dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1305 w11 = ( dsfrac) * ( dtfrac) * (1.0f / 128.0f);
1307 // values for pointer math
1308 line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1309 size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1311 // look up the pixel
1312 lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1314 // bilinear filter each lightmap style, and sum them
1315 for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1317 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1318 w = w00 * scale;VectorMA(ambientcolor, w, lightmap , ambientcolor);
1319 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3 , ambientcolor);
1320 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3 , ambientcolor);
1321 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1325 return true; // success
1330 // go down back side
1331 node = node->children[side ^ 1];
1333 distz = endz - startz;
1334 // loop back and process the new node
1337 // did not hit anything
1341 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1343 // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1344 VectorSet(diffusenormal, 0, 0, 1);
1346 if (!model->brushq1.lightdata)
1348 VectorSet(ambientcolor, 1, 1, 1);
1349 VectorSet(diffusecolor, 0, 0, 0);
1353 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);
1356 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1361 const msurface_t *surface;
1366 float edgenormal[3];
1373 surface = model->data_surfaces + node->firstsurface;
1374 for (i = 0;i < node->numsurfaces;i++, surface++)
1376 // skip surfaces whose bounding box does not include the point
1377 // if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1379 // skip faces with contents we don't care about
1380 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1382 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1383 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1385 // skip surfaces matching the skipmaterialflagsmask (e.g. MATERIALFLAG_NOSHADOW)
1386 if (t->trace->skipmaterialflagsmask & surface->texture->currentmaterialflags)
1388 // get the surface normal - since it is flat we know any vertex normal will suffice
1389 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1391 if (DotProduct(t->dist, normal) > 0)
1393 // iterate edges and see if the point is outside one of them
1394 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1396 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1397 VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1398 VectorSubtract(v0, v1, edgedir);
1399 CrossProduct(edgedir, normal, edgenormal);
1400 if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1403 // if the point is outside one of the edges, it is not within the surface
1404 if (j < surface->num_vertices)
1407 // we hit a surface, this is the impact point...
1408 VectorCopy(normal, t->trace->plane.normal);
1409 t->trace->plane.dist = DotProduct(normal, p);
1411 // calculate the return fraction which is nudged off the surface a bit
1412 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1413 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1414 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1415 t->trace->fraction = bound(0, midf, 1);
1417 t->trace->hittexture = surface->texture->currentframe;
1418 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1419 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1420 return surface->texture->currentframe;
1425 static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
1427 const mplane_t *plane;
1430 double midf, mid[3];
1431 const mleaf_t *leaf;
1435 plane = node->plane;
1436 if (plane->type < 3)
1438 t1 = p1[plane->type] - plane->dist;
1439 t2 = p2[plane->type] - plane->dist;
1443 t1 = DotProduct (plane->normal, p1) - plane->dist;
1444 t2 = DotProduct (plane->normal, p2) - plane->dist;
1450 node = node->children[1];
1459 node = node->children[0];
1465 // the line intersects, find intersection point
1466 // LordHavoc: this uses the original trace for maximum accuracy
1467 if (plane->type < 3)
1469 t1 = t->start[plane->type] - plane->dist;
1470 t2 = t->end[plane->type] - plane->dist;
1474 t1 = DotProduct (plane->normal, t->start) - plane->dist;
1475 t2 = DotProduct (plane->normal, t->end) - plane->dist;
1478 midf = t1 / (t1 - t2);
1479 VectorMA(t->start, midf, t->dist, mid);
1481 // recurse both sides, front side first, return if we hit a surface
1482 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1483 return HULLCHECKSTATE_DONE;
1485 // test each surface on the node
1486 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1487 if (t->trace->hittexture)
1488 return HULLCHECKSTATE_DONE;
1490 // recurse back side
1491 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1493 leaf = (const mleaf_t *)node;
1494 side = Mod_Q1BSP_SuperContentsFromNativeContents(leaf->contents);
1495 if (!t->trace->startfound)
1497 t->trace->startfound = true;
1498 t->trace->startsupercontents |= side;
1500 if (side & SUPERCONTENTS_LIQUIDSMASK)
1501 t->trace->inwater = true;
1503 t->trace->inopen = true;
1504 if (side & t->trace->hitsupercontentsmask)
1506 // if the first leaf is solid, set startsolid
1507 if (t->trace->allsolid)
1508 t->trace->startsolid = true;
1509 return HULLCHECKSTATE_SOLID;
1513 t->trace->allsolid = false;
1514 return HULLCHECKSTATE_EMPTY;
1518 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
1520 RecursiveHullCheckTraceInfo_t rhc;
1522 memset(&rhc, 0, sizeof(rhc));
1523 memset(trace, 0, sizeof(trace_t));
1525 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1526 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1527 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1528 rhc.trace->fraction = 1;
1529 rhc.trace->allsolid = true;
1530 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1531 VectorCopy(start, rhc.start);
1532 VectorCopy(end, rhc.end);
1533 VectorSubtract(rhc.end, rhc.start, rhc.dist);
1534 Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1535 VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1538 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1541 unsigned char *outstart = out;
1542 while (out < outend)
1546 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));
1556 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));
1559 for (c = *in++;c > 0;c--)
1563 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));
1574 R_Q1BSP_LoadSplitSky
1576 A sky texture is 256*128, with the right side being a masked overlay
1579 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1584 unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1585 unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1587 // allocate a texture pool if we need it
1588 if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1589 loadmodel->texturepool = R_AllocTexturePool();
1591 if (bytesperpixel == 4)
1593 for (y = 0;y < h;y++)
1595 for (x = 0;x < w;x++)
1597 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1598 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1604 // make an average value for the back to avoid
1605 // a fringe on the top level
1614 for (y = 0;y < h;y++)
1616 for (x = 0;x < w;x++)
1618 p = src[x*width+y+w];
1619 r += palette_rgb[p][0];
1620 g += palette_rgb[p][1];
1621 b += palette_rgb[p][2];
1624 bgra.b[2] = r/(w*h);
1625 bgra.b[1] = g/(w*h);
1626 bgra.b[0] = b/(w*h);
1628 for (y = 0;y < h;y++)
1630 for (x = 0;x < w;x++)
1632 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1634 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1639 loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0 , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1640 loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1641 Mem_Free(solidpixels);
1642 Mem_Free(alphapixels);
1645 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1647 int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0, firstskynoshadowtexture = 0;
1648 skinframe_t *skinframemissing;
1649 texture_t *tx, *tx2, *anims[10], *altanims[10], *currentskynoshadowtexture;
1650 texture_t backuptex;
1651 unsigned char *data, *mtdata;
1653 char mapname[MAX_QPATH], name[MAX_QPATH];
1654 unsigned char zeroopaque[4], zerotrans[4];
1657 Vector4Set(zeroopaque, 0, 0, 0, 255);
1658 Vector4Set(zerotrans, 0, 0, 0, 128);
1660 loadmodel->data_textures = NULL;
1662 // add two slots for notexture walls and notexture liquids, and duplicate
1663 // all sky textures; sky surfaces can be shadow-casting or not, the surface
1664 // loading will choose according to the contents behind the surface
1665 // (necessary to support e1m5 logo shadow which has a SKY contents brush,
1666 // while correctly treating sky textures as occluders in other situations).
1671 nummiptex = MSG_ReadLittleLong(sb);
1672 loadmodel->num_textures = nummiptex + 2;
1673 // save the position so we can go back to it
1674 watermark = sb->readcount;
1675 for (i = 0; i < nummiptex; i++)
1677 doffset = MSG_ReadLittleLong(sb);
1678 if (r_nosurftextures.integer)
1682 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1686 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1688 // copy name, but only up to 16 characters
1689 // (the output buffer can hold more than this, but the input buffer is
1691 for (j = 0; j < 16; j++)
1692 name[j] = MSG_ReadByte(&miptexsb);
1694 // pretty up the buffer (replacing any trailing garbage with 0)
1695 for (j = (int)strlen(name); j < 16; j++)
1698 if (!strncmp(name, "sky", 3))
1702 // bump it back to where we started parsing
1703 sb->readcount = watermark;
1705 firstskynoshadowtexture = loadmodel->num_textures;
1706 loadmodel->num_textures += numsky;
1710 loadmodel->num_textures = 2;
1711 firstskynoshadowtexture = loadmodel->num_textures;
1713 loadmodel->num_texturesperskin = loadmodel->num_textures;
1715 loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1717 // we'll be writing to these in parallel for sky textures
1718 currentskynoshadowtexture = loadmodel->data_textures + firstskynoshadowtexture;
1720 // fill out all slots with notexture
1721 skinframemissing = R_SkinFrame_LoadMissing();
1722 for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1724 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1727 tx->basealpha = 1.0f;
1728 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(loadmodel->mempool, skinframemissing);
1729 tx->materialshaderpass->skinframes[0] = skinframemissing;
1730 tx->currentskinframe = skinframemissing;
1731 tx->basematerialflags = MATERIALFLAG_WALL;
1732 if (i == loadmodel->num_textures - 1)
1734 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1735 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1736 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1740 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1741 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1743 tx->currentframe = tx;
1745 // clear water settings
1748 tx->refractfactor = 1;
1749 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1750 tx->reflectfactor = 1;
1751 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1752 tx->r_water_wateralpha = 1;
1753 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1754 tx->offsetscale = 1;
1756 tx->specularscalemod = 1;
1757 tx->specularpowermod = 1;
1758 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1759 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1760 // JUST GREP FOR "specularscalemod = 1".
1765 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1769 s = loadmodel->name;
1770 if (!strncasecmp(s, "maps/", 5))
1772 FS_StripExtension(s, mapname, sizeof(mapname));
1774 // LordHavoc: mostly rewritten map texture loader
1775 for (i = 0;i < nummiptex;i++)
1777 doffset = MSG_ReadLittleLong(sb);
1778 if (r_nosurftextures.integer)
1782 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1786 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1788 // copy name, but only up to 16 characters
1789 // (the output buffer can hold more than this, but the input buffer is
1791 for (j = 0;j < 16;j++)
1792 name[j] = MSG_ReadByte(&miptexsb);
1794 // pretty up the buffer (replacing any trailing garbage with 0)
1795 for (j = (int)strlen(name);j < 16;j++)
1800 dpsnprintf(name, sizeof(name), "unnamed%i", i);
1801 Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1804 mtwidth = MSG_ReadLittleLong(&miptexsb);
1805 mtheight = MSG_ReadLittleLong(&miptexsb);
1807 j = MSG_ReadLittleLong(&miptexsb);
1811 if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1813 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1816 mtdata = miptexsb.data + j;
1819 if ((mtwidth & 15) || (mtheight & 15))
1820 Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1822 // LordHavoc: force all names to lowercase
1823 for (j = 0;name[j];j++)
1824 if (name[j] >= 'A' && name[j] <= 'Z')
1825 name[j] += 'a' - 'A';
1827 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1828 backuptex = loadmodel->data_textures[i];
1829 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, name, false, false, 0))
1831 loadmodel->data_textures[i] = backuptex;
1833 tx = loadmodel->data_textures + i;
1834 strlcpy(tx->name, name, sizeof(tx->name));
1835 tx->width = mtwidth;
1836 tx->height = mtheight;
1837 tx->basealpha = 1.0f;
1839 // start out with no animation
1840 tx->currentframe = tx;
1841 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1843 if (tx->name[0] == '*')
1845 if (!strncmp(tx->name, "*lava", 5))
1847 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1848 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1850 else if (!strncmp(tx->name, "*slime", 6))
1852 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1853 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1857 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1858 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1861 else if (!strncmp(tx->name, "sky", 3))
1863 tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1864 tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1865 // for the surface traceline we need to hit this surface as a solid...
1866 tx->supercontents |= SUPERCONTENTS_SOLID;
1870 tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1871 tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1874 if (cls.state != ca_dedicated)
1876 // LordHavoc: HL sky textures are entirely different than quake
1877 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1879 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1881 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1882 if (data && image_width == image_height * 2)
1884 R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1887 else if (mtdata != NULL)
1888 R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1892 skinframe_t *skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false, false);
1894 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false, false);
1896 tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1899 // did not find external texture, load it from the bsp or wad3
1900 if (loadmodel->brush.ishlbsp)
1902 // internal texture overrides wad
1903 unsigned char *pixels, *freepixels;
1904 pixels = freepixels = NULL;
1906 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1908 pixels = freepixels = W_GetTextureBGRA(tx->name);
1911 tx->width = image_width;
1912 tx->height = image_height;
1913 skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1916 Mem_Free(freepixels);
1918 else if (mtdata) // texture included
1919 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1921 // if skinframe is still NULL the "missing" texture has already been assigned to this
1923 tx->materialshaderpass->skinframes[0] = skinframe;
1925 // LordHavoc: some Tenebrae textures get replaced by black
1926 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1927 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1928 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1929 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1930 tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1933 tx->basematerialflags = MATERIALFLAG_WALL;
1934 if (tx->name[0] == '*')
1936 // LordHavoc: some turbulent textures should not be affected by wateralpha
1937 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1938 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1939 else if (!strncmp(tx->name,"*lava",5)
1940 || !strncmp(tx->name,"*teleport",9)
1941 || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1942 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1944 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1945 if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1946 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1948 else if (tx->name[0] == '{') // fence textures
1950 tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1952 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1954 // replace the texture with black
1955 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1957 else if (!strncmp(tx->name, "sky", 3))
1958 tx->basematerialflags = MATERIALFLAG_SKY;
1959 else if (!strcmp(tx->name, "caulk"))
1960 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1961 else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1962 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1963 tx->currentmaterialflags = tx->basematerialflags;
1965 // duplicate of sky with NOSHADOW
1966 if (tx->basematerialflags & MATERIALFLAG_SKY)
1968 *currentskynoshadowtexture = *tx;
1969 currentskynoshadowtexture->basematerialflags |= MATERIALFLAG_NOSHADOW;
1970 tx->skynoshadowtexture = currentskynoshadowtexture;
1971 currentskynoshadowtexture++;
1975 // sequence the animations
1976 for (i = 0;i < nummiptex;i++)
1978 tx = loadmodel->data_textures + i;
1979 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1982 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1984 Con_Printf("Bad animating texture %s\n", tx->name);
1987 if (tx->anim_total[0] || tx->anim_total[1])
1988 continue; // already sequenced
1990 // find the number of frames in the animation
1991 memset(anims, 0, sizeof(anims));
1992 memset(altanims, 0, sizeof(altanims));
1994 for (j = i;j < nummiptex;j++)
1996 tx2 = loadmodel->data_textures + j;
1997 if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
2001 if (num >= '0' && num <= '9')
2002 anims[num - '0'] = tx2;
2003 else if (num >= 'a' && num <= 'j')
2004 altanims[num - 'a'] = tx2;
2005 // No need to warn otherwise - we already did above.
2009 for (j = 0;j < 10;j++)
2016 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
2019 for (j = 0;j < max;j++)
2023 Con_Printf("Missing frame %i of %s\n", j, tx->name);
2027 for (j = 0;j < altmax;j++)
2031 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
2038 // If we have exactly one frame, something's wrong.
2039 if (max + altmax <= 1)
2041 Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
2046 // if there is no alternate animation, duplicate the primary
2047 // animation into the alternate
2049 for (k = 0;k < 10;k++)
2050 altanims[k] = anims[k];
2056 Con_Printf("Missing frame 0 of %s\n", tx->name);
2058 // however, we can handle this by duplicating the alternate animation into the primary
2060 for (k = 0;k < 10;k++)
2061 anims[k] = altanims[k];
2065 // link together the primary animation
2066 for (j = 0;j < max;j++)
2069 tx2->animated = 1; // q1bsp
2070 tx2->anim_total[0] = max;
2071 tx2->anim_total[1] = altmax;
2072 for (k = 0;k < 10;k++)
2074 tx2->anim_frames[0][k] = anims[k];
2075 tx2->anim_frames[1][k] = altanims[k];
2079 // if there really is an alternate anim...
2080 if (anims[0] != altanims[0])
2082 // link together the alternate animation
2083 for (j = 0;j < altmax;j++)
2086 tx2->animated = 1; // q1bsp
2087 // the primary/alternate are reversed here
2088 tx2->anim_total[0] = altmax;
2089 tx2->anim_total[1] = max;
2090 for (k = 0;k < 10;k++)
2092 tx2->anim_frames[0][k] = altanims[k];
2093 tx2->anim_frames[1][k] = anims[k];
2100 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2103 unsigned char *in, *out, *data, d;
2104 char litfilename[MAX_QPATH];
2105 char dlitfilename[MAX_QPATH];
2106 fs_offset_t filesize;
2107 if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2109 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2110 for (i = 0;i < sb->cursize;i++)
2111 loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2113 else // LordHavoc: bsp version 29 (normal white lighting)
2115 // LordHavoc: hope is not lost yet, check for a .lit file to load
2116 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2117 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2118 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2119 strlcat (litfilename, ".lit", sizeof (litfilename));
2120 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2121 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2124 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2126 i = LittleLong(((int *)data)[1]);
2129 if (developer_loading.integer)
2130 Con_Printf("loaded %s\n", litfilename);
2131 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2132 memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2134 data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2137 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2139 i = LittleLong(((int *)data)[1]);
2142 if (developer_loading.integer)
2143 Con_Printf("loaded %s\n", dlitfilename);
2144 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2145 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2146 loadmodel->brushq3.deluxemapping_modelspace = false;
2147 loadmodel->brushq3.deluxemapping = true;
2156 Con_Printf("Unknown .lit file version (%d)\n", i);
2158 else if (filesize == 8)
2159 Con_Print("Empty .lit file, ignoring\n");
2161 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2168 // LordHavoc: oh well, expand the white lighting data
2171 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2173 out = loadmodel->brushq1.lightdata;
2174 for (i = 0;i < sb->cursize;i++)
2184 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2186 loadmodel->brushq1.num_compressedpvs = 0;
2187 loadmodel->brushq1.data_compressedpvs = NULL;
2190 loadmodel->brushq1.num_compressedpvs = sb->cursize;
2191 loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2192 MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2195 // used only for HalfLife maps
2196 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2198 char key[128], value[4096];
2202 if (!COM_ParseToken_Simple(&data, false, false, true))
2204 if (com_token[0] != '{')
2208 if (!COM_ParseToken_Simple(&data, false, false, true))
2210 if (com_token[0] == '}')
2211 break; // end of worldspawn
2212 if (com_token[0] == '_')
2213 strlcpy(key, com_token + 1, sizeof(key));
2215 strlcpy(key, com_token, sizeof(key));
2216 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2217 key[strlen(key)-1] = 0;
2218 if (!COM_ParseToken_Simple(&data, false, false, true))
2220 dpsnprintf(value, sizeof(value), "%s", com_token);
2221 if (!strcmp("wad", key)) // for HalfLife maps
2223 if (loadmodel->brush.ishlbsp)
2226 for (i = 0;i < (int)sizeof(value);i++)
2227 if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2229 if (i < (int)sizeof(value) && value[i])
2231 for (;i < (int)sizeof(value);i++)
2233 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2234 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2236 else if (value[i] == ';' || value[i] == 0)
2240 W_LoadTextureWadFile(&value[j], false);
2252 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2254 loadmodel->brush.entities = NULL;
2257 loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2258 MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2259 loadmodel->brush.entities[sb->cursize] = 0;
2260 if (loadmodel->brush.ishlbsp)
2261 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2265 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2269 int structsize = 12;
2271 if (sb->cursize % structsize)
2272 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2273 count = sb->cursize / structsize;
2274 out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2276 loadmodel->brushq1.vertexes = out;
2277 loadmodel->brushq1.numvertexes = count;
2279 for ( i=0 ; i<count ; i++, out++)
2281 out->position[0] = MSG_ReadLittleFloat(sb);
2282 out->position[1] = MSG_ReadLittleFloat(sb);
2283 out->position[2] = MSG_ReadLittleFloat(sb);
2287 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2291 int structsize = (48+4*hullinfo->filehulls);
2293 if (sb->cursize % structsize)
2294 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2296 count = sb->cursize / structsize;
2297 out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2299 loadmodel->brushq1.submodels = out;
2300 loadmodel->brush.numsubmodels = count;
2302 for (i = 0; i < count; i++, out++)
2304 // spread out the mins / maxs by a pixel
2305 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2306 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2307 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2308 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2309 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2310 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2311 out->origin[0] = MSG_ReadLittleFloat(sb);
2312 out->origin[1] = MSG_ReadLittleFloat(sb);
2313 out->origin[2] = MSG_ReadLittleFloat(sb);
2314 for (j = 0; j < hullinfo->filehulls; j++)
2315 out->headnode[j] = MSG_ReadLittleLong(sb);
2316 out->visleafs = MSG_ReadLittleLong(sb);
2317 out->firstface = MSG_ReadLittleLong(sb);
2318 out->numfaces = MSG_ReadLittleLong(sb);
2322 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2326 int structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2328 if (sb->cursize % structsize)
2329 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2330 count = sb->cursize / structsize;
2331 out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2333 loadmodel->brushq1.edges = out;
2334 loadmodel->brushq1.numedges = count;
2336 for ( i=0 ; i<count ; i++, out++)
2338 if (loadmodel->brush.isbsp2)
2340 out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2341 out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2345 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2346 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2348 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2350 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);
2351 if(!loadmodel->brushq1.numvertexes)
2352 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2360 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2363 int i, j, k, count, miptex;
2364 int structsize = 40;
2366 if (sb->cursize % structsize)
2367 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2368 count = sb->cursize / structsize;
2369 out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2371 loadmodel->brushq1.texinfo = out;
2372 loadmodel->brushq1.numtexinfo = count;
2374 for (i = 0;i < count;i++, out++)
2376 for (k = 0;k < 2;k++)
2377 for (j = 0;j < 4;j++)
2378 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2380 miptex = MSG_ReadLittleLong(sb);
2381 out->q1flags = MSG_ReadLittleLong(sb);
2383 if (out->q1flags & TEX_SPECIAL)
2385 // if texture chosen is NULL or the shader needs a lightmap,
2386 // force to notexture water shader
2387 out->textureindex = loadmodel->num_textures - 1;
2391 // if texture chosen is NULL, force to notexture
2392 out->textureindex = loadmodel->num_textures - 2;
2394 // see if the specified miptex is valid and try to use it instead
2395 if (loadmodel->data_textures)
2397 if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2398 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2400 out->textureindex = miptex;
2406 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2411 mins[0] = mins[1] = mins[2] = 9999;
2412 maxs[0] = maxs[1] = maxs[2] = -9999;
2414 for (i = 0;i < numverts;i++)
2416 for (j = 0;j < 3;j++, v++)
2426 #define MAX_SUBDIVPOLYTRIANGLES 4096
2427 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2429 static int subdivpolyverts, subdivpolytriangles;
2430 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2431 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2433 static int subdivpolylookupvert(vec3_t v)
2436 for (i = 0;i < subdivpolyverts;i++)
2437 if (subdivpolyvert[i][0] == v[0]
2438 && subdivpolyvert[i][1] == v[1]
2439 && subdivpolyvert[i][2] == v[2])
2441 if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2442 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2443 VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2444 return subdivpolyverts++;
2447 static void SubdividePolygon(int numverts, float *verts)
2449 int i, i1, i2, i3, f, b, c, p;
2450 vec3_t mins, maxs, front[256], back[256];
2451 float m, *pv, *cv, dist[256], frac;
2454 Host_Error("SubdividePolygon: ran out of verts in buffer");
2456 BoundPoly(numverts, verts, mins, maxs);
2458 for (i = 0;i < 3;i++)
2460 m = (mins[i] + maxs[i]) * 0.5;
2461 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2462 if (maxs[i] - m < 8)
2464 if (m - mins[i] < 8)
2468 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2469 dist[c] = cv[i] - m;
2472 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2476 VectorCopy(pv, front[f]);
2481 VectorCopy(pv, back[b]);
2484 if (dist[p] == 0 || dist[c] == 0)
2486 if ((dist[p] > 0) != (dist[c] > 0) )
2489 frac = dist[p] / (dist[p] - dist[c]);
2490 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2491 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2492 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2498 SubdividePolygon(f, front[0]);
2499 SubdividePolygon(b, back[0]);
2503 i1 = subdivpolylookupvert(verts);
2504 i2 = subdivpolylookupvert(verts + 3);
2505 for (i = 2;i < numverts;i++)
2507 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2509 Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2513 i3 = subdivpolylookupvert(verts + i * 3);
2514 subdivpolyindex[subdivpolytriangles][0] = i1;
2515 subdivpolyindex[subdivpolytriangles][1] = i2;
2516 subdivpolyindex[subdivpolytriangles][2] = i3;
2518 subdivpolytriangles++;
2522 //Breaks a polygon up along axial 64 unit
2523 //boundaries so that turbulent and sky warps
2524 //can be done reasonably.
2525 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2531 subdivpolytriangles = 0;
2532 subdivpolyverts = 0;
2533 SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2534 if (subdivpolytriangles < 1)
2535 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2537 surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2538 mesh->num_vertices = subdivpolyverts;
2539 mesh->num_triangles = subdivpolytriangles;
2540 mesh->vertex = (surfvertex_t *)(mesh + 1);
2541 mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2542 memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2544 for (i = 0;i < mesh->num_triangles;i++)
2545 for (j = 0;j < 3;j++)
2546 mesh->index[i*3+j] = subdivpolyindex[i][j];
2548 for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2550 VectorCopy(subdivpolyvert[i], v->v);
2551 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2552 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2557 extern cvar_t gl_max_lightmapsize;
2558 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2560 msurface_t *surface;
2561 int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2562 float texmins[2], texmaxs[2], val;
2563 rtexture_t *lightmaptexture, *deluxemaptexture;
2565 int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2567 if (sb->cursize % structsize)
2568 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2569 count = sb->cursize / structsize;
2570 loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2571 loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2573 loadmodel->num_surfaces = count;
2575 loadmodel->brushq1.firstrender = true;
2576 loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2580 for (surfacenum = 0;surfacenum < count;surfacenum++)
2582 if (loadmodel->brush.isbsp2)
2583 numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2585 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2586 totalverts += numedges;
2587 totaltris += numedges - 2;
2590 Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2592 lightmaptexture = NULL;
2593 deluxemaptexture = r_texture_blanknormalmap;
2595 lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2596 totallightmapsamples = 0;
2600 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2602 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2603 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2604 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2605 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2606 firstedge = MSG_ReadLittleLong(sb);
2607 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2608 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2609 for (i = 0;i < MAXLIGHTMAPS;i++)
2610 surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2611 lightmapoffset = MSG_ReadLittleLong(sb);
2613 // FIXME: validate edges, texinfo, etc?
2614 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)
2615 Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2616 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2617 Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2618 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2619 Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2621 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2622 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2624 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2625 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2626 lightmapoffset = -1;
2628 //surface->flags = surface->texture->flags;
2629 //if (LittleShort(in->side))
2630 // surface->flags |= SURF_PLANEBACK;
2631 //surface->plane = loadmodel->brush.data_planes + planenum;
2633 surface->num_firstvertex = totalverts;
2634 surface->num_vertices = numedges;
2635 surface->num_firsttriangle = totaltris;
2636 surface->num_triangles = numedges - 2;
2637 totalverts += numedges;
2638 totaltris += numedges - 2;
2640 // convert edges back to a normal polygon
2641 for (i = 0;i < surface->num_vertices;i++)
2643 int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2645 // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2647 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2649 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2650 s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2651 t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2652 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2653 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2654 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2655 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2656 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2659 for (i = 0;i < surface->num_triangles;i++)
2661 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2662 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2663 (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2666 // compile additional data about the surface geometry
2667 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
2668 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
2669 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2671 // generate surface extents information
2672 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2673 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2674 for (i = 1;i < surface->num_vertices;i++)
2676 for (j = 0;j < 2;j++)
2678 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2679 texmins[j] = min(texmins[j], val);
2680 texmaxs[j] = max(texmaxs[j], val);
2683 for (i = 0;i < 2;i++)
2685 surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2686 surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2689 smax = surface->lightmapinfo->extents[0] >> 4;
2690 tmax = surface->lightmapinfo->extents[1] >> 4;
2691 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2692 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2695 surface->lightmaptexture = NULL;
2696 surface->deluxemaptexture = r_texture_blanknormalmap;
2697 if (lightmapoffset == -1)
2699 surface->lightmapinfo->samples = NULL;
2701 // give non-lightmapped water a 1x white lightmap
2702 if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2704 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2705 surface->lightmapinfo->styles[0] = 0;
2706 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2710 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
2711 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2712 else // LordHavoc: white lighting (bsp version 29)
2714 surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2715 if (loadmodel->brushq1.nmaplightdata)
2716 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2719 // check if we should apply a lightmap to this
2720 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2722 if (ssize > 256 || tsize > 256)
2723 Host_Error("Bad surface extents");
2725 if (lightmapsize < ssize)
2726 lightmapsize = ssize;
2727 if (lightmapsize < tsize)
2728 lightmapsize = tsize;
2730 totallightmapsamples += ssize*tsize;
2732 // force lightmap upload on first time seeing the surface
2734 // additionally this is used by the later code to see if a
2735 // lightmap is needed on this surface (rather than duplicating the
2737 loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2738 loadmodel->lit = true;
2742 // small maps (such as ammo boxes especially) don't need big lightmap
2743 // textures, so this code tries to guess a good size based on
2744 // totallightmapsamples (size of the lightmaps lump basically), as well as
2745 // trying to max out the size if there is a lot of lightmap data to store
2746 // additionally, never choose a lightmapsize that is smaller than the
2747 // largest surface encountered (as it would fail)
2749 for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2752 // now that we've decided the lightmap texture size, we can do the rest
2753 if (cls.state != ca_dedicated)
2755 int stainmapsize = 0;
2756 mod_alloclightmap_state_t allocState;
2758 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2759 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2761 int iu, iv, lightmapx = 0, lightmapy = 0;
2762 float u, v, ubase, vbase, uscale, vscale;
2764 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2767 smax = surface->lightmapinfo->extents[0] >> 4;
2768 tmax = surface->lightmapinfo->extents[1] >> 4;
2769 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2770 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2771 stainmapsize += ssize * tsize * 3;
2773 if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2775 // allocate a texture pool if we need it
2776 if (loadmodel->texturepool == NULL)
2777 loadmodel->texturepool = R_AllocTexturePool();
2778 // could not find room, make a new lightmap
2779 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2780 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2781 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2782 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2783 if (loadmodel->brushq1.nmaplightdata)
2784 loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2786 Mod_AllocLightmap_Reset(&allocState);
2787 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2789 surface->lightmaptexture = lightmaptexture;
2790 surface->deluxemaptexture = deluxemaptexture;
2791 surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2792 surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2794 uscale = 1.0f / (float)lightmapsize;
2795 vscale = 1.0f / (float)lightmapsize;
2796 ubase = lightmapx * uscale;
2797 vbase = lightmapy * vscale;
2799 for (i = 0;i < surface->num_vertices;i++)
2801 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);
2802 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);
2803 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2804 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2805 // LordHavoc: calc lightmap data offset for vertex lighting to use
2808 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2812 if (cl_stainmaps.integer)
2814 // allocate stainmaps for permanent marks on walls and clear white
2815 unsigned char *stainsamples = NULL;
2816 stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2817 memset(stainsamples, 255, stainmapsize);
2819 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2821 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2823 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2824 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2825 surface->lightmapinfo->stainsamples = stainsamples;
2826 stainsamples += ssize * tsize * 3;
2831 // generate ushort elements array if possible
2832 if (loadmodel->surfmesh.data_element3s)
2833 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2834 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2837 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2840 // Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2841 node->parent = parent;
2844 // this is a node, recurse to children
2845 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2846 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2847 // combine supercontents of children
2848 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2853 mleaf_t *leaf = (mleaf_t *)node;
2854 // if this is a leaf, calculate supercontents mask from all collidable
2855 // primitives in the leaf (brushes and collision surfaces)
2856 // also flag if the leaf contains any collision surfaces
2857 leaf->combinedsupercontents = 0;
2858 // combine the supercontents values of all brushes in this leaf
2859 for (j = 0;j < leaf->numleafbrushes;j++)
2860 leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2861 // check if this leaf contains any collision surfaces (q3 patches)
2862 for (j = 0;j < leaf->numleafsurfaces;j++)
2864 msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2865 if (surface->num_collisiontriangles)
2867 leaf->containscollisionsurfaces = true;
2868 leaf->combinedsupercontents |= surface->texture->supercontents;
2874 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2876 int i, j, count, p, child[2];
2878 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2880 if (sb->cursize % structsize)
2881 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2882 count = sb->cursize / structsize;
2884 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2885 out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2887 loadmodel->brush.data_nodes = out;
2888 loadmodel->brush.num_nodes = count;
2890 for ( i=0 ; i<count ; i++, out++)
2892 p = MSG_ReadLittleLong(sb);
2893 out->plane = loadmodel->brush.data_planes + p;
2895 if (loadmodel->brush.isbsp2rmqe)
2897 child[0] = MSG_ReadLittleLong(sb);
2898 child[1] = MSG_ReadLittleLong(sb);
2899 out->mins[0] = MSG_ReadLittleShort(sb);
2900 out->mins[1] = MSG_ReadLittleShort(sb);
2901 out->mins[2] = MSG_ReadLittleShort(sb);
2902 out->maxs[0] = MSG_ReadLittleShort(sb);
2903 out->maxs[1] = MSG_ReadLittleShort(sb);
2904 out->maxs[2] = MSG_ReadLittleShort(sb);
2905 out->firstsurface = MSG_ReadLittleLong(sb);
2906 out->numsurfaces = MSG_ReadLittleLong(sb);
2908 else if (loadmodel->brush.isbsp2)
2910 child[0] = MSG_ReadLittleLong(sb);
2911 child[1] = MSG_ReadLittleLong(sb);
2912 out->mins[0] = MSG_ReadLittleFloat(sb);
2913 out->mins[1] = MSG_ReadLittleFloat(sb);
2914 out->mins[2] = MSG_ReadLittleFloat(sb);
2915 out->maxs[0] = MSG_ReadLittleFloat(sb);
2916 out->maxs[1] = MSG_ReadLittleFloat(sb);
2917 out->maxs[2] = MSG_ReadLittleFloat(sb);
2918 out->firstsurface = MSG_ReadLittleLong(sb);
2919 out->numsurfaces = MSG_ReadLittleLong(sb);
2923 child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2924 child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2925 if (child[0] >= count)
2927 if (child[1] >= count)
2930 out->mins[0] = MSG_ReadLittleShort(sb);
2931 out->mins[1] = MSG_ReadLittleShort(sb);
2932 out->mins[2] = MSG_ReadLittleShort(sb);
2933 out->maxs[0] = MSG_ReadLittleShort(sb);
2934 out->maxs[1] = MSG_ReadLittleShort(sb);
2935 out->maxs[2] = MSG_ReadLittleShort(sb);
2937 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2938 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2941 for (j=0 ; j<2 ; j++)
2943 // LordHavoc: this code supports broken bsp files produced by
2944 // arguire qbsp which can produce more than 32768 nodes, any value
2945 // below count is assumed to be a node number, any other value is
2946 // assumed to be a leaf number
2950 if (p < loadmodel->brush.num_nodes)
2951 out->children[j] = loadmodel->brush.data_nodes + p;
2954 Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2955 // map it to the solid leaf
2956 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2961 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2963 if (p < loadmodel->brush.num_leafs)
2964 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2967 Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2968 // map it to the solid leaf
2969 out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2975 Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL); // sets nodes and leafs
2978 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2981 int i, j, count, p, firstmarksurface, nummarksurfaces;
2982 int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2984 if (sb->cursize % structsize)
2985 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2986 count = sb->cursize / structsize;
2987 out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2989 loadmodel->brush.data_leafs = out;
2990 loadmodel->brush.num_leafs = count;
2991 // get visleafs from the submodel data
2992 loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2993 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2994 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2995 memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2997 // FIXME: this function could really benefit from some error checking
2998 for ( i=0 ; i<count ; i++, out++)
3000 out->contents = MSG_ReadLittleLong(sb);
3002 out->clusterindex = i - 1;
3003 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
3004 out->clusterindex = -1;
3006 p = MSG_ReadLittleLong(sb);
3007 // ignore visofs errors on leaf 0 (solid)
3008 if (p >= 0 && out->clusterindex >= 0)
3010 if (p >= loadmodel->brushq1.num_compressedpvs)
3011 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
3013 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);
3016 if (loadmodel->brush.isbsp2rmqe)
3018 out->mins[0] = MSG_ReadLittleShort(sb);
3019 out->mins[1] = MSG_ReadLittleShort(sb);
3020 out->mins[2] = MSG_ReadLittleShort(sb);
3021 out->maxs[0] = MSG_ReadLittleShort(sb);
3022 out->maxs[1] = MSG_ReadLittleShort(sb);
3023 out->maxs[2] = MSG_ReadLittleShort(sb);
3025 firstmarksurface = MSG_ReadLittleLong(sb);
3026 nummarksurfaces = MSG_ReadLittleLong(sb);
3028 else if (loadmodel->brush.isbsp2)
3030 out->mins[0] = MSG_ReadLittleFloat(sb);
3031 out->mins[1] = MSG_ReadLittleFloat(sb);
3032 out->mins[2] = MSG_ReadLittleFloat(sb);
3033 out->maxs[0] = MSG_ReadLittleFloat(sb);
3034 out->maxs[1] = MSG_ReadLittleFloat(sb);
3035 out->maxs[2] = MSG_ReadLittleFloat(sb);
3037 firstmarksurface = MSG_ReadLittleLong(sb);
3038 nummarksurfaces = MSG_ReadLittleLong(sb);
3042 out->mins[0] = MSG_ReadLittleShort(sb);
3043 out->mins[1] = MSG_ReadLittleShort(sb);
3044 out->mins[2] = MSG_ReadLittleShort(sb);
3045 out->maxs[0] = MSG_ReadLittleShort(sb);
3046 out->maxs[1] = MSG_ReadLittleShort(sb);
3047 out->maxs[2] = MSG_ReadLittleShort(sb);
3049 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
3050 nummarksurfaces = (unsigned short)MSG_ReadLittleShort(sb);
3053 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
3055 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3056 out->numleafsurfaces = nummarksurfaces;
3060 Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3061 out->firstleafsurface = NULL;
3062 out->numleafsurfaces = 0;
3065 for (j = 0;j < 4;j++)
3066 out->ambient_sound_level[j] = MSG_ReadByte(sb);
3070 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
3074 const unsigned char *pvs;
3075 // if there's no vis data, assume supported (because everything is visible all the time)
3076 if (!loadmodel->brush.data_pvsclusters)
3078 // check all liquid leafs to see if they can see into empty leafs, if any
3079 // can we can assume this map supports r_wateralpha
3080 for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3082 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3084 pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3085 for (j = 0;j < loadmodel->brush.num_leafs;j++)
3086 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3093 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3098 int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3100 if (sb->cursize % structsize)
3101 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3102 count = sb->cursize / structsize;
3103 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3105 loadmodel->brushq1.clipnodes = out;
3106 loadmodel->brushq1.numclipnodes = count;
3108 for (i = 1; i < MAX_MAP_HULLS; i++)
3110 hull = &loadmodel->brushq1.hulls[i];
3111 hull->clipnodes = out;
3112 hull->firstclipnode = 0;
3113 hull->lastclipnode = count-1;
3114 hull->planes = loadmodel->brush.data_planes;
3115 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3116 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3117 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3118 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3119 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3120 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3121 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3124 for (i=0 ; i<count ; i++, out++)
3126 out->planenum = MSG_ReadLittleLong(sb);
3127 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3128 Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3129 if (loadmodel->brush.isbsp2)
3131 out->children[0] = MSG_ReadLittleLong(sb);
3132 out->children[1] = MSG_ReadLittleLong(sb);
3133 if (out->children[0] >= count)
3134 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3135 if (out->children[1] >= count)
3136 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3140 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3141 out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3142 out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3143 if (out->children[0] >= count)
3144 out->children[0] -= 65536;
3145 if (out->children[1] >= count)
3146 out->children[1] -= 65536;
3151 //Duplicate the drawing hull structure as a clipping hull
3152 static void Mod_Q1BSP_MakeHull0(void)
3159 hull = &loadmodel->brushq1.hulls[0];
3161 in = loadmodel->brush.data_nodes;
3162 out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3164 hull->clipnodes = out;
3165 hull->firstclipnode = 0;
3166 hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3167 hull->planes = loadmodel->brush.data_planes;
3169 for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3171 out->planenum = in->plane - loadmodel->brush.data_planes;
3172 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3173 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3177 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3180 int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3182 if (sb->cursize % structsize)
3183 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3184 loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3185 loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3187 if (loadmodel->brush.isbsp2)
3189 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3191 j = MSG_ReadLittleLong(sb);
3192 if (j < 0 || j >= loadmodel->num_surfaces)
3193 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3194 loadmodel->brush.data_leafsurfaces[i] = j;
3199 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3201 j = (unsigned short) MSG_ReadLittleShort(sb);
3202 if (j >= loadmodel->num_surfaces)
3203 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3204 loadmodel->brush.data_leafsurfaces[i] = j;
3209 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3214 if (sb->cursize % structsize)
3215 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3216 loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3217 loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3219 for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3220 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3224 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3228 int structsize = 20;
3230 if (sb->cursize % structsize)
3231 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3232 loadmodel->brush.num_planes = sb->cursize / structsize;
3233 loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3235 for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3237 out->normal[0] = MSG_ReadLittleFloat(sb);
3238 out->normal[1] = MSG_ReadLittleFloat(sb);
3239 out->normal[2] = MSG_ReadLittleFloat(sb);
3240 out->dist = MSG_ReadLittleFloat(sb);
3241 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3246 // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
3247 static void Mod_Q1BSP_AssignNoShadowSkySurfaces(dp_model_t *mod)
3250 msurface_t *surface;
3253 for (i = 0, surface = mod->data_surfaces + mod->firstmodelsurface; i < mod->nummodelsurfaces; i++, surface++)
3255 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3257 // check if the point behind the surface polygon is SOLID or SKY contents
3258 VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
3259 contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
3260 if (!(contents & SUPERCONTENTS_SOLID))
3261 surface->texture = surface->texture->skynoshadowtexture;
3266 static void Mod_Q1BSP_LoadMapBrushes(void)
3270 int submodel, numbrushes;
3271 qboolean firstbrush;
3272 char *text, *maptext;
3273 char mapfilename[MAX_QPATH];
3274 FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3275 strlcat (mapfilename, ".map", sizeof (mapfilename));
3276 maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3280 if (!COM_ParseToken_Simple(&data, false, false, true))
3285 if (!COM_ParseToken_Simple(&data, false, false, true))
3287 if (com_token[0] != '{')
3293 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3296 if (!COM_ParseToken_Simple(&data, false, false, true))
3298 if (com_token[0] == '}')
3299 break; // end of entity
3300 if (com_token[0] == '{')
3307 if (submodel > loadmodel->brush.numsubmodels)
3309 Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3313 model = loadmodel->brush.submodels[submodel];