BIH building and recursion no longer directly links leaf nodes into the
[xonotic/darkplaces.git] / model_brush.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "curves.h"
26 #include "wad.h"
27
28
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 mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
42 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
43 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
44 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
45 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
46 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
47 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
48 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
49 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces"};
50 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
51 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
52
53 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)"};
54 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"};
55 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
56
57 static texture_t mod_q1bsp_texture_solid;
58 static texture_t mod_q1bsp_texture_sky;
59 static texture_t mod_q1bsp_texture_lava;
60 static texture_t mod_q1bsp_texture_slime;
61 static texture_t mod_q1bsp_texture_water;
62
63 void Mod_BrushInit(void)
64 {
65 //      Cvar_RegisterVariable(&r_subdivide_size);
66         Cvar_RegisterVariable(&mod_bsp_portalize);
67         Cvar_RegisterVariable(&r_novis);
68         Cvar_RegisterVariable(&r_nosurftextures);
69         Cvar_RegisterVariable(&r_subdivisions_tolerance);
70         Cvar_RegisterVariable(&r_subdivisions_mintess);
71         Cvar_RegisterVariable(&r_subdivisions_maxtess);
72         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
73         Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
74         Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
75         Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
76         Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
77         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
78         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
79         Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
80         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
81         Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
82         Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
83         Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
84         Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
85         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
86         Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
87         Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
88         Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
89         Cvar_RegisterVariable(&mod_collision_bih);
90         Cvar_RegisterVariable(&mod_recalculatenodeboxes);
91
92         memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
93         strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
94         mod_q1bsp_texture_solid.surfaceflags = 0;
95         mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
96
97         mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
98         strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
99         mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
100         mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
101
102         mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
103         strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
104         mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
105         mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
106
107         mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
108         strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
109         mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
110         mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
111
112         mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
113         strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
114         mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
115         mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
116 }
117
118 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
119 {
120         mnode_t *node;
121
122         if (model == NULL)
123                 return NULL;
124
125         // LordHavoc: modified to start at first clip node,
126         // in other words: first node of the (sub)model
127         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
128         while (node->plane)
129                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
130
131         return (mleaf_t *)node;
132 }
133
134 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
135 {
136         int i;
137         mleaf_t *leaf;
138         leaf = Mod_Q1BSP_PointInLeaf(model, p);
139         if (leaf)
140         {
141                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
142                 if (i)
143                 {
144                         memcpy(out, leaf->ambient_sound_level, i);
145                         out += i;
146                         outsize -= i;
147                 }
148         }
149         if (outsize)
150                 memset(out, 0, outsize);
151 }
152
153 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
154 {
155         int numclusters = 0;
156         int nodestackindex = 0;
157         mnode_t *node, *nodestack[1024];
158         if (!model->brush.num_pvsclusters)
159                 return -1;
160         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
161         for (;;)
162         {
163 #if 1
164                 if (node->plane)
165                 {
166                         // node - recurse down the BSP tree
167                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
168                         if (sides < 3)
169                         {
170                                 if (sides == 0)
171                                         return -1; // ERROR: NAN bounding box!
172                                 // box is on one side of plane, take that path
173                                 node = node->children[sides-1];
174                         }
175                         else
176                         {
177                                 // box crosses plane, take one path and remember the other
178                                 if (nodestackindex < 1024)
179                                         nodestack[nodestackindex++] = node->children[0];
180                                 node = node->children[1];
181                         }
182                         continue;
183                 }
184                 else
185                 {
186                         // leaf - add clusterindex to list
187                         if (numclusters < maxclusters)
188                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
189                         numclusters++;
190                 }
191 #else
192                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
193                 {
194                         if (node->plane)
195                         {
196                                 if (nodestackindex < 1024)
197                                         nodestack[nodestackindex++] = node->children[0];
198                                 node = node->children[1];
199                                 continue;
200                         }
201                         else
202                         {
203                                 // leaf - add clusterindex to list
204                                 if (numclusters < maxclusters)
205                                         clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
206                                 numclusters++;
207                         }
208                 }
209 #endif
210                 // try another path we didn't take earlier
211                 if (nodestackindex == 0)
212                         break;
213                 node = nodestack[--nodestackindex];
214         }
215         // return number of clusters found (even if more than the maxclusters)
216         return numclusters;
217 }
218
219 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
220 {
221         int nodestackindex = 0;
222         mnode_t *node, *nodestack[1024];
223         if (!model->brush.num_pvsclusters)
224                 return true;
225         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
226         for (;;)
227         {
228 #if 1
229                 if (node->plane)
230                 {
231                         // node - recurse down the BSP tree
232                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
233                         if (sides < 3)
234                         {
235                                 if (sides == 0)
236                                         return -1; // ERROR: NAN bounding box!
237                                 // box is on one side of plane, take that path
238                                 node = node->children[sides-1];
239                         }
240                         else
241                         {
242                                 // box crosses plane, take one path and remember the other
243                                 if (nodestackindex < 1024)
244                                         nodestack[nodestackindex++] = node->children[0];
245                                 node = node->children[1];
246                         }
247                         continue;
248                 }
249                 else
250                 {
251                         // leaf - check cluster bit
252                         int clusterindex = ((mleaf_t *)node)->clusterindex;
253                         if (CHECKPVSBIT(pvs, clusterindex))
254                         {
255                                 // it is visible, return immediately with the news
256                                 return true;
257                         }
258                 }
259 #else
260                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
261                 {
262                         if (node->plane)
263                         {
264                                 if (nodestackindex < 1024)
265                                         nodestack[nodestackindex++] = node->children[0];
266                                 node = node->children[1];
267                                 continue;
268                         }
269                         else
270                         {
271                                 // leaf - check cluster bit
272                                 int clusterindex = ((mleaf_t *)node)->clusterindex;
273                                 if (CHECKPVSBIT(pvs, clusterindex))
274                                 {
275                                         // it is visible, return immediately with the news
276                                         return true;
277                                 }
278                         }
279                 }
280 #endif
281                 // nothing to see here, try another path we didn't take earlier
282                 if (nodestackindex == 0)
283                         break;
284                 node = nodestack[--nodestackindex];
285         }
286         // it is not visible
287         return false;
288 }
289
290 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
291 {
292         int nodestackindex = 0;
293         mnode_t *node, *nodestack[1024];
294         if (!model->brush.num_leafs)
295                 return true;
296         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
297         for (;;)
298         {
299 #if 1
300                 if (node->plane)
301                 {
302                         // node - recurse down the BSP tree
303                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
304                         if (sides < 3)
305                         {
306                                 if (sides == 0)
307                                         return -1; // ERROR: NAN bounding box!
308                                 // box is on one side of plane, take that path
309                                 node = node->children[sides-1];
310                         }
311                         else
312                         {
313                                 // box crosses plane, take one path and remember the other
314                                 if (nodestackindex < 1024)
315                                         nodestack[nodestackindex++] = node->children[0];
316                                 node = node->children[1];
317                         }
318                         continue;
319                 }
320                 else
321                 {
322                         // leaf - check cluster bit
323                         int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
324                         if (CHECKPVSBIT(pvs, clusterindex))
325                         {
326                                 // it is visible, return immediately with the news
327                                 return true;
328                         }
329                 }
330 #else
331                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
332                 {
333                         if (node->plane)
334                         {
335                                 if (nodestackindex < 1024)
336                                         nodestack[nodestackindex++] = node->children[0];
337                                 node = node->children[1];
338                                 continue;
339                         }
340                         else
341                         {
342                                 // leaf - check cluster bit
343                                 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
344                                 if (CHECKPVSBIT(pvs, clusterindex))
345                                 {
346                                         // it is visible, return immediately with the news
347                                         return true;
348                                 }
349                         }
350                 }
351 #endif
352                 // nothing to see here, try another path we didn't take earlier
353                 if (nodestackindex == 0)
354                         break;
355                 node = nodestack[--nodestackindex];
356         }
357         // it is not visible
358         return false;
359 }
360
361 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
362 {
363         int nodestackindex = 0;
364         mnode_t *node, *nodestack[1024];
365         if (!model->brush.num_leafs)
366                 return true;
367         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
368         for (;;)
369         {
370 #if 1
371                 if (node->plane)
372                 {
373                         // node - recurse down the BSP tree
374                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
375                         if (sides < 3)
376                         {
377                                 if (sides == 0)
378                                         return -1; // ERROR: NAN bounding box!
379                                 // box is on one side of plane, take that path
380                                 node = node->children[sides-1];
381                         }
382                         else
383                         {
384                                 // box crosses plane, take one path and remember the other
385                                 if (nodestackindex < 1024)
386                                         nodestack[nodestackindex++] = node->children[0];
387                                 node = node->children[1];
388                         }
389                         continue;
390                 }
391                 else
392                 {
393                         // leaf - check if it is visible
394                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
395                         {
396                                 // it is visible, return immediately with the news
397                                 return true;
398                         }
399                 }
400 #else
401                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
402                 {
403                         if (node->plane)
404                         {
405                                 if (nodestackindex < 1024)
406                                         nodestack[nodestackindex++] = node->children[0];
407                                 node = node->children[1];
408                                 continue;
409                         }
410                         else
411                         {
412                                 // leaf - check if it is visible
413                                 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
414                                 {
415                                         // it is visible, return immediately with the news
416                                         return true;
417                                 }
418                         }
419                 }
420 #endif
421                 // nothing to see here, try another path we didn't take earlier
422                 if (nodestackindex == 0)
423                         break;
424                 node = nodestack[--nodestackindex];
425         }
426         // it is not visible
427         return false;
428 }
429
430 typedef struct findnonsolidlocationinfo_s
431 {
432         vec3_t center;
433         vec3_t absmin, absmax;
434         vec_t radius;
435         vec3_t nudge;
436         vec_t bestdist;
437         dp_model_t *model;
438 }
439 findnonsolidlocationinfo_t;
440
441 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
442 {
443         int i, *tri;
444         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
445
446         tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
447         VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
448         VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
449         VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
450         VectorSubtract(vert[1], vert[0], edge[0]);
451         VectorSubtract(vert[2], vert[1], edge[1]);
452         CrossProduct(edge[1], edge[0], facenormal);
453         if (facenormal[0] || facenormal[1] || facenormal[2])
454         {
455                 VectorNormalize(facenormal);
456                 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
457                 if (f <= info->bestdist && f >= -info->bestdist)
458                 {
459                         VectorSubtract(vert[0], vert[2], edge[2]);
460                         VectorNormalize(edge[0]);
461                         VectorNormalize(edge[1]);
462                         VectorNormalize(edge[2]);
463                         CrossProduct(facenormal, edge[0], edgenormal[0]);
464                         CrossProduct(facenormal, edge[1], edgenormal[1]);
465                         CrossProduct(facenormal, edge[2], edgenormal[2]);
466                         // face distance
467                         if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
468                                         && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
469                                         && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
470                         {
471                                 // we got lucky, the center is within the face
472                                 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
473                                 if (dist < 0)
474                                 {
475                                         dist = -dist;
476                                         if (info->bestdist > dist)
477                                         {
478                                                 info->bestdist = dist;
479                                                 VectorScale(facenormal, (info->radius - -dist), info->nudge);
480                                         }
481                                 }
482                                 else
483                                 {
484                                         if (info->bestdist > dist)
485                                         {
486                                                 info->bestdist = dist;
487                                                 VectorScale(facenormal, (info->radius - dist), info->nudge);
488                                         }
489                                 }
490                         }
491                         else
492                         {
493                                 // check which edge or vertex the center is nearest
494                                 for (i = 0;i < 3;i++)
495                                 {
496                                         f = DotProduct(info->center, edge[i]);
497                                         if (f >= DotProduct(vert[0], edge[i])
498                                                         && f <= DotProduct(vert[1], edge[i]))
499                                         {
500                                                 // on edge
501                                                 VectorMA(info->center, -f, edge[i], point);
502                                                 dist = sqrt(DotProduct(point, point));
503                                                 if (info->bestdist > dist)
504                                                 {
505                                                         info->bestdist = dist;
506                                                         VectorScale(point, (info->radius / dist), info->nudge);
507                                                 }
508                                                 // skip both vertex checks
509                                                 // (both are further away than this edge)
510                                                 i++;
511                                         }
512                                         else
513                                         {
514                                                 // not on edge, check first vertex of edge
515                                                 VectorSubtract(info->center, vert[i], point);
516                                                 dist = sqrt(DotProduct(point, point));
517                                                 if (info->bestdist > dist)
518                                                 {
519                                                         info->bestdist = dist;
520                                                         VectorScale(point, (info->radius / dist), info->nudge);
521                                                 }
522                                         }
523                                 }
524                         }
525                 }
526         }
527 }
528
529 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
530 {
531         int surfacenum, k, *mark;
532         msurface_t *surface;
533         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
534         {
535                 surface = info->model->data_surfaces + *mark;
536                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
537                 {
538                         if(surface->deprecatedq3num_bboxstride > 0)
539                         {
540                                 int i, cnt, tri;
541                                 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
542                                 for(i = 0; i < cnt; ++i)
543                                 {
544                                         if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
545                                         {
546                                                 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
547                                                 {
548                                                         tri = i * surface->deprecatedq3num_bboxstride + k;
549                                                         if(tri >= surface->num_triangles)
550                                                                 break;
551                                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
552                                                 }
553                                         }
554                                 }
555                         }
556                         else
557                         {
558                                 for (k = 0;k < surface->num_triangles;k++)
559                                 {
560                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
561                                 }
562                         }
563                 }
564         }
565 }
566
567 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
568 {
569         if (node->plane)
570         {
571                 float f = PlaneDiff(info->center, node->plane);
572                 if (f >= -info->bestdist)
573                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
574                 if (f <= info->bestdist)
575                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
576         }
577         else
578         {
579                 if (((mleaf_t *)node)->numleafsurfaces)
580                         Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
581         }
582 }
583
584 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
585 {
586         int i;
587         findnonsolidlocationinfo_t info;
588         if (model == NULL)
589         {
590                 VectorCopy(in, out);
591                 return;
592         }
593         VectorCopy(in, info.center);
594         info.radius = radius;
595         info.model = model;
596         i = 0;
597         do
598         {
599                 VectorClear(info.nudge);
600                 info.bestdist = radius;
601                 VectorCopy(info.center, info.absmin);
602                 VectorCopy(info.center, info.absmax);
603                 info.absmin[0] -= info.radius + 1;
604                 info.absmin[1] -= info.radius + 1;
605                 info.absmin[2] -= info.radius + 1;
606                 info.absmax[0] += info.radius + 1;
607                 info.absmax[1] += info.radius + 1;
608                 info.absmax[2] += info.radius + 1;
609                 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
610                 VectorAdd(info.center, info.nudge, info.center);
611         }
612         while (info.bestdist < radius && ++i < 10);
613         VectorCopy(info.center, out);
614 }
615
616 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
617 {
618         switch(nativecontents)
619         {
620                 case CONTENTS_EMPTY:
621                         return 0;
622                 case CONTENTS_SOLID:
623                         return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
624                 case CONTENTS_WATER:
625                         return SUPERCONTENTS_WATER;
626                 case CONTENTS_SLIME:
627                         return SUPERCONTENTS_SLIME;
628                 case CONTENTS_LAVA:
629                         return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
630                 case CONTENTS_SKY:
631                         return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
632         }
633         return 0;
634 }
635
636 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
637 {
638         if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
639                 return CONTENTS_SOLID;
640         if (supercontents & SUPERCONTENTS_SKY)
641                 return CONTENTS_SKY;
642         if (supercontents & SUPERCONTENTS_LAVA)
643                 return CONTENTS_LAVA;
644         if (supercontents & SUPERCONTENTS_SLIME)
645                 return CONTENTS_SLIME;
646         if (supercontents & SUPERCONTENTS_WATER)
647                 return CONTENTS_WATER;
648         return CONTENTS_EMPTY;
649 }
650
651 typedef struct RecursiveHullCheckTraceInfo_s
652 {
653         // the hull we're tracing through
654         const hull_t *hull;
655
656         // the trace structure to fill in
657         trace_t *trace;
658
659         // start, end, and end - start (in model space)
660         double start[3];
661         double end[3];
662         double dist[3];
663 }
664 RecursiveHullCheckTraceInfo_t;
665
666 // 1/32 epsilon to keep floating point happy
667 #define DIST_EPSILON (0.03125)
668
669 #define HULLCHECKSTATE_EMPTY 0
670 #define HULLCHECKSTATE_SOLID 1
671 #define HULLCHECKSTATE_DONE 2
672
673 extern cvar_t collision_prefernudgedfraction;
674 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
675 {
676         // status variables, these don't need to be saved on the stack when
677         // recursing...  but are because this should be thread-safe
678         // (note: tracing against a bbox is not thread-safe, yet)
679         int ret;
680         mplane_t *plane;
681         double t1, t2;
682
683         // variables that need to be stored on the stack when recursing
684         mclipnode_t *node;
685         int side;
686         double midf, mid[3];
687
688         // LordHavoc: a goto!  everyone flee in terror... :)
689 loc0:
690         // check for empty
691         if (num < 0)
692         {
693                 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
694                 if (!t->trace->startfound)
695                 {
696                         t->trace->startfound = true;
697                         t->trace->startsupercontents |= num;
698                 }
699                 if (num & SUPERCONTENTS_LIQUIDSMASK)
700                         t->trace->inwater = true;
701                 if (num == 0)
702                         t->trace->inopen = true;
703                 if (num & SUPERCONTENTS_SOLID)
704                         t->trace->hittexture = &mod_q1bsp_texture_solid;
705                 else if (num & SUPERCONTENTS_SKY)
706                         t->trace->hittexture = &mod_q1bsp_texture_sky;
707                 else if (num & SUPERCONTENTS_LAVA)
708                         t->trace->hittexture = &mod_q1bsp_texture_lava;
709                 else if (num & SUPERCONTENTS_SLIME)
710                         t->trace->hittexture = &mod_q1bsp_texture_slime;
711                 else
712                         t->trace->hittexture = &mod_q1bsp_texture_water;
713                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
714                 t->trace->hitsupercontents = num;
715                 if (num & t->trace->hitsupercontentsmask)
716                 {
717                         // if the first leaf is solid, set startsolid
718                         if (t->trace->allsolid)
719                                 t->trace->startsolid = true;
720 #if COLLISIONPARANOID >= 3
721                         Con_Print("S");
722 #endif
723                         return HULLCHECKSTATE_SOLID;
724                 }
725                 else
726                 {
727                         t->trace->allsolid = false;
728 #if COLLISIONPARANOID >= 3
729                         Con_Print("E");
730 #endif
731                         return HULLCHECKSTATE_EMPTY;
732                 }
733         }
734
735         // find the point distances
736         node = t->hull->clipnodes + num;
737
738         plane = t->hull->planes + node->planenum;
739         if (plane->type < 3)
740         {
741                 t1 = p1[plane->type] - plane->dist;
742                 t2 = p2[plane->type] - plane->dist;
743         }
744         else
745         {
746                 t1 = DotProduct (plane->normal, p1) - plane->dist;
747                 t2 = DotProduct (plane->normal, p2) - plane->dist;
748         }
749
750         if (t1 < 0)
751         {
752                 if (t2 < 0)
753                 {
754 #if COLLISIONPARANOID >= 3
755                         Con_Print("<");
756 #endif
757                         num = node->children[1];
758                         goto loc0;
759                 }
760                 side = 1;
761         }
762         else
763         {
764                 if (t2 >= 0)
765                 {
766 #if COLLISIONPARANOID >= 3
767                         Con_Print(">");
768 #endif
769                         num = node->children[0];
770                         goto loc0;
771                 }
772                 side = 0;
773         }
774
775         // the line intersects, find intersection point
776         // LordHavoc: this uses the original trace for maximum accuracy
777 #if COLLISIONPARANOID >= 3
778         Con_Print("M");
779 #endif
780         if (plane->type < 3)
781         {
782                 t1 = t->start[plane->type] - plane->dist;
783                 t2 = t->end[plane->type] - plane->dist;
784         }
785         else
786         {
787                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
788                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
789         }
790
791         midf = t1 / (t1 - t2);
792         midf = bound(p1f, midf, p2f);
793         VectorMA(t->start, midf, t->dist, mid);
794
795         // recurse both sides, front side first
796         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
797         // if this side is not empty, return what it is (solid or done)
798         if (ret != HULLCHECKSTATE_EMPTY)
799                 return ret;
800
801         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
802         // if other side is not solid, return what it is (empty or done)
803         if (ret != HULLCHECKSTATE_SOLID)
804                 return ret;
805
806         // front is air and back is solid, this is the impact point...
807         if (side)
808         {
809                 t->trace->plane.dist = -plane->dist;
810                 VectorNegate (plane->normal, t->trace->plane.normal);
811         }
812         else
813         {
814                 t->trace->plane.dist = plane->dist;
815                 VectorCopy (plane->normal, t->trace->plane.normal);
816         }
817
818         // calculate the true fraction
819         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
820         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
821         midf = t1 / (t1 - t2);
822         t->trace->realfraction = bound(0, midf, 1);
823
824         // calculate the return fraction which is nudged off the surface a bit
825         midf = (t1 - DIST_EPSILON) / (t1 - t2);
826         t->trace->fraction = bound(0, midf, 1);
827
828         if (collision_prefernudgedfraction.integer)
829                 t->trace->realfraction = t->trace->fraction;
830
831 #if COLLISIONPARANOID >= 3
832         Con_Print("D");
833 #endif
834         return HULLCHECKSTATE_DONE;
835 }
836
837 //#if COLLISIONPARANOID < 2
838 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
839 {
840         mplane_t *plane;
841         mclipnode_t *nodes = t->hull->clipnodes;
842         mplane_t *planes = t->hull->planes;
843         vec3_t point;
844         VectorCopy(t->start, point);
845         while (num >= 0)
846         {
847                 plane = planes + nodes[num].planenum;
848                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
849         }
850         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
851         t->trace->startsupercontents |= num;
852         if (num & SUPERCONTENTS_LIQUIDSMASK)
853                 t->trace->inwater = true;
854         if (num == 0)
855                 t->trace->inopen = true;
856         if (num & t->trace->hitsupercontentsmask)
857         {
858                 t->trace->allsolid = t->trace->startsolid = true;
859                 return HULLCHECKSTATE_SOLID;
860         }
861         else
862         {
863                 t->trace->allsolid = t->trace->startsolid = false;
864                 return HULLCHECKSTATE_EMPTY;
865         }
866 }
867 //#endif
868
869 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)
870 {
871         RecursiveHullCheckTraceInfo_t rhc;
872
873         memset(&rhc, 0, sizeof(rhc));
874         memset(trace, 0, sizeof(trace_t));
875         rhc.trace = trace;
876         rhc.trace->fraction = 1;
877         rhc.trace->realfraction = 1;
878         rhc.trace->allsolid = true;
879         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
880         VectorCopy(start, rhc.start);
881         VectorCopy(start, rhc.end);
882         Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
883 }
884
885 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)
886 {
887         RecursiveHullCheckTraceInfo_t rhc;
888
889         if (VectorCompare(start, end))
890         {
891                 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
892                 return;
893         }
894
895         memset(&rhc, 0, sizeof(rhc));
896         memset(trace, 0, sizeof(trace_t));
897         rhc.trace = trace;
898         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
899         rhc.trace->fraction = 1;
900         rhc.trace->realfraction = 1;
901         rhc.trace->allsolid = true;
902         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
903         VectorCopy(start, rhc.start);
904         VectorCopy(end, rhc.end);
905         VectorSubtract(rhc.end, rhc.start, rhc.dist);
906 #if COLLISIONPARANOID >= 2
907         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]);
908         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
909         {
910
911                 double test[3];
912                 trace_t testtrace;
913                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
914                 memset(&testtrace, 0, sizeof(trace_t));
915                 rhc.trace = &testtrace;
916                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
917                 rhc.trace->fraction = 1;
918                 rhc.trace->realfraction = 1;
919                 rhc.trace->allsolid = true;
920                 VectorCopy(test, rhc.start);
921                 VectorCopy(test, rhc.end);
922                 VectorClear(rhc.dist);
923                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
924                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
925                 if (!trace->startsolid && testtrace.startsolid)
926                         Con_Printf(" - ended in solid!\n");
927         }
928         Con_Print("\n");
929 #else
930         if (VectorLength2(rhc.dist))
931                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
932         else
933                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
934 #endif
935 }
936
937 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)
938 {
939         // this function currently only supports same size start and end
940         double boxsize[3];
941         RecursiveHullCheckTraceInfo_t rhc;
942
943         if (VectorCompare(boxmins, boxmaxs))
944         {
945                 if (VectorCompare(start, end))
946                         Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
947                 else
948                         Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
949                 return;
950         }
951
952         memset(&rhc, 0, sizeof(rhc));
953         memset(trace, 0, sizeof(trace_t));
954         rhc.trace = trace;
955         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
956         rhc.trace->fraction = 1;
957         rhc.trace->realfraction = 1;
958         rhc.trace->allsolid = true;
959         VectorSubtract(boxmaxs, boxmins, boxsize);
960         if (boxsize[0] < 3)
961                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
962         else if (model->brush.ishlbsp)
963         {
964                 // LordHavoc: this has to have a minor tolerance (the .1) because of
965                 // minor float precision errors from the box being transformed around
966                 if (boxsize[0] < 32.1)
967                 {
968                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
969                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
970                         else
971                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
972                 }
973                 else
974                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
975         }
976         else
977         {
978                 // LordHavoc: this has to have a minor tolerance (the .1) because of
979                 // minor float precision errors from the box being transformed around
980                 if (boxsize[0] < 32.1)
981                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
982                 else
983                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
984         }
985         VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
986         VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
987         VectorSubtract(rhc.end, rhc.start, rhc.dist);
988 #if COLLISIONPARANOID >= 2
989         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]);
990         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
991         {
992
993                 double test[3];
994                 trace_t testtrace;
995                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
996                 memset(&testtrace, 0, sizeof(trace_t));
997                 rhc.trace = &testtrace;
998                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
999                 rhc.trace->fraction = 1;
1000                 rhc.trace->realfraction = 1;
1001                 rhc.trace->allsolid = true;
1002                 VectorCopy(test, rhc.start);
1003                 VectorCopy(test, rhc.end);
1004                 VectorClear(rhc.dist);
1005                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1006                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1007                 if (!trace->startsolid && testtrace.startsolid)
1008                         Con_Printf(" - ended in solid!\n");
1009         }
1010         Con_Print("\n");
1011 #else
1012         if (VectorLength2(rhc.dist))
1013                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1014         else
1015                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1016 #endif
1017 }
1018
1019 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1020 {
1021         int num = model->brushq1.hulls[0].firstclipnode;
1022         mplane_t *plane;
1023         mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1024         mplane_t *planes = model->brushq1.hulls[0].planes;
1025         while (num >= 0)
1026         {
1027                 plane = planes + nodes[num].planenum;
1028                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1029         }
1030         return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1031 }
1032
1033 void Collision_ClipTrace_Box(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1034 {
1035 #if 1
1036         colbrushf_t cbox;
1037         colplanef_t cbox_planes[6];
1038         cbox.isaabb = true;
1039         cbox.hasaabbplanes = true;
1040         cbox.supercontents = boxsupercontents;
1041         cbox.numplanes = 6;
1042         cbox.numpoints = 0;
1043         cbox.numtriangles = 0;
1044         cbox.planes = cbox_planes;
1045         cbox.points = NULL;
1046         cbox.elements = NULL;
1047         cbox.markframe = 0;
1048         cbox.mins[0] = 0;
1049         cbox.mins[1] = 0;
1050         cbox.mins[2] = 0;
1051         cbox.maxs[0] = 0;
1052         cbox.maxs[1] = 0;
1053         cbox.maxs[2] = 0;
1054         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];
1055         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];
1056         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];
1057         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];
1058         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];
1059         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];
1060         cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1061         cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1062         cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1063         cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1064         cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1065         cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1066         memset(trace, 0, sizeof(trace_t));
1067         trace->hitsupercontentsmask = hitsupercontentsmask;
1068         trace->fraction = 1;
1069         trace->realfraction = 1;
1070         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1071 #else
1072         RecursiveHullCheckTraceInfo_t rhc;
1073         static hull_t box_hull;
1074         static mclipnode_t box_clipnodes[6];
1075         static mplane_t box_planes[6];
1076         // fill in a default trace
1077         memset(&rhc, 0, sizeof(rhc));
1078         memset(trace, 0, sizeof(trace_t));
1079         //To keep everything totally uniform, bounding boxes are turned into small
1080         //BSP trees instead of being compared directly.
1081         // create a temp hull from bounding box sizes
1082         box_planes[0].dist = cmaxs[0] - mins[0];
1083         box_planes[1].dist = cmins[0] - maxs[0];
1084         box_planes[2].dist = cmaxs[1] - mins[1];
1085         box_planes[3].dist = cmins[1] - maxs[1];
1086         box_planes[4].dist = cmaxs[2] - mins[2];
1087         box_planes[5].dist = cmins[2] - maxs[2];
1088 #if COLLISIONPARANOID >= 3
1089         Con_Printf("box_planes %f:%f %f:%f %f:%f\ncbox %f %f %f:%f %f %f\nbox %f %f %f:%f %f %f\n", box_planes[0].dist, box_planes[1].dist, box_planes[2].dist, box_planes[3].dist, box_planes[4].dist, box_planes[5].dist, cmins[0], cmins[1], cmins[2], cmaxs[0], cmaxs[1], cmaxs[2], mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
1090 #endif
1091
1092         if (box_hull.clipnodes == NULL)
1093         {
1094                 int i, side;
1095
1096                 //Set up the planes and clipnodes so that the six floats of a bounding box
1097                 //can just be stored out and get a proper hull_t structure.
1098
1099                 box_hull.clipnodes = box_clipnodes;
1100                 box_hull.planes = box_planes;
1101                 box_hull.firstclipnode = 0;
1102                 box_hull.lastclipnode = 5;
1103
1104                 for (i = 0;i < 6;i++)
1105                 {
1106                         box_clipnodes[i].planenum = i;
1107
1108                         side = i&1;
1109
1110                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1111                         if (i != 5)
1112                                 box_clipnodes[i].children[side^1] = i + 1;
1113                         else
1114                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1115
1116                         box_planes[i].type = i>>1;
1117                         box_planes[i].normal[i>>1] = 1;
1118                 }
1119         }
1120
1121         // trace a line through the generated clipping hull
1122         //rhc.boxsupercontents = boxsupercontents;
1123         rhc.hull = &box_hull;
1124         rhc.trace = trace;
1125         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1126         rhc.trace->fraction = 1;
1127         rhc.trace->realfraction = 1;
1128         rhc.trace->allsolid = true;
1129         VectorCopy(start, rhc.start);
1130         VectorCopy(end, rhc.end);
1131         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1132         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1133         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1134         if (rhc.trace->startsupercontents)
1135                 rhc.trace->startsupercontents = boxsupercontents;
1136 #endif
1137 }
1138
1139 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1140 {
1141         memset(trace, 0, sizeof(trace_t));
1142         trace->fraction = 1;
1143         trace->realfraction = 1;
1144         if (BoxesOverlap(start, start, cmins, cmaxs))
1145         {
1146                 trace->startsupercontents |= boxsupercontents;
1147                 if (hitsupercontentsmask & boxsupercontents)
1148                 {
1149                         trace->startsolid = true;
1150                         trace->allsolid = true;
1151                 }
1152         }
1153 }
1154
1155 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1156 {
1157         trace_t trace;
1158         model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1159         return trace.fraction == 1;
1160 }
1161
1162 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)
1163 {
1164         int side;
1165         float front, back;
1166         float mid, distz = endz - startz;
1167
1168 loc0:
1169         if (!node->plane)
1170                 return false;           // didn't hit anything
1171
1172         switch (node->plane->type)
1173         {
1174         case PLANE_X:
1175                 node = node->children[x < node->plane->dist];
1176                 goto loc0;
1177         case PLANE_Y:
1178                 node = node->children[y < node->plane->dist];
1179                 goto loc0;
1180         case PLANE_Z:
1181                 side = startz < node->plane->dist;
1182                 if ((endz < node->plane->dist) == side)
1183                 {
1184                         node = node->children[side];
1185                         goto loc0;
1186                 }
1187                 // found an intersection
1188                 mid = node->plane->dist;
1189                 break;
1190         default:
1191                 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1192                 front += startz * node->plane->normal[2];
1193                 back += endz * node->plane->normal[2];
1194                 side = front < node->plane->dist;
1195                 if ((back < node->plane->dist) == side)
1196                 {
1197                         node = node->children[side];
1198                         goto loc0;
1199                 }
1200                 // found an intersection
1201                 mid = startz + distz * (front - node->plane->dist) / (front - back);
1202                 break;
1203         }
1204
1205         // go down front side
1206         if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1207                 return true;    // hit something
1208         else
1209         {
1210                 // check for impact on this node
1211                 if (node->numsurfaces)
1212                 {
1213                         int i, dsi, dti, lmwidth, lmheight;
1214                         float ds, dt;
1215                         msurface_t *surface;
1216                         unsigned char *lightmap;
1217                         int maps, line3, size3;
1218                         float dsfrac;
1219                         float dtfrac;
1220                         float scale, w, w00, w01, w10, w11;
1221
1222                         surface = model->data_surfaces + node->firstsurface;
1223                         for (i = 0;i < node->numsurfaces;i++, surface++)
1224                         {
1225                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1226                                         continue;       // no lightmaps
1227
1228                                 // location we want to sample in the lightmap
1229                                 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;
1230                                 dt = ((x * surface->lightmapinfo->texinfo->vecs[1][0] + y * surface->lightmapinfo->texinfo->vecs[1][1] + mid * surface->lightmapinfo->texinfo->vecs[1][2] + surface->lightmapinfo->texinfo->vecs[1][3]) - surface->lightmapinfo->texturemins[1]) * 0.0625f;
1231
1232                                 // check the bounds
1233                                 dsi = (int)ds;
1234                                 dti = (int)dt;
1235                                 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1236                                 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1237
1238                                 // is it in bounds?
1239                                 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1240                                 {
1241                                         // calculate bilinear interpolation factors
1242                                         // and also multiply by fixedpoint conversion factors
1243                                         dsfrac = ds - dsi;
1244                                         dtfrac = dt - dti;
1245                                         w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1246                                         w01 = (    dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1247                                         w10 = (1 - dsfrac) * (    dtfrac) * (1.0f / 32768.0f);
1248                                         w11 = (    dsfrac) * (    dtfrac) * (1.0f / 32768.0f);
1249
1250                                         // values for pointer math
1251                                         line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1252                                         size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1253
1254                                         // look up the pixel
1255                                         lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1256
1257                                         // bilinear filter each lightmap style, and sum them
1258                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1259                                         {
1260                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1261                                                 w = w00 * scale;VectorMA(ambientcolor, w, lightmap            , ambientcolor);
1262                                                 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3        , ambientcolor);
1263                                                 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3    , ambientcolor);
1264                                                 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1265                                                 lightmap += size3;
1266                                         }
1267
1268                                         return true; // success
1269                                 }
1270                         }
1271                 }
1272
1273                 // go down back side
1274                 node = node->children[side ^ 1];
1275                 startz = mid;
1276                 distz = endz - startz;
1277                 goto loc0;
1278         }
1279 }
1280
1281 void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1282 {
1283         // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1284         VectorSet(diffusenormal, 0, 0, 1);
1285
1286         if (!model->brushq1.lightdata)
1287         {
1288                 VectorSet(ambientcolor, 1, 1, 1);
1289                 VectorSet(diffusecolor, 0, 0, 0);
1290                 return;
1291         }
1292
1293         Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2] + 0.125, p[2] - 65536);
1294 }
1295
1296 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1297 {
1298         int i;
1299         int j;
1300         int k;
1301         const msurface_t *surface;
1302         float normal[3];
1303         float v0[3];
1304         float v1[3];
1305         float edgedir[3];
1306         float edgenormal[3];
1307         float p[4];
1308         float midf;
1309         float t1;
1310         float t2;
1311         VectorCopy(mid, p);
1312         p[3] = 1;
1313         surface = model->data_surfaces + node->firstsurface;
1314         for (i = 0;i < node->numsurfaces;i++, surface++)
1315         {
1316                 // skip surfaces whose bounding box does not include the point
1317 //              if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1318 //                      continue;
1319                 // skip faces with contents we don't care about
1320                 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1321                         continue;
1322                 // get the surface normal - since it is flat we know any vertex normal will suffice
1323                 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1324                 // skip backfaces
1325                 if (DotProduct(t->dist, normal) > 0)
1326                         continue;
1327                 // iterate edges and see if the point is outside one of them
1328                 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1329                 {
1330                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1331                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1332                         VectorSubtract(v0, v1, edgedir);
1333                         CrossProduct(edgedir, normal, edgenormal);
1334                         if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1335                                 break;
1336                 }
1337                 // if the point is outside one of the edges, it is not within the surface
1338                 if (j < surface->num_vertices)
1339                         continue;
1340
1341                 // we hit a surface, this is the impact point...
1342                 VectorCopy(normal, t->trace->plane.normal);
1343                 t->trace->plane.dist = DotProduct(normal, p);
1344
1345                 // calculate the true fraction
1346                 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1347                 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1348                 midf = t1 / (t1 - t2);
1349                 t->trace->realfraction = midf;
1350
1351                 // calculate the return fraction which is nudged off the surface a bit
1352                 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1353                 t->trace->fraction = bound(0, midf, 1);
1354
1355                 if (collision_prefernudgedfraction.integer)
1356                         t->trace->realfraction = t->trace->fraction;
1357
1358                 t->trace->hittexture = surface->texture->currentframe;
1359                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1360                 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1361                 return surface->texture->currentframe;
1362         }
1363         return NULL;
1364 }
1365
1366 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])
1367 {
1368         const mplane_t *plane;
1369         double t1, t2;
1370         int side;
1371         double midf, mid[3];
1372         const mleaf_t *leaf;
1373
1374         while (node->plane)
1375         {
1376                 plane = node->plane;
1377                 if (plane->type < 3)
1378                 {
1379                         t1 = p1[plane->type] - plane->dist;
1380                         t2 = p2[plane->type] - plane->dist;
1381                 }
1382                 else
1383                 {
1384                         t1 = DotProduct (plane->normal, p1) - plane->dist;
1385                         t2 = DotProduct (plane->normal, p2) - plane->dist;
1386                 }
1387                 if (t1 < 0)
1388                 {
1389                         if (t2 < 0)
1390                         {
1391                                 node = node->children[1];
1392                                 continue;
1393                         }
1394                         side = 1;
1395                 }
1396                 else
1397                 {
1398                         if (t2 >= 0)
1399                         {
1400                                 node = node->children[0];
1401                                 continue;
1402                         }
1403                         side = 0;
1404                 }
1405
1406                 // the line intersects, find intersection point
1407                 // LordHavoc: this uses the original trace for maximum accuracy
1408                 if (plane->type < 3)
1409                 {
1410                         t1 = t->start[plane->type] - plane->dist;
1411                         t2 = t->end[plane->type] - plane->dist;
1412                 }
1413                 else
1414                 {
1415                         t1 = DotProduct (plane->normal, t->start) - plane->dist;
1416                         t2 = DotProduct (plane->normal, t->end) - plane->dist;
1417                 }
1418         
1419                 midf = t1 / (t1 - t2);
1420                 VectorMA(t->start, midf, t->dist, mid);
1421
1422                 // recurse both sides, front side first, return if we hit a surface
1423                 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1424                         return HULLCHECKSTATE_DONE;
1425
1426                 // test each surface on the node
1427                 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1428                 if (t->trace->hittexture)
1429                         return HULLCHECKSTATE_DONE;
1430
1431                 // recurse back side
1432                 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1433         }
1434         leaf = (const mleaf_t *)node;
1435         side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1436         if (!t->trace->startfound)
1437         {
1438                 t->trace->startfound = true;
1439                 t->trace->startsupercontents |= side;
1440         }
1441         if (side & SUPERCONTENTS_LIQUIDSMASK)
1442                 t->trace->inwater = true;
1443         if (side == 0)
1444                 t->trace->inopen = true;
1445         if (side & t->trace->hitsupercontentsmask)
1446         {
1447                 // if the first leaf is solid, set startsolid
1448                 if (t->trace->allsolid)
1449                         t->trace->startsolid = true;
1450                 return HULLCHECKSTATE_SOLID;
1451         }
1452         else
1453         {
1454                 t->trace->allsolid = false;
1455                 return HULLCHECKSTATE_EMPTY;
1456         }
1457 }
1458
1459 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)
1460 {
1461         RecursiveHullCheckTraceInfo_t rhc;
1462
1463         memset(&rhc, 0, sizeof(rhc));
1464         memset(trace, 0, sizeof(trace_t));
1465         rhc.trace = trace;
1466         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1467         rhc.trace->fraction = 1;
1468         rhc.trace->realfraction = 1;
1469         rhc.trace->allsolid = true;
1470         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1471         VectorCopy(start, rhc.start);
1472         VectorCopy(end, rhc.end);
1473         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1474         Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1475         VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1476 }
1477
1478 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1479 {
1480         int c;
1481         unsigned char *outstart = out;
1482         while (out < outend)
1483         {
1484                 if (in == inend)
1485                 {
1486                         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));
1487                         return;
1488                 }
1489                 c = *in++;
1490                 if (c)
1491                         *out++ = c;
1492                 else
1493                 {
1494                         if (in == inend)
1495                         {
1496                                 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));
1497                                 return;
1498                         }
1499                         for (c = *in++;c > 0;c--)
1500                         {
1501                                 if (out == outend)
1502                                 {
1503                                         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));
1504                                         return;
1505                                 }
1506                                 *out++ = 0;
1507                         }
1508                 }
1509         }
1510 }
1511
1512 /*
1513 =============
1514 R_Q1BSP_LoadSplitSky
1515
1516 A sky texture is 256*128, with the right side being a masked overlay
1517 ==============
1518 */
1519 void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1520 {
1521         int x, y;
1522         int w = width/2;
1523         int h = height;
1524         unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1525         unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1526
1527         // allocate a texture pool if we need it
1528         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1529                 loadmodel->texturepool = R_AllocTexturePool();
1530
1531         if (bytesperpixel == 4)
1532         {
1533                 for (y = 0;y < h;y++)
1534                 {
1535                         for (x = 0;x < w;x++)
1536                         {
1537                                 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1538                                 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1539                         }
1540                 }
1541         }
1542         else
1543         {
1544                 // make an average value for the back to avoid
1545                 // a fringe on the top level
1546                 int p, r, g, b;
1547                 union
1548                 {
1549                         unsigned int i;
1550                         unsigned char b[4];
1551                 }
1552                 bgra;
1553                 r = g = b = 0;
1554                 for (y = 0;y < h;y++)
1555                 {
1556                         for (x = 0;x < w;x++)
1557                         {
1558                                 p = src[x*width+y+w];
1559                                 r += palette_rgb[p][0];
1560                                 g += palette_rgb[p][1];
1561                                 b += palette_rgb[p][2];
1562                         }
1563                 }
1564                 bgra.b[2] = r/(w*h);
1565                 bgra.b[1] = g/(w*h);
1566                 bgra.b[0] = b/(w*h);
1567                 bgra.b[3] = 0;
1568                 for (y = 0;y < h;y++)
1569                 {
1570                         for (x = 0;x < w;x++)
1571                         {
1572                                 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1573                                 p = src[y*width+x];
1574                                 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1575                         }
1576                 }
1577         }
1578
1579         loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0         , (unsigned char *) solidpixels, w, h);
1580         loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h);
1581         Mem_Free(solidpixels);
1582         Mem_Free(alphapixels);
1583 }
1584
1585 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1586 {
1587         int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1588         skinframe_t *skinframe;
1589         miptex_t *dmiptex;
1590         texture_t *tx, *tx2, *anims[10], *altanims[10];
1591         dmiptexlump_t *m;
1592         unsigned char *data, *mtdata;
1593         const char *s;
1594         char mapname[MAX_QPATH], name[MAX_QPATH];
1595         unsigned char zero[4];
1596
1597         memset(zero, 0, sizeof(zero));
1598
1599         loadmodel->data_textures = NULL;
1600
1601         // add two slots for notexture walls and notexture liquids
1602         if (l->filelen)
1603         {
1604                 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1605                 m->nummiptex = LittleLong (m->nummiptex);
1606                 loadmodel->num_textures = m->nummiptex + 2;
1607                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1608         }
1609         else
1610         {
1611                 m = NULL;
1612                 loadmodel->num_textures = 2;
1613                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1614         }
1615
1616         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1617
1618         // fill out all slots with notexture
1619         if (cls.state != ca_dedicated)
1620                 skinframe = R_SkinFrame_LoadMissing();
1621         else
1622                 skinframe = NULL;
1623         for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1624         {
1625                 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1626                 tx->width = 16;
1627                 tx->height = 16;
1628                 if (cls.state != ca_dedicated)
1629                 {
1630                         tx->numskinframes = 1;
1631                         tx->skinframerate = 1;
1632                         tx->skinframes[0] = skinframe;
1633                         tx->currentskinframe = tx->skinframes[0];
1634                 }
1635                 tx->basematerialflags = MATERIALFLAG_WALL;
1636                 if (i == loadmodel->num_textures - 1)
1637                 {
1638                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1639                         tx->supercontents = mod_q1bsp_texture_water.supercontents;
1640                         tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1641                 }
1642                 else
1643                 {
1644                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1645                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1646                 }
1647                 tx->currentframe = tx;
1648
1649                 // clear water settings
1650                 tx->reflectmin = 0;
1651                 tx->reflectmax = 1;
1652                 tx->refractfactor = 1;
1653                 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1654                 tx->reflectfactor = 1;
1655                 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1656                 tx->r_water_wateralpha = 1;
1657                 tx->offsetmapping = OFFSETMAPPING_OFF;
1658                 tx->offsetscale = 1;
1659                 tx->specularscalemod = 1;
1660                 tx->specularpowermod = 1;
1661         }
1662
1663         if (!m)
1664         {
1665                 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1666                 return;
1667         }
1668
1669         s = loadmodel->name;
1670         if (!strncasecmp(s, "maps/", 5))
1671                 s += 5;
1672         FS_StripExtension(s, mapname, sizeof(mapname));
1673
1674         // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1675         dofs = m->dataofs;
1676         // LordHavoc: mostly rewritten map texture loader
1677         for (i = 0;i < m->nummiptex;i++)
1678         {
1679                 dofs[i] = LittleLong(dofs[i]);
1680                 if (r_nosurftextures.integer)
1681                         continue;
1682                 if (dofs[i] == -1)
1683                 {
1684                         Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1685                         continue;
1686                 }
1687                 dmiptex = (miptex_t *)((unsigned char *)m + dofs[i]);
1688
1689                 // copy name, but only up to 16 characters
1690                 // (the output buffer can hold more than this, but the input buffer is
1691                 //  only 16)
1692                 for (j = 0;j < 16 && dmiptex->name[j];j++)
1693                         name[j] = dmiptex->name[j];
1694                 name[j] = 0;
1695
1696                 if (!name[0])
1697                 {
1698                         dpsnprintf(name, sizeof(name), "unnamed%i", i);
1699                         Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1700                 }
1701
1702                 mtwidth = LittleLong(dmiptex->width);
1703                 mtheight = LittleLong(dmiptex->height);
1704                 mtdata = NULL;
1705                 j = LittleLong(dmiptex->offsets[0]);
1706                 if (j)
1707                 {
1708                         // texture included
1709                         if (j < 40 || j + mtwidth * mtheight > l->filelen)
1710                         {
1711                                 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, dmiptex->name);
1712                                 continue;
1713                         }
1714                         mtdata = (unsigned char *)dmiptex + j;
1715                 }
1716
1717                 if ((mtwidth & 15) || (mtheight & 15))
1718                         Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, dmiptex->name);
1719
1720                 // LordHavoc: force all names to lowercase
1721                 for (j = 0;name[j];j++)
1722                         if (name[j] >= 'A' && name[j] <= 'Z')
1723                                 name[j] += 'a' - 'A';
1724
1725                 if (dmiptex->name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1726                         continue;
1727
1728                 tx = loadmodel->data_textures + i;
1729                 strlcpy(tx->name, name, sizeof(tx->name));
1730                 tx->width = mtwidth;
1731                 tx->height = mtheight;
1732
1733                 if (tx->name[0] == '*')
1734                 {
1735                         if (!strncmp(tx->name, "*lava", 5))
1736                         {
1737                                 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1738                                 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1739                         }
1740                         else if (!strncmp(tx->name, "*slime", 6))
1741                         {
1742                                 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1743                                 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1744                         }
1745                         else
1746                         {
1747                                 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1748                                 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1749                         }
1750                 }
1751                 else if (!strncmp(tx->name, "sky", 3))
1752                 {
1753                         tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1754                         tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1755                 }
1756                 else
1757                 {
1758                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1759                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1760                 }
1761
1762                 if (cls.state != ca_dedicated)
1763                 {
1764                         // LordHavoc: HL sky textures are entirely different than quake
1765                         if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1766                         {
1767                                 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), false, false, r_texture_convertsRGB_skin.integer != 0, NULL);
1768                                 if (!data)
1769                                         data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), false, false, r_texture_convertsRGB_skin.integer != 0, NULL);
1770                                 if (data && image_width == image_height * 2)
1771                                 {
1772                                         R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1773                                         Mem_Free(data);
1774                                 }
1775                                 else if (mtdata != NULL)
1776                                         R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1777                         }
1778                         else
1779                         {
1780                                 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1781                                 if (!skinframe)
1782                                         skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va("textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1783                                 if (!skinframe)
1784                                 {
1785                                         // did not find external texture, load it from the bsp or wad3
1786                                         if (loadmodel->brush.ishlbsp)
1787                                         {
1788                                                 // internal texture overrides wad
1789                                                 unsigned char *pixels, *freepixels;
1790                                                 pixels = freepixels = NULL;
1791                                                 if (mtdata)
1792                                                         pixels = W_ConvertWAD3TextureBGRA(dmiptex);
1793                                                 if (pixels == NULL)
1794                                                         pixels = freepixels = W_GetTextureBGRA(tx->name);
1795                                                 if (pixels != NULL)
1796                                                 {
1797                                                         tx->width = image_width;
1798                                                         tx->height = image_height;
1799                                                         skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height);
1800                                                 }
1801                                                 if (freepixels)
1802                                                         Mem_Free(freepixels);
1803                                         }
1804                                         else if (mtdata) // texture included
1805                                                 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1806                                 }
1807                                 // if skinframe is still NULL the "missing" texture will be used
1808                                 if (skinframe)
1809                                         tx->skinframes[0] = skinframe;
1810                         }
1811
1812                         tx->basematerialflags = MATERIALFLAG_WALL;
1813                         if (tx->name[0] == '*')
1814                         {
1815                                 // LordHavoc: some turbulent textures should not be affected by wateralpha
1816                                 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1817                                 {
1818                                         // replace the texture with transparent black
1819                                         Vector4Set(zero, 128, 128, 128, 128);
1820                                         tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zero, 1, 1);
1821                                         tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1822                                 }
1823                                 else if (!strncmp(tx->name,"*lava",5)
1824                                  || !strncmp(tx->name,"*teleport",9)
1825                                  || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1826                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1827                                 else
1828                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1829                                 if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1830                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1831                         }
1832                         else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1833                         {
1834                                 // replace the texture with black
1835                                 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zero, 1, 1);
1836                                 tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1837                         }
1838                         else if (!strncmp(tx->name, "sky", 3))
1839                                 tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1840                         else if (!strcmp(tx->name, "caulk"))
1841                                 tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1842                         else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1843                                 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1844
1845                         // start out with no animation
1846                         tx->currentframe = tx;
1847                         tx->currentskinframe = tx->skinframes[0];
1848                 }
1849         }
1850
1851         // sequence the animations
1852         for (i = 0;i < m->nummiptex;i++)
1853         {
1854                 tx = loadmodel->data_textures + i;
1855                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1856                         continue;
1857                 if (tx->anim_total[0] || tx->anim_total[1])
1858                         continue;       // already sequenced
1859
1860                 // find the number of frames in the animation
1861                 memset(anims, 0, sizeof(anims));
1862                 memset(altanims, 0, sizeof(altanims));
1863
1864                 for (j = i;j < m->nummiptex;j++)
1865                 {
1866                         tx2 = loadmodel->data_textures + j;
1867                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1868                                 continue;
1869
1870                         num = tx2->name[1];
1871                         if (num >= '0' && num <= '9')
1872                                 anims[num - '0'] = tx2;
1873                         else if (num >= 'a' && num <= 'j')
1874                                 altanims[num - 'a'] = tx2;
1875                         else
1876                                 Con_Printf("Bad animating texture %s\n", tx->name);
1877                 }
1878
1879                 max = altmax = 0;
1880                 for (j = 0;j < 10;j++)
1881                 {
1882                         if (anims[j])
1883                                 max = j + 1;
1884                         if (altanims[j])
1885                                 altmax = j + 1;
1886                 }
1887                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1888
1889                 incomplete = false;
1890                 for (j = 0;j < max;j++)
1891                 {
1892                         if (!anims[j])
1893                         {
1894                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1895                                 incomplete = true;
1896                         }
1897                 }
1898                 for (j = 0;j < altmax;j++)
1899                 {
1900                         if (!altanims[j])
1901                         {
1902                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1903                                 incomplete = true;
1904                         }
1905                 }
1906                 if (incomplete)
1907                         continue;
1908
1909                 if (altmax < 1)
1910                 {
1911                         // if there is no alternate animation, duplicate the primary
1912                         // animation into the alternate
1913                         altmax = max;
1914                         for (k = 0;k < 10;k++)
1915                                 altanims[k] = anims[k];
1916                 }
1917
1918                 // link together the primary animation
1919                 for (j = 0;j < max;j++)
1920                 {
1921                         tx2 = anims[j];
1922                         tx2->animated = true;
1923                         tx2->anim_total[0] = max;
1924                         tx2->anim_total[1] = altmax;
1925                         for (k = 0;k < 10;k++)
1926                         {
1927                                 tx2->anim_frames[0][k] = anims[k];
1928                                 tx2->anim_frames[1][k] = altanims[k];
1929                         }
1930                 }
1931
1932                 // if there really is an alternate anim...
1933                 if (anims[0] != altanims[0])
1934                 {
1935                         // link together the alternate animation
1936                         for (j = 0;j < altmax;j++)
1937                         {
1938                                 tx2 = altanims[j];
1939                                 tx2->animated = true;
1940                                 // the primary/alternate are reversed here
1941                                 tx2->anim_total[0] = altmax;
1942                                 tx2->anim_total[1] = max;
1943                                 for (k = 0;k < 10;k++)
1944                                 {
1945                                         tx2->anim_frames[0][k] = altanims[k];
1946                                         tx2->anim_frames[1][k] = anims[k];
1947                                 }
1948                         }
1949                 }
1950         }
1951 }
1952
1953 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1954 {
1955         int i;
1956         unsigned char *in, *out, *data, d;
1957         char litfilename[MAX_QPATH];
1958         char dlitfilename[MAX_QPATH];
1959         fs_offset_t filesize;
1960         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1961         {
1962                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1963                 for (i=0; i<l->filelen; i++)
1964                         loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1965         }
1966         else // LordHavoc: bsp version 29 (normal white lighting)
1967         {
1968                 // LordHavoc: hope is not lost yet, check for a .lit file to load
1969                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1970                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1971                 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
1972                 strlcat (litfilename, ".lit", sizeof (litfilename));
1973                 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
1974                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
1975                 if (data)
1976                 {
1977                         if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1978                         {
1979                                 i = LittleLong(((int *)data)[1]);
1980                                 if (i == 1)
1981                                 {
1982                                         if (developer_loading.integer)
1983                                                 Con_Printf("loaded %s\n", litfilename);
1984                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1985                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
1986                                         Mem_Free(data);
1987                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
1988                                         if (data)
1989                                         {
1990                                                 if (filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1991                                                 {
1992                                                         i = LittleLong(((int *)data)[1]);
1993                                                         if (i == 1)
1994                                                         {
1995                                                                 if (developer_loading.integer)
1996                                                                         Con_Printf("loaded %s\n", dlitfilename);
1997                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
1998                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
1999                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
2000                                                                 loadmodel->brushq3.deluxemapping = true;
2001                                                         }
2002                                                 }
2003                                                 Mem_Free(data);
2004                                                 data = NULL;
2005                                         }
2006                                         return;
2007                                 }
2008                                 else
2009                                         Con_Printf("Unknown .lit file version (%d)\n", i);
2010                         }
2011                         else if (filesize == 8)
2012                                 Con_Print("Empty .lit file, ignoring\n");
2013                         else
2014                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + l->filelen * 3));
2015                         if (data)
2016                         {
2017                                 Mem_Free(data);
2018                                 data = NULL;
2019                         }
2020                 }
2021                 // LordHavoc: oh well, expand the white lighting data
2022                 if (!l->filelen)
2023                         return;
2024                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
2025                 in = mod_base + l->fileofs;
2026                 out = loadmodel->brushq1.lightdata;
2027                 for (i = 0;i < l->filelen;i++)
2028                 {
2029                         d = *in++;
2030                         *out++ = d;
2031                         *out++ = d;
2032                         *out++ = d;
2033                 }
2034         }
2035 }
2036
2037 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
2038 {
2039         loadmodel->brushq1.num_compressedpvs = 0;
2040         loadmodel->brushq1.data_compressedpvs = NULL;
2041         if (!l->filelen)
2042                 return;
2043         loadmodel->brushq1.num_compressedpvs = l->filelen;
2044         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, l->filelen);
2045         memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
2046 }
2047
2048 // used only for HalfLife maps
2049 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2050 {
2051         char key[128], value[4096];
2052         int i, j, k;
2053         if (!data)
2054                 return;
2055         if (!COM_ParseToken_Simple(&data, false, false))
2056                 return; // error
2057         if (com_token[0] != '{')
2058                 return; // error
2059         while (1)
2060         {
2061                 if (!COM_ParseToken_Simple(&data, false, false))
2062                         return; // error
2063                 if (com_token[0] == '}')
2064                         break; // end of worldspawn
2065                 if (com_token[0] == '_')
2066                         strlcpy(key, com_token + 1, sizeof(key));
2067                 else
2068                         strlcpy(key, com_token, sizeof(key));
2069                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2070                         key[strlen(key)-1] = 0;
2071                 if (!COM_ParseToken_Simple(&data, false, false))
2072                         return; // error
2073                 dpsnprintf(value, sizeof(value), "%s", com_token);
2074                 if (!strcmp("wad", key)) // for HalfLife maps
2075                 {
2076                         if (loadmodel->brush.ishlbsp)
2077                         {
2078                                 j = 0;
2079                                 for (i = 0;i < (int)sizeof(value);i++)
2080                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2081                                                 break;
2082                                 if (value[i])
2083                                 {
2084                                         for (;i < (int)sizeof(value);i++)
2085                                         {
2086                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2087                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2088                                                         j = i+1;
2089                                                 else if (value[i] == ';' || value[i] == 0)
2090                                                 {
2091                                                         k = value[i];
2092                                                         value[i] = 0;
2093                                                         W_LoadTextureWadFile(&value[j], false);
2094                                                         j = i+1;
2095                                                         if (!k)
2096                                                                 break;
2097                                                 }
2098                                         }
2099                                 }
2100                         }
2101                 }
2102         }
2103 }
2104
2105 static void Mod_Q1BSP_LoadEntities(lump_t *l)
2106 {
2107         loadmodel->brush.entities = NULL;
2108         if (!l->filelen)
2109                 return;
2110         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
2111         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
2112         loadmodel->brush.entities[l->filelen] = 0;
2113         if (loadmodel->brush.ishlbsp)
2114                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2115 }
2116
2117
2118 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
2119 {
2120         dvertex_t       *in;
2121         mvertex_t       *out;
2122         int                     i, count;
2123
2124         in = (dvertex_t *)(mod_base + l->fileofs);
2125         if (l->filelen % sizeof(*in))
2126                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2127         count = l->filelen / sizeof(*in);
2128         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2129
2130         loadmodel->brushq1.vertexes = out;
2131         loadmodel->brushq1.numvertexes = count;
2132
2133         for ( i=0 ; i<count ; i++, in++, out++)
2134         {
2135                 out->position[0] = LittleFloat(in->point[0]);
2136                 out->position[1] = LittleFloat(in->point[1]);
2137                 out->position[2] = LittleFloat(in->point[2]);
2138         }
2139 }
2140
2141 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
2142 // can be used for this
2143 // REMOVEME
2144 int SB_ReadInt (unsigned char **buffer)
2145 {
2146         int     i;
2147         i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
2148         (*buffer) += 4;
2149         return i;
2150 }
2151
2152 // REMOVEME
2153 float SB_ReadFloat (unsigned char **buffer)
2154 {
2155         union
2156         {
2157                 int             i;
2158                 float   f;
2159         } u;
2160
2161         u.i = SB_ReadInt (buffer);
2162         return u.f;
2163 }
2164
2165 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
2166 {
2167         unsigned char           *index;
2168         dmodel_t        *out;
2169         int                     i, j, count;
2170
2171         index = (unsigned char *)(mod_base + l->fileofs);
2172         if (l->filelen % (48+4*hullinfo->filehulls))
2173                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2174
2175         count = l->filelen / (48+4*hullinfo->filehulls);
2176         out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2177
2178         loadmodel->brushq1.submodels = out;
2179         loadmodel->brush.numsubmodels = count;
2180
2181         for (i = 0; i < count; i++, out++)
2182         {
2183         // spread out the mins / maxs by a pixel
2184                 out->mins[0] = SB_ReadFloat (&index) - 1;
2185                 out->mins[1] = SB_ReadFloat (&index) - 1;
2186                 out->mins[2] = SB_ReadFloat (&index) - 1;
2187                 out->maxs[0] = SB_ReadFloat (&index) + 1;
2188                 out->maxs[1] = SB_ReadFloat (&index) + 1;
2189                 out->maxs[2] = SB_ReadFloat (&index) + 1;
2190                 out->origin[0] = SB_ReadFloat (&index);
2191                 out->origin[1] = SB_ReadFloat (&index);
2192                 out->origin[2] = SB_ReadFloat (&index);
2193                 for (j = 0; j < hullinfo->filehulls; j++)
2194                         out->headnode[j] = SB_ReadInt (&index);
2195                 out->visleafs = SB_ReadInt (&index);
2196                 out->firstface = SB_ReadInt (&index);
2197                 out->numfaces = SB_ReadInt (&index);
2198         }
2199 }
2200
2201 static void Mod_Q1BSP_LoadEdges(lump_t *l)
2202 {
2203         dedge_t *in;
2204         medge_t *out;
2205         int     i, count;
2206
2207         in = (dedge_t *)(mod_base + l->fileofs);
2208         if (l->filelen % sizeof(*in))
2209                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2210         count = l->filelen / sizeof(*in);
2211         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2212
2213         loadmodel->brushq1.edges = out;
2214         loadmodel->brushq1.numedges = count;
2215
2216         for ( i=0 ; i<count ; i++, in++, out++)
2217         {
2218                 out->v[0] = (unsigned short)LittleShort(in->v[0]);
2219                 out->v[1] = (unsigned short)LittleShort(in->v[1]);
2220                 if (out->v[0] >= loadmodel->brushq1.numvertexes || out->v[1] >= loadmodel->brushq1.numvertexes)
2221                 {
2222                         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);
2223                         if(!loadmodel->brushq1.numvertexes)
2224                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2225                                 
2226                         out->v[0] = 0;
2227                         out->v[1] = 0;
2228                 }
2229         }
2230 }
2231
2232 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
2233 {
2234         texinfo_t *in;
2235         mtexinfo_t *out;
2236         int i, j, k, count, miptex;
2237
2238         in = (texinfo_t *)(mod_base + l->fileofs);
2239         if (l->filelen % sizeof(*in))
2240                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2241         count = l->filelen / sizeof(*in);
2242         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2243
2244         loadmodel->brushq1.texinfo = out;
2245         loadmodel->brushq1.numtexinfo = count;
2246
2247         for (i = 0;i < count;i++, in++, out++)
2248         {
2249                 for (k = 0;k < 2;k++)
2250                         for (j = 0;j < 4;j++)
2251                                 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
2252
2253                 miptex = LittleLong(in->miptex);
2254                 out->flags = LittleLong(in->flags);
2255
2256                 out->texture = NULL;
2257                 if (loadmodel->data_textures)
2258                 {
2259                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2260                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2261                         else
2262                                 out->texture = loadmodel->data_textures + miptex;
2263                 }
2264                 if (out->flags & TEX_SPECIAL)
2265                 {
2266                         // if texture chosen is NULL or the shader needs a lightmap,
2267                         // force to notexture water shader
2268                         if (out->texture == NULL)
2269                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2270                 }
2271                 else
2272                 {
2273                         // if texture chosen is NULL, force to notexture
2274                         if (out->texture == NULL)
2275                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2276                 }
2277         }
2278 }
2279
2280 #if 0
2281 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2282 {
2283         int             i, j;
2284         float   *v;
2285
2286         mins[0] = mins[1] = mins[2] = 9999;
2287         maxs[0] = maxs[1] = maxs[2] = -9999;
2288         v = verts;
2289         for (i = 0;i < numverts;i++)
2290         {
2291                 for (j = 0;j < 3;j++, v++)
2292                 {
2293                         if (*v < mins[j])
2294                                 mins[j] = *v;
2295                         if (*v > maxs[j])
2296                                 maxs[j] = *v;
2297                 }
2298         }
2299 }
2300
2301 #define MAX_SUBDIVPOLYTRIANGLES 4096
2302 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2303
2304 static int subdivpolyverts, subdivpolytriangles;
2305 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2306 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2307
2308 static int subdivpolylookupvert(vec3_t v)
2309 {
2310         int i;
2311         for (i = 0;i < subdivpolyverts;i++)
2312                 if (subdivpolyvert[i][0] == v[0]
2313                  && subdivpolyvert[i][1] == v[1]
2314                  && subdivpolyvert[i][2] == v[2])
2315                         return i;
2316         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2317                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2318         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2319         return subdivpolyverts++;
2320 }
2321
2322 static void SubdividePolygon(int numverts, float *verts)
2323 {
2324         int             i, i1, i2, i3, f, b, c, p;
2325         vec3_t  mins, maxs, front[256], back[256];
2326         float   m, *pv, *cv, dist[256], frac;
2327
2328         if (numverts > 250)
2329                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2330
2331         BoundPoly(numverts, verts, mins, maxs);
2332
2333         for (i = 0;i < 3;i++)
2334         {
2335                 m = (mins[i] + maxs[i]) * 0.5;
2336                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2337                 if (maxs[i] - m < 8)
2338                         continue;
2339                 if (m - mins[i] < 8)
2340                         continue;
2341
2342                 // cut it
2343                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2344                         dist[c] = cv[i] - m;
2345
2346                 f = b = 0;
2347                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2348                 {
2349                         if (dist[p] >= 0)
2350                         {
2351                                 VectorCopy(pv, front[f]);
2352                                 f++;
2353                         }
2354                         if (dist[p] <= 0)
2355                         {
2356                                 VectorCopy(pv, back[b]);
2357                                 b++;
2358                         }
2359                         if (dist[p] == 0 || dist[c] == 0)
2360                                 continue;
2361                         if ((dist[p] > 0) != (dist[c] > 0) )
2362                         {
2363                                 // clip point
2364                                 frac = dist[p] / (dist[p] - dist[c]);
2365                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2366                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2367                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2368                                 f++;
2369                                 b++;
2370                         }
2371                 }
2372
2373                 SubdividePolygon(f, front[0]);
2374                 SubdividePolygon(b, back[0]);
2375                 return;
2376         }
2377
2378         i1 = subdivpolylookupvert(verts);
2379         i2 = subdivpolylookupvert(verts + 3);
2380         for (i = 2;i < numverts;i++)
2381         {
2382                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2383                 {
2384                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2385                         return;
2386                 }
2387
2388                 i3 = subdivpolylookupvert(verts + i * 3);
2389                 subdivpolyindex[subdivpolytriangles][0] = i1;
2390                 subdivpolyindex[subdivpolytriangles][1] = i2;
2391                 subdivpolyindex[subdivpolytriangles][2] = i3;
2392                 i2 = i3;
2393                 subdivpolytriangles++;
2394         }
2395 }
2396
2397 //Breaks a polygon up along axial 64 unit
2398 //boundaries so that turbulent and sky warps
2399 //can be done reasonably.
2400 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2401 {
2402         int i, j;
2403         surfvertex_t *v;
2404         surfmesh_t *mesh;
2405
2406         subdivpolytriangles = 0;
2407         subdivpolyverts = 0;
2408         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2409         if (subdivpolytriangles < 1)
2410                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2411
2412         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2413         mesh->num_vertices = subdivpolyverts;
2414         mesh->num_triangles = subdivpolytriangles;
2415         mesh->vertex = (surfvertex_t *)(mesh + 1);
2416         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2417         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2418
2419         for (i = 0;i < mesh->num_triangles;i++)
2420                 for (j = 0;j < 3;j++)
2421                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2422
2423         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2424         {
2425                 VectorCopy(subdivpolyvert[i], v->v);
2426                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2427                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2428         }
2429 }
2430 #endif
2431
2432 extern cvar_t gl_max_lightmapsize;
2433 static void Mod_Q1BSP_LoadFaces(lump_t *l)
2434 {
2435         dface_t *in;
2436         msurface_t *surface;
2437         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples;
2438         float texmins[2], texmaxs[2], val;
2439         rtexture_t *lightmaptexture, *deluxemaptexture;
2440
2441         in = (dface_t *)(mod_base + l->fileofs);
2442         if (l->filelen % sizeof(*in))
2443                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2444         count = l->filelen / sizeof(*in);
2445         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2446         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2447
2448         loadmodel->num_surfaces = count;
2449
2450         loadmodel->brushq1.firstrender = true;
2451         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2452
2453         totalverts = 0;
2454         totaltris = 0;
2455         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
2456         {
2457                 numedges = (unsigned short)LittleShort(in->numedges);
2458                 totalverts += numedges;
2459                 totaltris += numedges - 2;
2460         }
2461
2462         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2463
2464         lightmaptexture = NULL;
2465         deluxemaptexture = r_texture_blanknormalmap;
2466         lightmapnumber = 0;
2467         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2468         totallightmapsamples = 0;
2469
2470         totalverts = 0;
2471         totaltris = 0;
2472         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
2473         {
2474                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2475
2476                 // FIXME: validate edges, texinfo, etc?
2477                 firstedge = LittleLong(in->firstedge);
2478                 numedges = (unsigned short)LittleShort(in->numedges);
2479                 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)
2480                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2481                 i = (unsigned short)LittleShort(in->texinfo);
2482                 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
2483                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", i, loadmodel->brushq1.numtexinfo);
2484                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
2485                 surface->texture = surface->lightmapinfo->texinfo->texture;
2486
2487                 planenum = (unsigned short)LittleShort(in->planenum);
2488                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2489                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2490
2491                 //surface->flags = surface->texture->flags;
2492                 //if (LittleShort(in->side))
2493                 //      surface->flags |= SURF_PLANEBACK;
2494                 //surface->plane = loadmodel->brush.data_planes + planenum;
2495
2496                 surface->num_firstvertex = totalverts;
2497                 surface->num_vertices = numedges;
2498                 surface->num_firsttriangle = totaltris;
2499                 surface->num_triangles = numedges - 2;
2500                 totalverts += numedges;
2501                 totaltris += numedges - 2;
2502
2503                 // convert edges back to a normal polygon
2504                 for (i = 0;i < surface->num_vertices;i++)
2505                 {
2506                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2507                         float s, t;
2508                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2509                         if (lindex >= 0)
2510                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2511                         else
2512                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2513                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2514                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2515                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2516                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2517                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2518                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2519                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2520                 }
2521
2522                 for (i = 0;i < surface->num_triangles;i++)
2523                 {
2524                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2525                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2526                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2527                 }
2528
2529                 // compile additional data about the surface geometry
2530                 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);
2531                 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);
2532                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2533
2534                 // generate surface extents information
2535                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2536                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2537                 for (i = 1;i < surface->num_vertices;i++)
2538                 {
2539                         for (j = 0;j < 2;j++)
2540                         {
2541                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2542                                 texmins[j] = min(texmins[j], val);
2543                                 texmaxs[j] = max(texmaxs[j], val);
2544                         }
2545                 }
2546                 for (i = 0;i < 2;i++)
2547                 {
2548                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2549                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2550                 }
2551
2552                 smax = surface->lightmapinfo->extents[0] >> 4;
2553                 tmax = surface->lightmapinfo->extents[1] >> 4;
2554                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2555                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2556
2557                 // lighting info
2558                 for (i = 0;i < MAXLIGHTMAPS;i++)
2559                         surface->lightmapinfo->styles[i] = in->styles[i];
2560                 surface->lightmaptexture = NULL;
2561                 surface->deluxemaptexture = r_texture_blanknormalmap;
2562                 i = LittleLong(in->lightofs);
2563                 if (i == -1)
2564                 {
2565                         surface->lightmapinfo->samples = NULL;
2566 #if 1
2567                         // give non-lightmapped water a 1x white lightmap
2568                         if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2569                         {
2570                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2571                                 surface->lightmapinfo->styles[0] = 0;
2572                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2573                         }
2574 #endif
2575                 }
2576                 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2577                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2578                 else // LordHavoc: white lighting (bsp version 29)
2579                 {
2580                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2581                         if (loadmodel->brushq1.nmaplightdata)
2582                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (i * 3);
2583                 }
2584
2585                 // check if we should apply a lightmap to this
2586                 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2587                 {
2588                         if (ssize > 256 || tsize > 256)
2589                                 Host_Error("Bad surface extents");
2590
2591                         if (lightmapsize < ssize)
2592                                 lightmapsize = ssize;
2593                         if (lightmapsize < tsize)
2594                                 lightmapsize = tsize;
2595
2596                         totallightmapsamples += ssize*tsize;
2597
2598                         // force lightmap upload on first time seeing the surface
2599                         //
2600                         // additionally this is used by the later code to see if a
2601                         // lightmap is needed on this surface (rather than duplicating the
2602                         // logic above)
2603                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2604                         loadmodel->lit = true;
2605                 }
2606         }
2607
2608         // small maps (such as ammo boxes especially) don't need big lightmap
2609         // textures, so this code tries to guess a good size based on
2610         // totallightmapsamples (size of the lightmaps lump basically), as well as
2611         // trying to max out the size if there is a lot of lightmap data to store
2612         // additionally, never choose a lightmapsize that is smaller than the
2613         // largest surface encountered (as it would fail)
2614         i = lightmapsize;
2615         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2616                 ;
2617
2618         // now that we've decided the lightmap texture size, we can do the rest
2619         if (cls.state != ca_dedicated)
2620         {
2621                 int stainmapsize = 0;
2622                 mod_alloclightmap_state_t allocState;
2623
2624                 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2625                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2626                 {
2627                         int i, iu, iv, lightmapx = 0, lightmapy = 0;
2628                         float u, v, ubase, vbase, uscale, vscale;
2629
2630                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2631                                 continue;
2632
2633                         smax = surface->lightmapinfo->extents[0] >> 4;
2634                         tmax = surface->lightmapinfo->extents[1] >> 4;
2635                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2636                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2637                         stainmapsize += ssize * tsize * 3;
2638
2639                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2640                         {
2641                                 // allocate a texture pool if we need it
2642                                 if (loadmodel->texturepool == NULL)
2643                                         loadmodel->texturepool = R_AllocTexturePool();
2644                                 // could not find room, make a new lightmap
2645                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2646                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2647                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2648                                 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2649                                 if (loadmodel->brushq1.nmaplightdata)
2650                                         loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va("deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2651                                 lightmapnumber++;
2652                                 Mod_AllocLightmap_Reset(&allocState);
2653                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2654                         }
2655                         surface->lightmaptexture = lightmaptexture;
2656                         surface->deluxemaptexture = deluxemaptexture;
2657                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2658                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2659
2660                         uscale = 1.0f / (float)lightmapsize;
2661                         vscale = 1.0f / (float)lightmapsize;
2662                         ubase = lightmapx * uscale;
2663                         vbase = lightmapy * vscale;
2664
2665                         for (i = 0;i < surface->num_vertices;i++)
2666                         {
2667                                 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);
2668                                 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);
2669                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2670                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2671                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2672                                 iu = (int) u;
2673                                 iv = (int) v;
2674                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2675                         }
2676                 }
2677
2678                 if (cl_stainmaps.integer)
2679                 {
2680                         // allocate stainmaps for permanent marks on walls and clear white
2681                         unsigned char *stainsamples = NULL;
2682                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2683                         memset(stainsamples, 255, stainmapsize);
2684                         // assign pointers
2685                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2686                         {
2687                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2688                                         continue;
2689                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2690                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2691                                 surface->lightmapinfo->stainsamples = stainsamples;
2692                                 stainsamples += ssize * tsize * 3;
2693                         }
2694                 }
2695         }
2696
2697         // generate ushort elements array if possible
2698         if (loadmodel->surfmesh.data_element3s)
2699                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2700                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2701 }
2702
2703 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2704 {
2705         //if (node->parent)
2706         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2707         node->parent = parent;
2708         if (node->plane)
2709         {
2710                 // this is a node, recurse to children
2711                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2712                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2713                 // combine supercontents of children
2714                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2715         }
2716         else
2717         {
2718                 int j;
2719                 mleaf_t *leaf = (mleaf_t *)node;
2720                 // if this is a leaf, calculate supercontents mask from all collidable
2721                 // primitives in the leaf (brushes and collision surfaces)
2722                 // also flag if the leaf contains any collision surfaces
2723                 leaf->combinedsupercontents = 0;
2724                 // combine the supercontents values of all brushes in this leaf
2725                 for (j = 0;j < leaf->numleafbrushes;j++)
2726                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2727                 // check if this leaf contains any collision surfaces (q3 patches)
2728                 for (j = 0;j < leaf->numleafsurfaces;j++)
2729                 {
2730                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2731                         if (surface->num_collisiontriangles)
2732                         {
2733                                 leaf->containscollisionsurfaces = true;
2734                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2735                         }
2736                 }
2737         }
2738 }
2739
2740 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2741 {
2742         int                     i, j, count, p;
2743         dnode_t         *in;
2744         mnode_t         *out;
2745
2746         in = (dnode_t *)(mod_base + l->fileofs);
2747         if (l->filelen % sizeof(*in))
2748                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2749         count = l->filelen / sizeof(*in);
2750         if (count == 0)
2751                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2752         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2753
2754         loadmodel->brush.data_nodes = out;
2755         loadmodel->brush.num_nodes = count;
2756
2757         for ( i=0 ; i<count ; i++, in++, out++)
2758         {
2759                 for (j=0 ; j<3 ; j++)
2760                 {
2761                         out->mins[j] = LittleShort(in->mins[j]);
2762                         out->maxs[j] = LittleShort(in->maxs[j]);
2763                 }
2764
2765                 p = LittleLong(in->planenum);
2766                 out->plane = loadmodel->brush.data_planes + p;
2767
2768                 out->firstsurface = (unsigned short)LittleShort(in->firstface);
2769                 out->numsurfaces = (unsigned short)LittleShort(in->numfaces);
2770
2771                 for (j=0 ; j<2 ; j++)
2772                 {
2773                         // LordHavoc: this code supports broken bsp files produced by
2774                         // arguire qbsp which can produce more than 32768 nodes, any value
2775                         // below count is assumed to be a node number, any other value is
2776                         // assumed to be a leaf number
2777                         p = (unsigned short)LittleShort(in->children[j]);
2778                         if (p < count)
2779                         {
2780                                 if (p < loadmodel->brush.num_nodes)
2781                                         out->children[j] = loadmodel->brush.data_nodes + p;
2782                                 else
2783                                 {
2784                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2785                                         // map it to the solid leaf
2786                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2787                                 }
2788                         }
2789                         else
2790                         {
2791                                 // note this uses 65535 intentionally, -1 is leaf 0
2792                                 p = 65535 - p;
2793                                 if (p < loadmodel->brush.num_leafs)
2794                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2795                                 else
2796                                 {
2797                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2798                                         // map it to the solid leaf
2799                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2800                                 }
2801                         }
2802                 }
2803         }
2804
2805         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2806 }
2807
2808 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2809 {
2810         dleaf_t *in;
2811         mleaf_t *out;
2812         int i, j, count, p;
2813
2814         in = (dleaf_t *)(mod_base + l->fileofs);
2815         if (l->filelen % sizeof(*in))
2816                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2817         count = l->filelen / sizeof(*in);
2818         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2819
2820         loadmodel->brush.data_leafs = out;
2821         loadmodel->brush.num_leafs = count;
2822         // get visleafs from the submodel data
2823         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2824         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2825         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2826         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2827
2828         for ( i=0 ; i<count ; i++, in++, out++)
2829         {
2830                 for (j=0 ; j<3 ; j++)
2831                 {
2832                         out->mins[j] = LittleShort(in->mins[j]);
2833                         out->maxs[j] = LittleShort(in->maxs[j]);
2834                 }
2835
2836                 // FIXME: this function could really benefit from some error checking
2837
2838                 out->contents = LittleLong(in->contents);
2839
2840                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + (unsigned short)LittleShort(in->firstmarksurface);
2841                 out->numleafsurfaces = (unsigned short)LittleShort(in->nummarksurfaces);
2842                 if ((unsigned short)LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2843                 {
2844                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", (int)(out->firstleafsurface - loadmodel->brush.data_leafsurfaces), (int)(out->firstleafsurface + out->numleafsurfaces - loadmodel->brush.data_leafsurfaces), 0, loadmodel->brush.num_leafsurfaces);
2845                         out->firstleafsurface = NULL;
2846                         out->numleafsurfaces = 0;
2847                 }
2848
2849                 out->clusterindex = i - 1;
2850                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2851                         out->clusterindex = -1;
2852
2853                 p = LittleLong(in->visofs);
2854                 // ignore visofs errors on leaf 0 (solid)
2855                 if (p >= 0 && out->clusterindex >= 0)
2856                 {
2857                         if (p >= loadmodel->brushq1.num_compressedpvs)
2858                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2859                         else
2860                                 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);
2861                 }
2862
2863                 for (j = 0;j < 4;j++)
2864                         out->ambient_sound_level[j] = in->ambient_level[j];
2865
2866                 // FIXME: Insert caustics here
2867         }
2868 }
2869
2870 qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2871 {
2872         int i, j;
2873         mleaf_t *leaf;
2874         const unsigned char *pvs;
2875         // if there's no vis data, assume supported (because everything is visible all the time)
2876         if (!loadmodel->brush.data_pvsclusters)
2877                 return true;
2878         // check all liquid leafs to see if they can see into empty leafs, if any
2879         // can we can assume this map supports r_wateralpha
2880         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2881         {
2882                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2883                 {
2884                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2885                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
2886                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2887                                         return true;
2888                 }
2889         }
2890         return false;
2891 }
2892
2893 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2894 {
2895         dclipnode_t *in;
2896         mclipnode_t *out;
2897         int                     i, count;
2898         hull_t          *hull;
2899
2900         in = (dclipnode_t *)(mod_base + l->fileofs);
2901         if (l->filelen % sizeof(*in))
2902                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2903         count = l->filelen / sizeof(*in);
2904         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2905
2906         loadmodel->brushq1.clipnodes = out;
2907         loadmodel->brushq1.numclipnodes = count;
2908
2909         for (i = 1; i < MAX_MAP_HULLS; i++)
2910         {
2911                 hull = &loadmodel->brushq1.hulls[i];
2912                 hull->clipnodes = out;
2913                 hull->firstclipnode = 0;
2914                 hull->lastclipnode = count-1;
2915                 hull->planes = loadmodel->brush.data_planes;
2916                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2917                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2918                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2919                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2920                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2921                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2922                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2923         }
2924
2925         for (i=0 ; i<count ; i++, out++, in++)
2926         {
2927                 out->planenum = LittleLong(in->planenum);
2928                 // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
2929                 out->children[0] = (unsigned short)LittleShort(in->children[0]);
2930                 out->children[1] = (unsigned short)LittleShort(in->children[1]);
2931                 if (out->children[0] >= count)
2932                         out->children[0] -= 65536;
2933                 if (out->children[1] >= count)
2934                         out->children[1] -= 65536;
2935                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
2936                         Host_Error("Corrupt clipping hull(out of range planenum)");
2937         }
2938 }
2939
2940 //Duplicate the drawing hull structure as a clipping hull
2941 static void Mod_Q1BSP_MakeHull0(void)
2942 {
2943         mnode_t         *in;
2944         mclipnode_t *out;
2945         int                     i;
2946         hull_t          *hull;
2947
2948         hull = &loadmodel->brushq1.hulls[0];
2949
2950         in = loadmodel->brush.data_nodes;
2951         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
2952
2953         hull->clipnodes = out;