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