]> icculus.org git repositories - divverent/darkplaces.git/blob - model_brush.c
don't send empty lightstyles during signon
[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"};
30 cvar_t halflifebsp = {0, "halflifebsp", "0"};
31 cvar_t mcbsp = {0, "mcbsp", "0"};
32 cvar_t r_novis = {0, "r_novis", "0"};
33 cvar_t r_miplightmaps = {CVAR_SAVE, "r_miplightmaps", "0"};
34 cvar_t r_lightmaprgba = {0, "r_lightmaprgba", "1"};
35 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0"};
36 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4"};
37 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "1"};
38 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024"};
39 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536"};
40 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15"};
41 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "1"};
42 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024"};
43 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225"};
44 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1"};
45 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1"};
46 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0"};
47
48 void Mod_BrushInit(void)
49 {
50 //      Cvar_RegisterVariable(&r_subdivide_size);
51         Cvar_RegisterVariable(&halflifebsp);
52         Cvar_RegisterVariable(&mcbsp);
53         Cvar_RegisterVariable(&r_novis);
54         Cvar_RegisterVariable(&r_miplightmaps);
55         Cvar_RegisterVariable(&r_lightmaprgba);
56         Cvar_RegisterVariable(&r_nosurftextures);
57         Cvar_RegisterVariable(&r_subdivisions_tolerance);
58         Cvar_RegisterVariable(&r_subdivisions_mintess);
59         Cvar_RegisterVariable(&r_subdivisions_maxtess);
60         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
61         Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
62         Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
63         Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
64         Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
65         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
66         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
67         Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
68 }
69
70 static mleaf_t *Mod_Q1BSP_PointInLeaf(model_t *model, const vec3_t p)
71 {
72         mnode_t *node;
73
74         if (model == NULL)
75                 return NULL;
76
77         // LordHavoc: modified to start at first clip node,
78         // in other words: first node of the (sub)model
79         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
80         while (node->plane)
81                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
82
83         return (mleaf_t *)node;
84 }
85
86 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(model_t *model, const vec3_t p, qbyte *out, int outsize)
87 {
88         int i;
89         mleaf_t *leaf;
90         leaf = Mod_Q1BSP_PointInLeaf(model, p);
91         if (leaf)
92         {
93                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
94                 if (i)
95                 {
96                         memcpy(out, leaf->ambient_sound_level, i);
97                         out += i;
98                         outsize -= i;
99                 }
100         }
101         if (outsize)
102                 memset(out, 0, outsize);
103 }
104
105 static int Mod_Q1BSP_FindBoxClusters(model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
106 {
107         int numclusters = 0, side, nodestackindex = 0;
108         mnode_t *node, *nodestack[1024];
109         if (!model->brush.num_pvsclusters)
110                 return -1;
111         node = model->brush.data_nodes;
112         for (;;)
113         {
114                 if (node->plane)
115                 {
116                         // node - recurse down the BSP tree
117                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
118                         if (side < 2)
119                         {
120                                 // box is on one side of plane, take that path
121                                 node = node->children[side];
122                         }
123                         else
124                         {
125                                 // box crosses plane, take one path and remember the other
126                                 if (nodestackindex < 1024)
127                                         nodestack[nodestackindex++] = node->children[0];
128                                 node = node->children[1];
129                         }
130                 }
131                 else
132                 {
133                         // leaf - check cluster bit
134                         if (numclusters < maxclusters)
135                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
136                         numclusters++;
137                         // try another path we didn't take earlier
138                         if (nodestackindex == 0)
139                                 break;
140                         node = nodestack[--nodestackindex];
141                 }
142         }
143         // return number of clusters found (even if more than the maxclusters)
144         return numclusters;
145 }
146
147 static int Mod_Q1BSP_BoxTouchingPVS(model_t *model, const qbyte *pvs, const vec3_t mins, const vec3_t maxs)
148 {
149         int clusterindex, side, nodestackindex = 0;
150         mnode_t *node, *nodestack[1024];
151         if (!model->brush.num_pvsclusters)
152                 return true;
153         node = model->brush.data_nodes;
154         for (;;)
155         {
156                 if (node->plane)
157                 {
158                         // node - recurse down the BSP tree
159                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
160                         if (side < 2)
161                         {
162                                 // box is on one side of plane, take that path
163                                 node = node->children[side];
164                         }
165                         else
166                         {
167                                 // box crosses plane, take one path and remember the other
168                                 if (nodestackindex < 1024)
169                                         nodestack[nodestackindex++] = node->children[0];
170                                 node = node->children[1];
171                         }
172                 }
173                 else
174                 {
175                         // leaf - check cluster bit
176                         clusterindex = ((mleaf_t *)node)->clusterindex;
177                         if (CHECKPVSBIT(pvs, clusterindex))
178                         {
179                                 // it is visible, return immediately with the news
180                                 return true;
181                         }
182                         else
183                         {
184                                 // nothing to see here, try another path we didn't take earlier
185                                 if (nodestackindex == 0)
186                                         break;
187                                 node = nodestack[--nodestackindex];
188                         }
189                 }
190         }
191         // it is not visible
192         return false;
193 }
194
195 static int Mod_Q1BSP_BoxTouchingLeafPVS(model_t *model, const qbyte *pvs, const vec3_t mins, const vec3_t maxs)
196 {
197         int clusterindex, side, nodestackindex = 0;
198         mnode_t *node, *nodestack[1024];
199         if (!model->brush.num_leafs)
200                 return true;
201         node = model->brush.data_nodes;
202         for (;;)
203         {
204                 if (node->plane)
205                 {
206                         // node - recurse down the BSP tree
207                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
208                         if (side < 2)
209                         {
210                                 // box is on one side of plane, take that path
211                                 node = node->children[side];
212                         }
213                         else
214                         {
215                                 // box crosses plane, take one path and remember the other
216                                 if (nodestackindex < 1024)
217                                         nodestack[nodestackindex++] = node->children[0];
218                                 node = node->children[1];
219                         }
220                 }
221                 else
222                 {
223                         // leaf - check cluster bit
224                         clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
225                         if (CHECKPVSBIT(pvs, clusterindex))
226                         {
227                                 // it is visible, return immediately with the news
228                                 return true;
229                         }
230                         else
231                         {
232                                 // nothing to see here, try another path we didn't take earlier
233                                 if (nodestackindex == 0)
234                                         break;
235                                 node = nodestack[--nodestackindex];
236                         }
237                 }
238         }
239         // it is not visible
240         return false;
241 }
242
243 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(model_t *model, const qbyte *visibleleafs, const vec3_t mins, const vec3_t maxs)
244 {
245         int side, nodestackindex = 0;
246         mnode_t *node, *nodestack[1024];
247         node = model->brush.data_nodes;
248         for (;;)
249         {
250                 if (node->plane)
251                 {
252                         // node - recurse down the BSP tree
253                         side = BoxOnPlaneSide(mins, maxs, node->plane) - 1;
254                         if (side < 2)
255                         {
256                                 // box is on one side of plane, take that path
257                                 node = node->children[side];
258                         }
259                         else
260                         {
261                                 // box crosses plane, take one path and remember the other
262                                 if (nodestackindex < 1024)
263                                         nodestack[nodestackindex++] = node->children[0];
264                                 node = node->children[1];
265                         }
266                 }
267                 else
268                 {
269                         // leaf - check if it is visible
270                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
271                         {
272                                 // it is visible, return immediately with the news
273                                 return true;
274                         }
275                         else
276                         {
277                                 // nothing to see here, try another path we didn't take earlier
278                                 if (nodestackindex == 0)
279                                         break;
280                                 node = nodestack[--nodestackindex];
281                         }
282                 }
283         }
284         // it is not visible
285         return false;
286 }
287
288 typedef struct findnonsolidlocationinfo_s
289 {
290         vec3_t center;
291         vec_t radius;
292         vec3_t nudge;
293         vec_t bestdist;
294         model_t *model;
295 }
296 findnonsolidlocationinfo_t;
297
298 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
299 {
300         int i, surfacenum, k, *tri, *mark;
301         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
302         msurface_t *surface;
303         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
304         {
305                 surface = info->model->data_surfaces + *mark;
306                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
307                 {
308                         for (k = 0;k < surface->num_triangles;k++)
309                         {
310                                 tri = (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle) + k * 3;
311                                 VectorCopy((surface->groupmesh->data_vertex3f + tri[0] * 3), vert[0]);
312                                 VectorCopy((surface->groupmesh->data_vertex3f + tri[1] * 3), vert[1]);
313                                 VectorCopy((surface->groupmesh->data_vertex3f + tri[2] * 3), vert[2]);
314                                 VectorSubtract(vert[1], vert[0], edge[0]);
315                                 VectorSubtract(vert[2], vert[1], edge[1]);
316                                 CrossProduct(edge[1], edge[0], facenormal);
317                                 if (facenormal[0] || facenormal[1] || facenormal[2])
318                                 {
319                                         VectorNormalize(facenormal);
320                                         f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
321                                         if (f <= info->bestdist && f >= -info->bestdist)
322                                         {
323                                                 VectorSubtract(vert[0], vert[2], edge[2]);
324                                                 VectorNormalize(edge[0]);
325                                                 VectorNormalize(edge[1]);
326                                                 VectorNormalize(edge[2]);
327                                                 CrossProduct(facenormal, edge[0], edgenormal[0]);
328                                                 CrossProduct(facenormal, edge[1], edgenormal[1]);
329                                                 CrossProduct(facenormal, edge[2], edgenormal[2]);
330                                                 // face distance
331                                                 if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
332                                                  && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
333                                                  && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
334                                                 {
335                                                         // we got lucky, the center is within the face
336                                                         dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
337                                                         if (dist < 0)
338                                                         {
339                                                                 dist = -dist;
340                                                                 if (info->bestdist > dist)
341                                                                 {
342                                                                         info->bestdist = dist;
343                                                                         VectorScale(facenormal, (info->radius - -dist), info->nudge);
344                                                                 }
345                                                         }
346                                                         else
347                                                         {
348                                                                 if (info->bestdist > dist)
349                                                                 {
350                                                                         info->bestdist = dist;
351                                                                         VectorScale(facenormal, (info->radius - dist), info->nudge);
352                                                                 }
353                                                         }
354                                                 }
355                                                 else
356                                                 {
357                                                         // check which edge or vertex the center is nearest
358                                                         for (i = 0;i < 3;i++)
359                                                         {
360                                                                 f = DotProduct(info->center, edge[i]);
361                                                                 if (f >= DotProduct(vert[0], edge[i])
362                                                                  && f <= DotProduct(vert[1], edge[i]))
363                                                                 {
364                                                                         // on edge
365                                                                         VectorMA(info->center, -f, edge[i], point);
366                                                                         dist = sqrt(DotProduct(point, point));
367                                                                         if (info->bestdist > dist)
368                                                                         {
369                                                                                 info->bestdist = dist;
370                                                                                 VectorScale(point, (info->radius / dist), info->nudge);
371                                                                         }
372                                                                         // skip both vertex checks
373                                                                         // (both are further away than this edge)
374                                                                         i++;
375                                                                 }
376                                                                 else
377                                                                 {
378                                                                         // not on edge, check first vertex of edge
379                                                                         VectorSubtract(info->center, vert[i], point);
380                                                                         dist = sqrt(DotProduct(point, point));
381                                                                         if (info->bestdist > dist)
382                                                                         {
383                                                                                 info->bestdist = dist;
384                                                                                 VectorScale(point, (info->radius / dist), info->nudge);
385                                                                         }
386                                                                 }
387                                                         }
388                                                 }
389                                         }
390                                 }
391                         }
392                 }
393         }
394 }
395
396 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
397 {
398         if (node->plane)
399         {
400                 float f = PlaneDiff(info->center, node->plane);
401                 if (f >= -info->bestdist)
402                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
403                 if (f <= info->bestdist)
404                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
405         }
406         else
407         {
408                 if (((mleaf_t *)node)->numleafsurfaces)
409                         Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
410         }
411 }
412
413 static void Mod_Q1BSP_FindNonSolidLocation(model_t *model, const vec3_t in, vec3_t out, float radius)
414 {
415         int i;
416         findnonsolidlocationinfo_t info;
417         if (model == NULL)
418         {
419                 VectorCopy(in, out);
420                 return;
421         }
422         VectorCopy(in, info.center);
423         info.radius = radius;
424         info.model = model;
425         i = 0;
426         do
427         {
428                 VectorClear(info.nudge);
429                 info.bestdist = radius;
430                 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
431                 VectorAdd(info.center, info.nudge, info.center);
432         }
433         while (info.bestdist < radius && ++i < 10);
434         VectorCopy(info.center, out);
435 }
436
437 int Mod_Q1BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
438 {
439         switch(nativecontents)
440         {
441                 case CONTENTS_EMPTY:
442                         return 0;
443                 case CONTENTS_SOLID:
444                         return SUPERCONTENTS_SOLID;
445                 case CONTENTS_WATER:
446                         return SUPERCONTENTS_WATER;
447                 case CONTENTS_SLIME:
448                         return SUPERCONTENTS_SLIME;
449                 case CONTENTS_LAVA:
450                         return SUPERCONTENTS_LAVA;
451                 case CONTENTS_SKY:
452                         return SUPERCONTENTS_SKY;
453         }
454         return 0;
455 }
456
457 int Mod_Q1BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
458 {
459         if (supercontents & SUPERCONTENTS_SOLID)
460                 return CONTENTS_SOLID;
461         if (supercontents & SUPERCONTENTS_SKY)
462                 return CONTENTS_SKY;
463         if (supercontents & SUPERCONTENTS_LAVA)
464                 return CONTENTS_LAVA;
465         if (supercontents & SUPERCONTENTS_SLIME)
466                 return CONTENTS_SLIME;
467         if (supercontents & SUPERCONTENTS_WATER)
468                 return CONTENTS_WATER;
469         return CONTENTS_EMPTY;
470 }
471
472 typedef struct RecursiveHullCheckTraceInfo_s
473 {
474         // the hull we're tracing through
475         const hull_t *hull;
476
477         // the trace structure to fill in
478         trace_t *trace;
479
480         // start, end, and end - start (in model space)
481         double start[3];
482         double end[3];
483         double dist[3];
484 }
485 RecursiveHullCheckTraceInfo_t;
486
487 // 1/32 epsilon to keep floating point happy
488 #define DIST_EPSILON (0.03125)
489
490 #define HULLCHECKSTATE_EMPTY 0
491 #define HULLCHECKSTATE_SOLID 1
492 #define HULLCHECKSTATE_DONE 2
493
494 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
495 {
496         // status variables, these don't need to be saved on the stack when
497         // recursing...  but are because this should be thread-safe
498         // (note: tracing against a bbox is not thread-safe, yet)
499         int ret;
500         mplane_t *plane;
501         double t1, t2;
502
503         // variables that need to be stored on the stack when recursing
504         dclipnode_t *node;
505         int side;
506         double midf, mid[3];
507
508         // LordHavoc: a goto!  everyone flee in terror... :)
509 loc0:
510         // check for empty
511         if (num < 0)
512         {
513                 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
514                 if (!t->trace->startfound)
515                 {
516                         t->trace->startfound = true;
517                         t->trace->startsupercontents |= num;
518                 }
519                 if (num & SUPERCONTENTS_LIQUIDSMASK)
520                         t->trace->inwater = true;
521                 if (num == 0)
522                         t->trace->inopen = true;
523                 if (num & t->trace->hitsupercontentsmask)
524                 {
525                         // if the first leaf is solid, set startsolid
526                         if (t->trace->allsolid)
527                                 t->trace->startsolid = true;
528 #if COLLISIONPARANOID >= 3
529                         Con_Print("S");
530 #endif
531                         return HULLCHECKSTATE_SOLID;
532                 }
533                 else
534                 {
535                         t->trace->allsolid = false;
536 #if COLLISIONPARANOID >= 3
537                         Con_Print("E");
538 #endif
539                         return HULLCHECKSTATE_EMPTY;
540                 }
541         }
542
543         // find the point distances
544         node = t->hull->clipnodes + num;
545
546         plane = t->hull->planes + node->planenum;
547         if (plane->type < 3)
548         {
549                 t1 = p1[plane->type] - plane->dist;
550                 t2 = p2[plane->type] - plane->dist;
551         }
552         else
553         {
554                 t1 = DotProduct (plane->normal, p1) - plane->dist;
555                 t2 = DotProduct (plane->normal, p2) - plane->dist;
556         }
557
558         if (t1 < 0)
559         {
560                 if (t2 < 0)
561                 {
562 #if COLLISIONPARANOID >= 3
563                         Con_Print("<");
564 #endif
565                         num = node->children[1];
566                         goto loc0;
567                 }
568                 side = 1;
569         }
570         else
571         {
572                 if (t2 >= 0)
573                 {
574 #if COLLISIONPARANOID >= 3
575                         Con_Print(">");
576 #endif
577                         num = node->children[0];
578                         goto loc0;
579                 }
580                 side = 0;
581         }
582
583         // the line intersects, find intersection point
584         // LordHavoc: this uses the original trace for maximum accuracy
585 #if COLLISIONPARANOID >= 3
586         Con_Print("M");
587 #endif
588         if (plane->type < 3)
589         {
590                 t1 = t->start[plane->type] - plane->dist;
591                 t2 = t->end[plane->type] - plane->dist;
592         }
593         else
594         {
595                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
596                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
597         }
598
599         midf = t1 / (t1 - t2);
600         midf = bound(p1f, midf, p2f);
601         VectorMA(t->start, midf, t->dist, mid);
602
603         // recurse both sides, front side first
604         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
605         // if this side is not empty, return what it is (solid or done)
606         if (ret != HULLCHECKSTATE_EMPTY)
607                 return ret;
608
609         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
610         // if other side is not solid, return what it is (empty or done)
611         if (ret != HULLCHECKSTATE_SOLID)
612                 return ret;
613
614         // front is air and back is solid, this is the impact point...
615         if (side)
616         {
617                 t->trace->plane.dist = -plane->dist;
618                 VectorNegate (plane->normal, t->trace->plane.normal);
619         }
620         else
621         {
622                 t->trace->plane.dist = plane->dist;
623                 VectorCopy (plane->normal, t->trace->plane.normal);
624         }
625
626         // calculate the true fraction
627         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
628         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
629         midf = t1 / (t1 - t2);
630         t->trace->realfraction = bound(0, midf, 1);
631
632         // calculate the return fraction which is nudged off the surface a bit
633         midf = (t1 - DIST_EPSILON) / (t1 - t2);
634         t->trace->fraction = bound(0, midf, 1);
635
636 #if COLLISIONPARANOID >= 3
637         Con_Print("D");
638 #endif
639         return HULLCHECKSTATE_DONE;
640 }
641
642 #if COLLISIONPARANOID < 2
643 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
644 {
645         while (num >= 0)
646                 num = t->hull->clipnodes[num].children[(t->hull->planes[t->hull->clipnodes[num].planenum].type < 3 ? t->start[t->hull->planes[t->hull->clipnodes[num].planenum].type] : DotProduct(t->hull->planes[t->hull->clipnodes[num].planenum].normal, t->start)) < t->hull->planes[t->hull->clipnodes[num].planenum].dist];
647         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
648         t->trace->startsupercontents |= num;
649         if (num & SUPERCONTENTS_LIQUIDSMASK)
650                 t->trace->inwater = true;
651         if (num == 0)
652                 t->trace->inopen = true;
653         if (num & t->trace->hitsupercontentsmask)
654         {
655                 t->trace->allsolid = t->trace->startsolid = true;
656                 return HULLCHECKSTATE_SOLID;
657         }
658         else
659         {
660                 t->trace->allsolid = t->trace->startsolid = false;
661                 return HULLCHECKSTATE_EMPTY;
662         }
663 }
664 #endif
665
666 static void Mod_Q1BSP_TraceBox(struct model_s *model, int frame, trace_t *trace, const vec3_t boxstartmins, const vec3_t boxstartmaxs, const vec3_t boxendmins, const vec3_t boxendmaxs, int hitsupercontentsmask)
667 {
668         // this function currently only supports same size start and end
669         double boxsize[3];
670         RecursiveHullCheckTraceInfo_t rhc;
671
672         memset(&rhc, 0, sizeof(rhc));
673         memset(trace, 0, sizeof(trace_t));
674         rhc.trace = trace;
675         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
676         rhc.trace->fraction = 1;
677         rhc.trace->realfraction = 1;
678         rhc.trace->allsolid = true;
679         VectorSubtract(boxstartmaxs, boxstartmins, boxsize);
680         if (boxsize[0] < 3)
681                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
682         else if (model->brush.ismcbsp)
683         {
684                 if (boxsize[2] < 48) // pick the nearest of 40 or 56
685                         rhc.hull = &model->brushq1.hulls[2]; // 16x16x40
686                 else
687                         rhc.hull = &model->brushq1.hulls[1]; // 16x16x56
688         }
689         else if (model->brush.ishlbsp)
690         {
691                 // LordHavoc: this has to have a minor tolerance (the .1) because of
692                 // minor float precision errors from the box being transformed around
693                 if (boxsize[0] < 32.1)
694                 {
695                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
696                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
697                         else
698                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
699                 }
700                 else
701                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
702         }
703         else
704         {
705                 // LordHavoc: this has to have a minor tolerance (the .1) because of
706                 // minor float precision errors from the box being transformed around
707                 if (boxsize[0] < 32.1)
708                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
709                 else
710                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
711         }
712         VectorSubtract(boxstartmins, rhc.hull->clip_mins, rhc.start);
713         VectorSubtract(boxendmins, rhc.hull->clip_mins, rhc.end);
714         VectorSubtract(rhc.end, rhc.start, rhc.dist);
715 #if COLLISIONPARANOID >= 2
716         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]);
717         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
718         Con_Print("\n");
719 #else
720         if (DotProduct(rhc.dist, rhc.dist))
721                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
722         else
723                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
724 #endif
725 }
726
727 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)
728 {
729 #if 1
730         colbrushf_t cbox;
731         colplanef_t cbox_planes[6];
732         cbox.supercontents = boxsupercontents;
733         cbox.numplanes = 6;
734         cbox.numpoints = 0;
735         cbox.numtriangles = 0;
736         cbox.planes = cbox_planes;
737         cbox.points = NULL;
738         cbox.elements = NULL;
739         cbox.markframe = 0;
740         cbox.mins[0] = 0;
741         cbox.mins[1] = 0;
742         cbox.mins[2] = 0;
743         cbox.maxs[0] = 0;
744         cbox.maxs[1] = 0;
745         cbox.maxs[2] = 0;
746         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];
747         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];
748         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];
749         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];
750         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];
751         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];
752         memset(trace, 0, sizeof(trace_t));
753         trace->hitsupercontentsmask = hitsupercontentsmask;
754         trace->fraction = 1;
755         trace->realfraction = 1;
756         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
757 #else
758         RecursiveHullCheckTraceInfo_t rhc;
759         static hull_t box_hull;
760         static dclipnode_t box_clipnodes[6];
761         static mplane_t box_planes[6];
762         // fill in a default trace
763         memset(&rhc, 0, sizeof(rhc));
764         memset(trace, 0, sizeof(trace_t));
765         //To keep everything totally uniform, bounding boxes are turned into small
766         //BSP trees instead of being compared directly.
767         // create a temp hull from bounding box sizes
768         box_planes[0].dist = cmaxs[0] - mins[0];
769         box_planes[1].dist = cmins[0] - maxs[0];
770         box_planes[2].dist = cmaxs[1] - mins[1];
771         box_planes[3].dist = cmins[1] - maxs[1];
772         box_planes[4].dist = cmaxs[2] - mins[2];
773         box_planes[5].dist = cmins[2] - maxs[2];
774 #if COLLISIONPARANOID >= 3
775         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]);
776 #endif
777
778         if (box_hull.clipnodes == NULL)
779         {
780                 int i, side;
781
782                 //Set up the planes and clipnodes so that the six floats of a bounding box
783                 //can just be stored out and get a proper hull_t structure.
784
785                 box_hull.clipnodes = box_clipnodes;
786                 box_hull.planes = box_planes;
787                 box_hull.firstclipnode = 0;
788                 box_hull.lastclipnode = 5;
789
790                 for (i = 0;i < 6;i++)
791                 {
792                         box_clipnodes[i].planenum = i;
793
794                         side = i&1;
795
796                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
797                         if (i != 5)
798                                 box_clipnodes[i].children[side^1] = i + 1;
799                         else
800                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
801
802                         box_planes[i].type = i>>1;
803                         box_planes[i].normal[i>>1] = 1;
804                 }
805         }
806
807         // trace a line through the generated clipping hull
808         //rhc.boxsupercontents = boxsupercontents;
809         rhc.hull = &box_hull;
810         rhc.trace = trace;
811         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
812         rhc.trace->fraction = 1;
813         rhc.trace->realfraction = 1;
814         rhc.trace->allsolid = true;
815         VectorCopy(start, rhc.start);
816         VectorCopy(end, rhc.end);
817         VectorSubtract(rhc.end, rhc.start, rhc.dist);
818         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
819         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
820         if (rhc.trace->startsupercontents)
821                 rhc.trace->startsupercontents = boxsupercontents;
822 #endif
823 }
824
825 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
826 {
827         int side, distz = endz - startz;
828         float front, back;
829         float mid;
830
831 loc0:
832         if (!node->plane)
833                 return false;           // didn't hit anything
834
835         switch (node->plane->type)
836         {
837         case PLANE_X:
838                 node = node->children[x < node->plane->dist];
839                 goto loc0;
840         case PLANE_Y:
841                 node = node->children[y < node->plane->dist];
842                 goto loc0;
843         case PLANE_Z:
844                 side = startz < node->plane->dist;
845                 if ((endz < node->plane->dist) == side)
846                 {
847                         node = node->children[side];
848                         goto loc0;
849                 }
850                 // found an intersection
851                 mid = node->plane->dist;
852                 break;
853         default:
854                 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
855                 front += startz * node->plane->normal[2];
856                 back += endz * node->plane->normal[2];
857                 side = front < node->plane->dist;
858                 if ((back < node->plane->dist) == side)
859                 {
860                         node = node->children[side];
861                         goto loc0;
862                 }
863                 // found an intersection
864                 mid = startz + distz * (front - node->plane->dist) / (front - back);
865                 break;
866         }
867
868         // go down front side
869         if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
870                 return true;    // hit something
871         else
872         {
873                 // check for impact on this node
874                 if (node->numsurfaces)
875                 {
876                         int i, ds, dt;
877                         msurface_t *surface;
878
879                         surface = model->data_surfaces + node->firstsurface;
880                         for (i = 0;i < node->numsurfaces;i++, surface++)
881                         {
882                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo->samples)
883                                         continue;       // no lightmaps
884
885                                 ds = (int) (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];
886                                 dt = (int) (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];
887
888                                 if (ds >= 0 && ds < surface->lightmapinfo->extents[0] && dt >= 0 && dt < surface->lightmapinfo->extents[1])
889                                 {
890                                         qbyte *lightmap;
891                                         int lmwidth, lmheight, maps, line3, size3, dsfrac = ds & 15, dtfrac = dt & 15, scale = 0, r00 = 0, g00 = 0, b00 = 0, r01 = 0, g01 = 0, b01 = 0, r10 = 0, g10 = 0, b10 = 0, r11 = 0, g11 = 0, b11 = 0;
892                                         lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
893                                         lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
894                                         line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
895                                         size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
896
897                                         lightmap = surface->lightmapinfo->samples + ((dt>>4) * lmwidth + (ds>>4))*3; // LordHavoc: *3 for colored lighting
898
899                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
900                                         {
901                                                 scale = d_lightstylevalue[surface->lightmapinfo->styles[maps]];
902                                                 r00 += lightmap[      0] * scale;g00 += lightmap[      1] * scale;b00 += lightmap[      2] * scale;
903                                                 r01 += lightmap[      3] * scale;g01 += lightmap[      4] * scale;b01 += lightmap[      5] * scale;
904                                                 r10 += lightmap[line3+0] * scale;g10 += lightmap[line3+1] * scale;b10 += lightmap[line3+2] * scale;
905                                                 r11 += lightmap[line3+3] * scale;g11 += lightmap[line3+4] * scale;b11 += lightmap[line3+5] * scale;
906                                                 lightmap += size3;
907                                         }
908
909 /*
910 LordHavoc: here's the readable version of the interpolation
911 code, not quite as easy for the compiler to optimize...
912
913 dsfrac is the X position in the lightmap pixel, * 16
914 dtfrac is the Y position in the lightmap pixel, * 16
915 r00 is top left corner, r01 is top right corner
916 r10 is bottom left corner, r11 is bottom right corner
917 g and b are the same layout.
918 r0 and r1 are the top and bottom intermediate results
919
920 first we interpolate the top two points, to get the top
921 edge sample
922
923         r0 = (((r01-r00) * dsfrac) >> 4) + r00;
924         g0 = (((g01-g00) * dsfrac) >> 4) + g00;
925         b0 = (((b01-b00) * dsfrac) >> 4) + b00;
926
927 then we interpolate the bottom two points, to get the
928 bottom edge sample
929
930         r1 = (((r11-r10) * dsfrac) >> 4) + r10;
931         g1 = (((g11-g10) * dsfrac) >> 4) + g10;
932         b1 = (((b11-b10) * dsfrac) >> 4) + b10;
933
934 then we interpolate the top and bottom samples to get the
935 middle sample (the one which was requested)
936
937         r = (((r1-r0) * dtfrac) >> 4) + r0;
938         g = (((g1-g0) * dtfrac) >> 4) + g0;
939         b = (((b1-b0) * dtfrac) >> 4) + b0;
940 */
941
942                                         ambientcolor[0] += (float) ((((((((r11-r10) * dsfrac) >> 4) + r10)-((((r01-r00) * dsfrac) >> 4) + r00)) * dtfrac) >> 4) + ((((r01-r00) * dsfrac) >> 4) + r00)) * (1.0f / 32768.0f);
943                                         ambientcolor[1] += (float) ((((((((g11-g10) * dsfrac) >> 4) + g10)-((((g01-g00) * dsfrac) >> 4) + g00)) * dtfrac) >> 4) + ((((g01-g00) * dsfrac) >> 4) + g00)) * (1.0f / 32768.0f);
944                                         ambientcolor[2] += (float) ((((((((b11-b10) * dsfrac) >> 4) + b10)-((((b01-b00) * dsfrac) >> 4) + b00)) * dtfrac) >> 4) + ((((b01-b00) * dsfrac) >> 4) + b00)) * (1.0f / 32768.0f);
945                                         return true; // success
946                                 }
947                         }
948                 }
949
950                 // go down back side
951                 node = node->children[side ^ 1];
952                 startz = mid;
953                 distz = endz - startz;
954                 goto loc0;
955         }
956 }
957
958 void Mod_Q1BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
959 {
960         Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2], p[2] - 65536);
961 }
962
963 static void Mod_Q1BSP_DecompressVis(const qbyte *in, const qbyte *inend, qbyte *out, qbyte *outend)
964 {
965         int c;
966         qbyte *outstart = out;
967         while (out < outend)
968         {
969                 if (in == inend)
970                 {
971                         Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
972                         return;
973                 }
974                 c = *in++;
975                 if (c)
976                         *out++ = c;
977                 else
978                 {
979                         if (in == inend)
980                         {
981                                 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
982                                 return;
983                         }
984                         for (c = *in++;c > 0;c--)
985                         {
986                                 if (out == outend)
987                                 {
988                                         Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, out - outstart, outend - outstart);
989                                         return;
990                                 }
991                                 *out++ = 0;
992                         }
993                 }
994         }
995 }
996
997 /*
998 =============
999 R_Q1BSP_LoadSplitSky
1000
1001 A sky texture is 256*128, with the right side being a masked overlay
1002 ==============
1003 */
1004 void R_Q1BSP_LoadSplitSky (qbyte *src, int width, int height, int bytesperpixel)
1005 {
1006         int i, j;
1007         unsigned solidpixels[128*128], alphapixels[128*128];
1008
1009         // if sky isn't the right size, just use it as a solid layer
1010         if (width != 256 || height != 128)
1011         {
1012                 loadmodel->brush.solidskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_solidtexture", width, height, src, bytesperpixel == 4 ? TEXTYPE_RGBA : TEXTYPE_PALETTE, TEXF_PRECACHE, bytesperpixel == 1 ? palette_complete : NULL);
1013                 loadmodel->brush.alphaskytexture = NULL;;
1014                 return;
1015         }
1016
1017         if (bytesperpixel == 4)
1018         {
1019                 for (i = 0;i < 128;i++)
1020                 {
1021                         for (j = 0;j < 128;j++)
1022                         {
1023                                 solidpixels[(i*128) + j] = ((unsigned *)src)[i*256+j+128];
1024                                 alphapixels[(i*128) + j] = ((unsigned *)src)[i*256+j];
1025                         }
1026                 }
1027         }
1028         else
1029         {
1030                 // make an average value for the back to avoid
1031                 // a fringe on the top level
1032                 int p, r, g, b;
1033                 union
1034                 {
1035                         unsigned int i;
1036                         unsigned char b[4];
1037                 }
1038                 rgba;
1039                 r = g = b = 0;
1040                 for (i = 0;i < 128;i++)
1041                 {
1042                         for (j = 0;j < 128;j++)
1043                         {
1044                                 rgba.i = palette_complete[src[i*256 + j + 128]];
1045                                 r += rgba.b[0];
1046                                 g += rgba.b[1];
1047                                 b += rgba.b[2];
1048                         }
1049                 }
1050                 rgba.b[0] = r/(128*128);
1051                 rgba.b[1] = g/(128*128);
1052                 rgba.b[2] = b/(128*128);
1053                 rgba.b[3] = 0;
1054                 for (i = 0;i < 128;i++)
1055                 {
1056                         for (j = 0;j < 128;j++)
1057                         {
1058                                 solidpixels[(i*128) + j] = palette_complete[src[i*256 + j + 128]];
1059                                 alphapixels[(i*128) + j] = (p = src[i*256 + j]) ? palette_complete[p] : rgba.i;
1060                         }
1061                 }
1062         }
1063
1064         loadmodel->brush.solidskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_solidtexture", 128, 128, (qbyte *) solidpixels, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
1065         loadmodel->brush.alphaskytexture = R_LoadTexture2D(loadmodel->texturepool, "sky_alphatexture", 128, 128, (qbyte *) alphapixels, TEXTYPE_RGBA, TEXF_ALPHA | TEXF_PRECACHE, NULL);
1066 }
1067
1068 static void Mod_Q1BSP_LoadTextures(lump_t *l)
1069 {
1070         int i, j, k, num, max, altmax, mtwidth, mtheight, *dofs, incomplete;
1071         miptex_t *dmiptex;
1072         texture_t *tx, *tx2, *anims[10], *altanims[10];
1073         dmiptexlump_t *m;
1074         qbyte *data, *mtdata;
1075         char name[256];
1076
1077         loadmodel->data_textures = NULL;
1078
1079         // add two slots for notexture walls and notexture liquids
1080         if (l->filelen)
1081         {
1082                 m = (dmiptexlump_t *)(mod_base + l->fileofs);
1083                 m->nummiptex = LittleLong (m->nummiptex);
1084                 loadmodel->num_textures = m->nummiptex + 2;
1085         }
1086         else
1087         {
1088                 m = NULL;
1089                 loadmodel->num_textures = 2;
1090         }
1091
1092         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1093
1094         // fill out all slots with notexture
1095         for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1096         {
1097                 strcpy(tx->name, "NO TEXTURE FOUND");
1098                 tx->width = 16;
1099                 tx->height = 16;
1100                 tx->skin.base = r_texture_notexture;
1101                 tx->basematerialflags = 0;
1102                 if (i == loadmodel->num_textures - 1)
1103                 {
1104                         tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1105                         tx->supercontents = SUPERCONTENTS_WATER;
1106                 }
1107                 else
1108                 {
1109                         tx->basematerialflags |= MATERIALFLAG_WALL;
1110                         tx->supercontents = SUPERCONTENTS_SOLID;
1111                 }
1112                 tx->currentframe = tx;
1113         }
1114
1115         if (!m)
1116                 return;
1117
1118         // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1119         dofs = m->dataofs;
1120         // LordHavoc: mostly rewritten map texture loader
1121         for (i = 0;i < m->nummiptex;i++)
1122         {
1123                 dofs[i] = LittleLong(dofs[i]);
1124                 if (dofs[i] == -1 || r_nosurftextures.integer)
1125                         continue;
1126                 dmiptex = (miptex_t *)((qbyte *)m + dofs[i]);
1127
1128                 // make sure name is no more than 15 characters
1129                 for (j = 0;dmiptex->name[j] && j < 15;j++)
1130                         name[j] = dmiptex->name[j];
1131                 name[j] = 0;
1132
1133                 mtwidth = LittleLong(dmiptex->width);
1134                 mtheight = LittleLong(dmiptex->height);
1135                 mtdata = NULL;
1136                 j = LittleLong(dmiptex->offsets[0]);
1137                 if (j)
1138                 {
1139                         // texture included
1140                         if (j < 40 || j + mtwidth * mtheight > l->filelen)
1141                         {
1142                                 Con_Printf("Texture \"%s\" in \"%s\"is corrupt or incomplete\n", dmiptex->name, loadmodel->name);
1143                                 continue;
1144                         }
1145                         mtdata = (qbyte *)dmiptex + j;
1146                 }
1147
1148                 if ((mtwidth & 15) || (mtheight & 15))
1149                         Con_Printf("warning: texture \"%s\" in \"%s\" is not 16 aligned\n", dmiptex->name, loadmodel->name);
1150
1151                 // LordHavoc: force all names to lowercase
1152                 for (j = 0;name[j];j++)
1153                         if (name[j] >= 'A' && name[j] <= 'Z')
1154                                 name[j] += 'a' - 'A';
1155
1156                 tx = loadmodel->data_textures + i;
1157                 strcpy(tx->name, name);
1158                 tx->width = mtwidth;
1159                 tx->height = mtheight;
1160
1161                 if (!tx->name[0])
1162                 {
1163                         sprintf(tx->name, "unnamed%i", i);
1164                         Con_Printf("warning: unnamed texture in %s, renaming to %s\n", loadmodel->name, tx->name);
1165                 }
1166
1167                 // LordHavoc: HL sky textures are entirely different than quake
1168                 if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == 256 && mtheight == 128)
1169                 {
1170                         if (loadmodel->isworldmodel)
1171                         {
1172                                 data = loadimagepixels(tx->name, false, 0, 0);
1173                                 if (data)
1174                                 {
1175                                         R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1176                                         Mem_Free(data);
1177                                 }
1178                                 else if (mtdata != NULL)
1179                                         R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1180                         }
1181                 }
1182                 else
1183                 {
1184                         if (!Mod_LoadSkinFrame(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, true))
1185                         {
1186                                 // did not find external texture, load it from the bsp or wad3
1187                                 if (loadmodel->brush.ishlbsp)
1188                                 {
1189                                         // internal texture overrides wad
1190                                         qbyte *pixels, *freepixels, *fogpixels;
1191                                         pixels = freepixels = NULL;
1192                                         if (mtdata)
1193                                                 pixels = W_ConvertWAD3Texture(dmiptex);
1194                                         if (pixels == NULL)
1195                                                 pixels = freepixels = W_GetTexture(tx->name);
1196                                         if (pixels != NULL)
1197                                         {
1198                                                 tx->width = image_width;
1199                                                 tx->height = image_height;
1200                                                 tx->skin.base = tx->skin.merged = R_LoadTexture2D(loadmodel->texturepool, tx->name, image_width, image_height, pixels, TEXTYPE_RGBA, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, NULL);
1201                                                 if (Image_CheckAlpha(pixels, image_width * image_height, true))
1202                                                 {
1203                                                         fogpixels = (qbyte *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1204                                                         for (j = 0;j < image_width * image_height * 4;j += 4)
1205                                                         {
1206                                                                 fogpixels[j + 0] = 255;
1207                                                                 fogpixels[j + 1] = 255;
1208                                                                 fogpixels[j + 2] = 255;
1209                                                                 fogpixels[j + 3] = pixels[j + 3];
1210                                                         }
1211                                                         tx->skin.fog = R_LoadTexture2D(loadmodel->texturepool, tx->name, image_width, image_height, pixels, TEXTYPE_RGBA, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, NULL);
1212                                                         Mem_Free(fogpixels);
1213                                                 }
1214                                         }
1215                                         if (freepixels)
1216                                                 Mem_Free(freepixels);
1217                                 }
1218                                 else if (mtdata) // texture included
1219                                         Mod_LoadSkinFrame_Internal(&tx->skin, tx->name, TEXF_MIPMAP | TEXF_PRECACHE | TEXF_PICMIP, false, tx->name[0] != '*' && r_fullbrights.integer, mtdata, tx->width, tx->height);
1220                         }
1221                 }
1222                 if (tx->skin.base == NULL)
1223                 {
1224                         // no texture found
1225                         tx->width = 16;
1226                         tx->height = 16;
1227                         tx->skin.base = r_texture_notexture;
1228                 }
1229
1230                 tx->basematerialflags = 0;
1231                 if (tx->name[0] == '*')
1232                 {
1233                         // turb does not block movement
1234                         tx->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES;
1235                         // LordHavoc: some turbulent textures should be fullbright and solid
1236                         if (!strncmp(tx->name,"*lava",5)
1237                          || !strncmp(tx->name,"*teleport",9)
1238                          || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1239                                 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1240                         else
1241                                 tx->basematerialflags |= MATERIALFLAG_WATERALPHA;
1242                         if (!strncmp(tx->name, "*lava", 5))
1243                                 tx->supercontents = SUPERCONTENTS_LAVA;
1244                         else if (!strncmp(tx->name, "*slime", 6))
1245                                 tx->supercontents = SUPERCONTENTS_SLIME;
1246                         else
1247                                 tx->supercontents = SUPERCONTENTS_WATER;
1248                 }
1249                 else if (tx->name[0] == 's' && tx->name[1] == 'k' && tx->name[2] == 'y')
1250                 {
1251                         tx->supercontents = SUPERCONTENTS_SKY;
1252                         tx->basematerialflags |= MATERIALFLAG_SKY;
1253                 }
1254                 else
1255                 {
1256                         tx->supercontents = SUPERCONTENTS_SOLID;
1257                         tx->basematerialflags |= MATERIALFLAG_WALL;
1258                 }
1259                 if (tx->skin.fog)
1260                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
1261
1262                 // start out with no animation
1263                 tx->currentframe = tx;
1264         }
1265
1266         // sequence the animations
1267         for (i = 0;i < m->nummiptex;i++)
1268         {
1269                 tx = loadmodel->data_textures + i;
1270                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1271                         continue;
1272                 if (tx->anim_total[0] || tx->anim_total[1])
1273                         continue;       // already sequenced
1274
1275                 // find the number of frames in the animation
1276                 memset(anims, 0, sizeof(anims));
1277                 memset(altanims, 0, sizeof(altanims));
1278
1279                 for (j = i;j < m->nummiptex;j++)
1280                 {
1281                         tx2 = loadmodel->data_textures + j;
1282                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1283                                 continue;
1284
1285                         num = tx2->name[1];
1286                         if (num >= '0' && num <= '9')
1287                                 anims[num - '0'] = tx2;
1288                         else if (num >= 'a' && num <= 'j')
1289                                 altanims[num - 'a'] = tx2;
1290                         else
1291                                 Con_Printf("Bad animating texture %s\n", tx->name);
1292                 }
1293
1294                 max = altmax = 0;
1295                 for (j = 0;j < 10;j++)
1296                 {
1297                         if (anims[j])
1298                                 max = j + 1;
1299                         if (altanims[j])
1300                                 altmax = j + 1;
1301                 }
1302                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1303
1304                 incomplete = false;
1305                 for (j = 0;j < max;j++)
1306                 {
1307                         if (!anims[j])
1308                         {
1309                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1310                                 incomplete = true;
1311                         }
1312                 }
1313                 for (j = 0;j < altmax;j++)
1314                 {
1315                         if (!altanims[j])
1316                         {
1317                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1318                                 incomplete = true;
1319                         }
1320                 }
1321                 if (incomplete)
1322                         continue;
1323
1324                 if (altmax < 1)
1325                 {
1326                         // if there is no alternate animation, duplicate the primary
1327                         // animation into the alternate
1328                         altmax = max;
1329                         for (k = 0;k < 10;k++)
1330                                 altanims[k] = anims[k];
1331                 }
1332
1333                 // link together the primary animation
1334                 for (j = 0;j < max;j++)
1335                 {
1336                         tx2 = anims[j];
1337                         tx2->animated = true;
1338                         tx2->anim_total[0] = max;
1339                         tx2->anim_total[1] = altmax;
1340                         for (k = 0;k < 10;k++)
1341                         {
1342                                 tx2->anim_frames[0][k] = anims[k];
1343                                 tx2->anim_frames[1][k] = altanims[k];
1344                         }
1345                 }
1346
1347                 // if there really is an alternate anim...
1348                 if (anims[0] != altanims[0])
1349                 {
1350                         // link together the alternate animation
1351                         for (j = 0;j < altmax;j++)
1352                         {
1353                                 tx2 = altanims[j];
1354                                 tx2->animated = true;
1355                                 // the primary/alternate are reversed here
1356                                 tx2->anim_total[0] = altmax;
1357                                 tx2->anim_total[1] = max;
1358                                 for (k = 0;k < 10;k++)
1359                                 {
1360                                         tx2->anim_frames[0][k] = altanims[k];
1361                                         tx2->anim_frames[1][k] = anims[k];
1362                                 }
1363                         }
1364                 }
1365         }
1366 }
1367
1368 static void Mod_Q1BSP_LoadLighting(lump_t *l)
1369 {
1370         int i;
1371         qbyte *in, *out, *data, d;
1372         char litfilename[1024];
1373         loadmodel->brushq1.lightdata = NULL;
1374         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
1375         {
1376                 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1377                 for (i=0; i<l->filelen; i++)
1378                         loadmodel->brushq1.lightdata[i] = mod_base[l->fileofs+i] >>= 1;
1379         }
1380         else if (loadmodel->brush.ismcbsp)
1381         {
1382                 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1383                 memcpy(loadmodel->brushq1.lightdata, mod_base + l->fileofs, l->filelen);
1384         }
1385         else // LordHavoc: bsp version 29 (normal white lighting)
1386         {
1387                 // LordHavoc: hope is not lost yet, check for a .lit file to load
1388                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
1389                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
1390                 strlcat (litfilename, ".lit", sizeof (litfilename));
1391                 data = (qbyte*) FS_LoadFile(litfilename, tempmempool, false);
1392                 if (data)
1393                 {
1394                         if (fs_filesize == (fs_offset_t)(8 + l->filelen * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
1395                         {
1396                                 i = LittleLong(((int *)data)[1]);
1397                                 if (i == 1)
1398                                 {
1399                                         Con_DPrintf("loaded %s\n", litfilename);
1400                                         loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, fs_filesize - 8);
1401                                         memcpy(loadmodel->brushq1.lightdata, data + 8, fs_filesize - 8);
1402                                         Mem_Free(data);
1403                                         return;
1404                                 }
1405                                 else
1406                                 {
1407                                         Con_Printf("Unknown .lit file version (%d)\n", i);
1408                                         Mem_Free(data);
1409                                 }
1410                         }
1411                         else
1412                         {
1413                                 if (fs_filesize == 8)
1414                                         Con_Print("Empty .lit file, ignoring\n");
1415                                 else
1416                                         Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", fs_filesize, 8 + l->filelen * 3);
1417                                 Mem_Free(data);
1418                         }
1419                 }
1420                 // LordHavoc: oh well, expand the white lighting data
1421                 if (!l->filelen)
1422                         return;
1423                 loadmodel->brushq1.lightdata = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen*3);
1424                 in = loadmodel->brushq1.lightdata + l->filelen*2; // place the file at the end, so it will not be overwritten until the very last write
1425                 out = loadmodel->brushq1.lightdata;
1426                 memcpy(in, mod_base + l->fileofs, l->filelen);
1427                 for (i = 0;i < l->filelen;i++)
1428                 {
1429                         d = *in++;
1430                         *out++ = d;
1431                         *out++ = d;
1432                         *out++ = d;
1433                 }
1434         }
1435 }
1436
1437 static void Mod_Q1BSP_LoadLightList(void)
1438 {
1439         int a, n, numlights;
1440         char tempchar, *s, *t, *lightsstring, lightsfilename[1024];
1441         mlight_t *e;
1442
1443         strlcpy (lightsfilename, loadmodel->name, sizeof (lightsfilename));
1444         FS_StripExtension (lightsfilename, lightsfilename, sizeof(lightsfilename));
1445         strlcat (lightsfilename, ".lights", sizeof (lightsfilename));
1446         s = lightsstring = (char *) FS_LoadFile(lightsfilename, tempmempool, false);
1447         if (s)
1448         {
1449                 numlights = 0;
1450                 while (*s)
1451                 {
1452                         while (*s && *s != '\n' && *s != '\r')
1453                                 s++;
1454                         if (!*s)
1455                         {
1456                                 Mem_Free(lightsstring);
1457                                 Con_Printf("lights file must end with a newline\n");
1458                                 return;
1459                         }
1460                         s++;
1461                         numlights++;
1462                 }
1463                 loadmodel->brushq1.lights = (mlight_t *)Mem_Alloc(loadmodel->mempool, numlights * sizeof(mlight_t));
1464                 s = lightsstring;
1465                 n = 0;
1466                 while (*s && n < numlights)
1467                 {
1468                         t = s;
1469                         while (*s && *s != '\n' && *s != '\r')
1470                                 s++;
1471                         if (!*s)
1472                         {
1473                                 Con_Printf("misparsed lights file!\n");
1474                                 break;
1475                         }
1476                         e = loadmodel->brushq1.lights + n;
1477                         tempchar = *s;
1478                         *s = 0;
1479                         a = sscanf(t, "%f %f %f %f %f %f %f %f %f %f %f %f %f %d", &e->origin[0], &e->origin[1], &e->origin[2], &e->falloff, &e->light[0], &e->light[1], &e->light[2], &e->subtract, &e->spotdir[0], &e->spotdir[1], &e->spotdir[2], &e->spotcone, &e->distbias, &e->style);
1480                         *s = tempchar;
1481                         if (a != 14)
1482                         {
1483                                 Con_Printf("invalid lights file, found %d parameters on line %i, should be 14 parameters (origin[0] origin[1] origin[2] falloff light[0] light[1] light[2] subtract spotdir[0] spotdir[1] spotdir[2] spotcone distancebias style)\n", a, n + 1);
1484                                 break;
1485                         }
1486                         if (*s == '\r')
1487                                 s++;
1488                         if (*s == '\n')
1489                                 s++;
1490                         n++;
1491                 }
1492                 if (*s)
1493                         Con_Printf("misparsed lights file!\n");
1494                 loadmodel->brushq1.numlights = numlights;
1495                 Mem_Free(lightsstring);
1496         }
1497 }
1498
1499 static void Mod_Q1BSP_LoadVisibility(lump_t *l)
1500 {
1501         loadmodel->brushq1.num_compressedpvs = 0;
1502         loadmodel->brushq1.data_compressedpvs = NULL;
1503         if (!l->filelen)
1504                 return;
1505         loadmodel->brushq1.num_compressedpvs = l->filelen;
1506         loadmodel->brushq1.data_compressedpvs = (qbyte *)Mem_Alloc(loadmodel->mempool, l->filelen);
1507         memcpy(loadmodel->brushq1.data_compressedpvs, mod_base + l->fileofs, l->filelen);
1508 }
1509
1510 // used only for HalfLife maps
1511 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
1512 {
1513         char key[128], value[4096];
1514         char wadname[128];
1515         int i, j, k;
1516         if (!data)
1517                 return;
1518         if (!COM_ParseToken(&data, false))
1519                 return; // error
1520         if (com_token[0] != '{')
1521                 return; // error
1522         while (1)
1523         {
1524                 if (!COM_ParseToken(&data, false))
1525                         return; // error
1526                 if (com_token[0] == '}')
1527                         break; // end of worldspawn
1528                 if (com_token[0] == '_')
1529                         strcpy(key, com_token + 1);
1530                 else
1531                         strcpy(key, com_token);
1532                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
1533                         key[strlen(key)-1] = 0;
1534                 if (!COM_ParseToken(&data, false))
1535                         return; // error
1536                 strcpy(value, com_token);
1537                 if (!strcmp("wad", key)) // for HalfLife maps
1538                 {
1539                         if (loadmodel->brush.ishlbsp)
1540                         {
1541                                 j = 0;
1542                                 for (i = 0;i < 4096;i++)
1543                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
1544                                                 break;
1545                                 if (value[i])
1546                                 {
1547                                         for (;i < 4096;i++)
1548                                         {
1549                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
1550                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
1551                                                         j = i+1;
1552                                                 else if (value[i] == ';' || value[i] == 0)
1553                                                 {
1554                                                         k = value[i];
1555                                                         value[i] = 0;
1556                                                         strcpy(wadname, "textures/");
1557                                                         strcat(wadname, &value[j]);
1558                                                         W_LoadTextureWadFile(wadname, false);
1559                                                         j = i+1;
1560                                                         if (!k)
1561                                                                 break;
1562                                                 }
1563                                         }
1564                                 }
1565                         }
1566                 }
1567         }
1568 }
1569
1570 static void Mod_Q1BSP_LoadEntities(lump_t *l)
1571 {
1572         loadmodel->brush.entities = NULL;
1573         if (!l->filelen)
1574                 return;
1575         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen);
1576         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
1577         if (loadmodel->brush.ishlbsp)
1578                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
1579 }
1580
1581
1582 static void Mod_Q1BSP_LoadVertexes(lump_t *l)
1583 {
1584         dvertex_t       *in;
1585         mvertex_t       *out;
1586         int                     i, count;
1587
1588         in = (dvertex_t *)(mod_base + l->fileofs);
1589         if (l->filelen % sizeof(*in))
1590                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
1591         count = l->filelen / sizeof(*in);
1592         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
1593
1594         loadmodel->brushq1.vertexes = out;
1595         loadmodel->brushq1.numvertexes = count;
1596
1597         for ( i=0 ; i<count ; i++, in++, out++)
1598         {
1599                 out->position[0] = LittleFloat(in->point[0]);
1600                 out->position[1] = LittleFloat(in->point[1]);
1601                 out->position[2] = LittleFloat(in->point[2]);
1602         }
1603 }
1604
1605 // The following two functions should be removed and MSG_* or SZ_* function sets adjusted so they
1606 // can be used for this
1607 // REMOVEME
1608 int SB_ReadInt (qbyte **buffer)
1609 {
1610         int     i;
1611         i = ((*buffer)[0]) + 256*((*buffer)[1]) + 65536*((*buffer)[2]) + 16777216*((*buffer)[3]);
1612         (*buffer) += 4;
1613         return i;
1614 }
1615
1616 // REMOVEME
1617 float SB_ReadFloat (qbyte **buffer)
1618 {
1619         union
1620         {
1621                 int             i;
1622                 float   f;
1623         } u;
1624
1625         u.i = SB_ReadInt (buffer);
1626         return u.f;
1627 }
1628
1629 static void Mod_Q1BSP_LoadSubmodels(lump_t *l, hullinfo_t *hullinfo)
1630 {
1631         qbyte           *index;
1632         dmodel_t        *out;
1633         int                     i, j, count;
1634
1635         index = (qbyte *)(mod_base + l->fileofs);
1636         if (l->filelen % (48+4*hullinfo->filehulls))
1637                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
1638
1639         count = l->filelen / (48+4*hullinfo->filehulls);
1640         out = (dmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
1641
1642         loadmodel->brushq1.submodels = out;
1643         loadmodel->brush.numsubmodels = count;
1644
1645         for (i = 0; i < count; i++, out++)
1646         {
1647         // spread out the mins / maxs by a pixel
1648                 out->mins[0] = SB_ReadFloat (&index) - 1;
1649                 out->mins[1] = SB_ReadFloat (&index) - 1;
1650                 out->mins[2] = SB_ReadFloat (&index) - 1;
1651                 out->maxs[0] = SB_ReadFloat (&index) + 1;
1652                 out->maxs[1] = SB_ReadFloat (&index) + 1;
1653                 out->maxs[2] = SB_ReadFloat (&index) + 1;
1654                 out->origin[0] = SB_ReadFloat (&index);
1655                 out->origin[1] = SB_ReadFloat (&index);
1656                 out->origin[2] = SB_ReadFloat (&index);
1657                 for (j = 0; j < hullinfo->filehulls; j++)
1658                         out->headnode[j] = SB_ReadInt (&index);
1659                 out->visleafs = SB_ReadInt (&index);
1660                 out->firstface = SB_ReadInt (&index);
1661                 out->numfaces = SB_ReadInt (&index);
1662         }
1663 }
1664
1665 static void Mod_Q1BSP_LoadEdges(lump_t *l)
1666 {
1667         dedge_t *in;
1668         medge_t *out;
1669         int     i, count;
1670
1671         in = (dedge_t *)(mod_base + l->fileofs);
1672         if (l->filelen % sizeof(*in))
1673                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
1674         count = l->filelen / sizeof(*in);
1675         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1676
1677         loadmodel->brushq1.edges = out;
1678         loadmodel->brushq1.numedges = count;
1679
1680         for ( i=0 ; i<count ; i++, in++, out++)
1681         {
1682                 out->v[0] = (unsigned short)LittleShort(in->v[0]);
1683                 out->v[1] = (unsigned short)LittleShort(in->v[1]);
1684         }
1685 }
1686
1687 static void Mod_Q1BSP_LoadTexinfo(lump_t *l)
1688 {
1689         texinfo_t *in;
1690         mtexinfo_t *out;
1691         int i, j, k, count, miptex;
1692
1693         in = (texinfo_t *)(mod_base + l->fileofs);
1694         if (l->filelen % sizeof(*in))
1695                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
1696         count = l->filelen / sizeof(*in);
1697         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
1698
1699         loadmodel->brushq1.texinfo = out;
1700         loadmodel->brushq1.numtexinfo = count;
1701
1702         for (i = 0;i < count;i++, in++, out++)
1703         {
1704                 for (k = 0;k < 2;k++)
1705                         for (j = 0;j < 4;j++)
1706                                 out->vecs[k][j] = LittleFloat(in->vecs[k][j]);
1707
1708                 miptex = LittleLong(in->miptex);
1709                 out->flags = LittleLong(in->flags);
1710
1711                 out->texture = NULL;
1712                 if (loadmodel->data_textures)
1713                 {
1714                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
1715                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
1716                         else
1717                                 out->texture = loadmodel->data_textures + miptex;
1718                 }
1719                 if (out->flags & TEX_SPECIAL)
1720                 {
1721                         // if texture chosen is NULL or the shader needs a lightmap,
1722                         // force to notexture water shader
1723                         if (out->texture == NULL || out->texture->basematerialflags & MATERIALFLAG_WALL)
1724                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
1725                 }
1726                 else
1727                 {
1728                         // if texture chosen is NULL, force to notexture
1729                         if (out->texture == NULL)
1730                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
1731                 }
1732         }
1733 }
1734
1735 #if 0
1736 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
1737 {
1738         int             i, j;
1739         float   *v;
1740
1741         mins[0] = mins[1] = mins[2] = 9999;
1742         maxs[0] = maxs[1] = maxs[2] = -9999;
1743         v = verts;
1744         for (i = 0;i < numverts;i++)
1745         {
1746                 for (j = 0;j < 3;j++, v++)
1747                 {
1748                         if (*v < mins[j])
1749                                 mins[j] = *v;
1750                         if (*v > maxs[j])
1751                                 maxs[j] = *v;
1752                 }
1753         }
1754 }
1755
1756 #define MAX_SUBDIVPOLYTRIANGLES 4096
1757 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
1758
1759 static int subdivpolyverts, subdivpolytriangles;
1760 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
1761 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
1762
1763 static int subdivpolylookupvert(vec3_t v)
1764 {
1765         int i;
1766         for (i = 0;i < subdivpolyverts;i++)
1767                 if (subdivpolyvert[i][0] == v[0]
1768                  && subdivpolyvert[i][1] == v[1]
1769                  && subdivpolyvert[i][2] == v[2])
1770                         return i;
1771         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
1772                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
1773         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
1774         return subdivpolyverts++;
1775 }
1776
1777 static void SubdividePolygon(int numverts, float *verts)
1778 {
1779         int             i, i1, i2, i3, f, b, c, p;
1780         vec3_t  mins, maxs, front[256], back[256];
1781         float   m, *pv, *cv, dist[256], frac;
1782
1783         if (numverts > 250)
1784                 Host_Error("SubdividePolygon: ran out of verts in buffer");
1785
1786         BoundPoly(numverts, verts, mins, maxs);
1787
1788         for (i = 0;i < 3;i++)
1789         {
1790                 m = (mins[i] + maxs[i]) * 0.5;
1791                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
1792                 if (maxs[i] - m < 8)
1793                         continue;
1794                 if (m - mins[i] < 8)
1795                         continue;
1796
1797                 // cut it
1798                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
1799                         dist[c] = cv[i] - m;
1800
1801                 f = b = 0;
1802                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
1803                 {
1804                         if (dist[p] >= 0)
1805                         {
1806                                 VectorCopy(pv, front[f]);
1807                                 f++;
1808                         }
1809                         if (dist[p] <= 0)
1810                         {
1811                                 VectorCopy(pv, back[b]);
1812                                 b++;
1813                         }
1814                         if (dist[p] == 0 || dist[c] == 0)
1815                                 continue;
1816                         if ((dist[p] > 0) != (dist[c] > 0) )
1817                         {
1818                                 // clip point
1819                                 frac = dist[p] / (dist[p] - dist[c]);
1820                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
1821                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
1822                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
1823                                 f++;
1824                                 b++;
1825                         }
1826                 }
1827
1828                 SubdividePolygon(f, front[0]);
1829                 SubdividePolygon(b, back[0]);
1830                 return;
1831         }
1832
1833         i1 = subdivpolylookupvert(verts);
1834         i2 = subdivpolylookupvert(verts + 3);
1835         for (i = 2;i < numverts;i++)
1836         {
1837                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
1838                 {
1839                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
1840                         return;
1841                 }
1842
1843                 i3 = subdivpolylookupvert(verts + i * 3);
1844                 subdivpolyindex[subdivpolytriangles][0] = i1;
1845                 subdivpolyindex[subdivpolytriangles][1] = i2;
1846                 subdivpolyindex[subdivpolytriangles][2] = i3;
1847                 i2 = i3;
1848                 subdivpolytriangles++;
1849         }
1850 }
1851
1852 //Breaks a polygon up along axial 64 unit
1853 //boundaries so that turbulent and sky warps
1854 //can be done reasonably.
1855 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
1856 {
1857         int i, j;
1858         surfvertex_t *v;
1859         surfmesh_t *mesh;
1860
1861         subdivpolytriangles = 0;
1862         subdivpolyverts = 0;
1863         SubdividePolygon(surface->num_vertices, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex));
1864         if (subdivpolytriangles < 1)
1865                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?\n");
1866
1867         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
1868         mesh->num_vertices = subdivpolyverts;
1869         mesh->num_triangles = subdivpolytriangles;
1870         mesh->vertex = (surfvertex_t *)(mesh + 1);
1871         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
1872         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
1873
1874         for (i = 0;i < mesh->num_triangles;i++)
1875                 for (j = 0;j < 3;j++)
1876                         mesh->index[i*3+j] = subdivpolyindex[i][j];
1877
1878         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
1879         {
1880                 VectorCopy(subdivpolyvert[i], v->v);
1881                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
1882                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
1883         }
1884 }
1885 #endif
1886
1887 static void Mod_Q1BSP_LoadFaces(lump_t *l)
1888 {
1889         dface_t *in;
1890         msurface_t *surface;
1891         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris;
1892         float texmins[2], texmaxs[2], val;
1893
1894         in = (dface_t *)(mod_base + l->fileofs);
1895         if (l->filelen % sizeof(*in))
1896                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
1897         count = l->filelen / sizeof(*in);
1898         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
1899         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
1900
1901         loadmodel->num_surfaces = count;
1902
1903         totalverts = 0;
1904         totaltris = 0;
1905         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs);surfacenum < count;surfacenum++, in++)
1906         {
1907                 numedges = LittleShort(in->numedges);
1908                 totalverts += numedges;
1909                 totaltris += numedges - 2;
1910         }
1911
1912         // TODO: split up into multiple meshes as needed to avoid exceeding 65536
1913         // vertex limit
1914         loadmodel->nummeshes = 1;
1915         loadmodel->meshlist = (surfmesh_t **)Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *));
1916         loadmodel->meshlist[0] = Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
1917
1918         totalverts = 0;
1919         totaltris = 0;
1920         for (surfacenum = 0, in = (dface_t *)(mod_base + l->fileofs), surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, in++, surface++)
1921         {
1922                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
1923
1924                 // FIXME: validate edges, texinfo, etc?
1925                 firstedge = LittleLong(in->firstedge);
1926                 numedges = LittleShort(in->numedges);
1927                 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)
1928                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)\n", firstedge, numedges, loadmodel->brushq1.numsurfedges);
1929                 i = LittleShort(in->texinfo);
1930                 if ((unsigned int) i >= (unsigned int) loadmodel->brushq1.numtexinfo)
1931                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)\n", i, loadmodel->brushq1.numtexinfo);
1932                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + i;
1933                 surface->texture = surface->lightmapinfo->texinfo->texture;
1934
1935                 planenum = LittleShort(in->planenum);
1936                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
1937                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)\n", planenum, loadmodel->brush.num_planes);
1938
1939                 //surface->flags = surface->texture->flags;
1940                 //if (LittleShort(in->side))
1941                 //      surface->flags |= SURF_PLANEBACK;
1942                 //surface->plane = loadmodel->brush.data_planes + planenum;
1943
1944                 surface->groupmesh = loadmodel->meshlist[0];
1945                 surface->num_firstvertex = totalverts;
1946                 surface->num_vertices = numedges;
1947                 surface->num_firsttriangle = totaltris;
1948                 surface->num_triangles = numedges - 2;
1949                 totalverts += numedges;
1950                 totaltris += numedges - 2;
1951
1952                 // convert edges back to a normal polygon
1953                 for (i = 0;i < surface->num_vertices;i++)
1954                 {
1955                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
1956                         float s, t;
1957                         if (lindex > 0)
1958                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
1959                         else
1960                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
1961                         s = DotProduct(((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
1962                         t = DotProduct(((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
1963                         (surface->groupmesh->data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
1964                         (surface->groupmesh->data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
1965                         (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
1966                         (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
1967                         (surface->groupmesh->data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
1968                 }
1969
1970                 for (i = 0;i < surface->num_triangles;i++)
1971                 {
1972                         (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
1973                         (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
1974                         (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
1975                 }
1976
1977                 // compile additional data about the surface geometry
1978                 Mod_BuildTextureVectorsAndNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, surface->groupmesh->data_vertex3f, surface->groupmesh->data_texcoordtexture2f, (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle), surface->groupmesh->data_svector3f, surface->groupmesh->data_tvector3f, surface->groupmesh->data_normal3f, true);
1979                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex));
1980
1981                 // generate surface extents information
1982                 texmins[0] = texmaxs[0] = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
1983                 texmins[1] = texmaxs[1] = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
1984                 for (i = 1;i < surface->num_vertices;i++)
1985                 {
1986                         for (j = 0;j < 2;j++)
1987                         {
1988                                 val = DotProduct((surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
1989                                 texmins[j] = min(texmins[j], val);
1990                                 texmaxs[j] = max(texmaxs[j], val);
1991                         }
1992                 }
1993                 for (i = 0;i < 2;i++)
1994                 {
1995                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
1996                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
1997                 }
1998
1999                 smax = surface->lightmapinfo->extents[0] >> 4;
2000                 tmax = surface->lightmapinfo->extents[1] >> 4;
2001                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2002                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2003
2004                 // lighting info
2005                 for (i = 0;i < MAXLIGHTMAPS;i++)
2006                         surface->lightmapinfo->styles[i] = in->styles[i];
2007                 // force lightmap upload on first time seeing the surface
2008                 surface->cached_dlight = true;
2009                 surface->lightmapinfo->lightmaptexturestride = 0;
2010                 surface->lightmaptexture = NULL;
2011                 i = LittleLong(in->lightofs);
2012                 if (i == -1)
2013                 {
2014                         surface->lightmapinfo->samples = NULL;
2015                         // give non-lightmapped water a 1x white lightmap
2016                         if ((surface->texture->basematerialflags & MATERIALFLAG_WATER) && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2017                         {
2018                                 surface->lightmapinfo->samples = (qbyte *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2019                                 surface->lightmapinfo->styles[0] = 0;
2020                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2021                         }
2022                 }
2023                 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2024                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + i;
2025                 else // LordHavoc: white lighting (bsp version 29)
2026                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (i * 3);
2027
2028                 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2029                 {
2030                         int i, iu, iv;
2031                         float u, v, ubase, vbase, uscale, vscale;
2032
2033                         if (ssize > 256 || tsize > 256)
2034                                 Host_Error("Bad surface extents");
2035                         // stainmap for permanent marks on walls
2036                         surface->lightmapinfo->stainsamples = (qbyte *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2037                         // clear to white
2038                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
2039
2040                         if (r_miplightmaps.integer)
2041                         {
2042                                 surface->lightmapinfo->lightmaptexturestride = ssize;
2043                                 surface->lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, NULL, surface->lightmapinfo->lightmaptexturestride, tsize, NULL, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, TEXF_MIPMAP | TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
2044                         }
2045                         else
2046                         {
2047                                 surface->lightmapinfo->lightmaptexturestride = R_CompatibleFragmentWidth(ssize, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, 0);
2048                                 surface->lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, NULL, surface->lightmapinfo->lightmaptexturestride, tsize, NULL, loadmodel->brushq1.lightmaprgba ? TEXTYPE_RGBA : TEXTYPE_RGB, TEXF_FRAGMENT | TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
2049                         }
2050                         R_FragmentLocation(surface->lightmaptexture, NULL, NULL, &ubase, &vbase, &uscale, &vscale);
2051                         uscale = (uscale - ubase) / ssize;
2052                         vscale = (vscale - vbase) / tsize;
2053
2054                         for (i = 0;i < surface->num_vertices;i++)
2055                         {
2056                                 u = ((DotProduct(((surface->groupmesh->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);
2057                                 v = ((DotProduct(((surface->groupmesh->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);
2058                                 (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2059                                 (surface->groupmesh->data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2060                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2061                                 iu = (int) u;
2062                                 iv = (int) v;
2063                                 (surface->groupmesh->data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2064                         }
2065                 }
2066         }
2067 }
2068
2069 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2070 {
2071         //if (node->parent)
2072         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion\n");
2073         node->parent = parent;
2074         if (node->plane)
2075         {
2076                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2077                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2078         }
2079 }
2080
2081 static void Mod_Q1BSP_LoadNodes(lump_t *l)
2082 {
2083         int                     i, j, count, p;
2084         dnode_t         *in;
2085         mnode_t         *out;
2086
2087         in = (dnode_t *)(mod_base + l->fileofs);
2088         if (l->filelen % sizeof(*in))
2089                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2090         count = l->filelen / sizeof(*in);
2091         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2092
2093         loadmodel->brush.data_nodes = out;
2094         loadmodel->brush.num_nodes = count;
2095
2096         for ( i=0 ; i<count ; i++, in++, out++)
2097         {
2098                 for (j=0 ; j<3 ; j++)
2099                 {
2100                         out->mins[j] = LittleShort(in->mins[j]);
2101                         out->maxs[j] = LittleShort(in->maxs[j]);
2102                 }
2103
2104                 p = LittleLong(in->planenum);
2105                 out->plane = loadmodel->brush.data_planes + p;
2106
2107                 out->firstsurface = LittleShort(in->firstface);
2108                 out->numsurfaces = LittleShort(in->numfaces);
2109
2110                 for (j=0 ; j<2 ; j++)
2111                 {
2112                         p = LittleShort(in->children[j]);
2113                         if (p >= 0)
2114                                 out->children[j] = loadmodel->brush.data_nodes + p;
2115                         else
2116                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + (-1 - p));
2117                 }
2118         }
2119
2120         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2121 }
2122
2123 static void Mod_Q1BSP_LoadLeafs(lump_t *l)
2124 {
2125         dleaf_t *in;
2126         mleaf_t *out;
2127         int i, j, count, p;
2128
2129         in = (dleaf_t *)(mod_base + l->fileofs);
2130         if (l->filelen % sizeof(*in))
2131                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2132         count = l->filelen / sizeof(*in);
2133         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2134
2135         loadmodel->brush.data_leafs = out;
2136         loadmodel->brush.num_leafs = count;
2137         // get visleafs from the submodel data
2138         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2139         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2140         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2141         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2142
2143         for ( i=0 ; i<count ; i++, in++, out++)
2144         {
2145                 for (j=0 ; j<3 ; j++)
2146                 {
2147                         out->mins[j] = LittleShort(in->mins[j]);
2148                         out->maxs[j] = LittleShort(in->maxs[j]);
2149                 }
2150
2151                 // FIXME: this function could really benefit from some error checking
2152
2153                 out->contents = LittleLong(in->contents);
2154
2155                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + LittleShort(in->firstmarksurface);
2156                 out->numleafsurfaces = LittleShort(in->nummarksurfaces);
2157                 if (out->firstleafsurface < 0 || LittleShort(in->firstmarksurface) + out->numleafsurfaces > loadmodel->brush.num_leafsurfaces)
2158                 {
2159                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", out->firstleafsurface, out->firstleafsurface + out->numleafsurfaces, 0, loadmodel->brush.num_leafsurfaces);
2160                         out->firstleafsurface = NULL;
2161                         out->numleafsurfaces = 0;
2162                 }
2163
2164                 out->clusterindex = i - 1;
2165                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2166                         out->clusterindex = -1;
2167
2168                 p = LittleLong(in->visofs);
2169                 // ignore visofs errors on leaf 0 (solid)
2170                 if (p >= 0 && out->clusterindex >= 0)
2171                 {
2172                         if (p >= loadmodel->brushq1.num_compressedpvs)
2173                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2174                         else
2175                                 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);
2176                 }
2177
2178                 for (j = 0;j < 4;j++)
2179                         out->ambient_sound_level[j] = in->ambient_level[j];
2180
2181                 // FIXME: Insert caustics here
2182         }
2183 }
2184
2185 static void Mod_Q1BSP_LoadClipnodes(lump_t *l, hullinfo_t *hullinfo)
2186 {
2187         dclipnode_t *in, *out;
2188         int                     i, count;
2189         hull_t          *hull;
2190
2191         in = (dclipnode_t *)(mod_base + l->fileofs);
2192         if (l->filelen % sizeof(*in))
2193                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2194         count = l->filelen / sizeof(*in);
2195         out = (dclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2196
2197         loadmodel->brushq1.clipnodes = out;
2198         loadmodel->brushq1.numclipnodes = count;
2199
2200         for (i = 1; i < hullinfo->numhulls; i++)
2201         {
2202                 hull = &loadmodel->brushq1.hulls[i];
2203                 hull->clipnodes = out;
2204                 hull->firstclipnode = 0;
2205                 hull->lastclipnode = count-1;
2206                 hull->planes = loadmodel->brush.data_planes;
2207                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
2208                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
2209                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
2210                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
2211                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
2212                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
2213                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
2214         }
2215
2216         for (i=0 ; i<count ; i++, out++, in++)
2217         {
2218                 out->planenum = LittleLong(in->planenum);
2219                 out->children[0] = LittleShort(in->children[0]);
2220                 out->children[1] = LittleShort(in->children[1]);
2221                 if (out->children[0] >= count || out->children[1] >= count)
2222                         Host_Error("Corrupt clipping hull(out of range child)\n");
2223         }
2224 }
2225
2226 //Duplicate the drawing hull structure as a clipping hull
2227 static void Mod_Q1BSP_MakeHull0(void)
2228 {
2229         mnode_t         *in;
2230         dclipnode_t *out;
2231         int                     i;
2232         hull_t          *hull;
2233
2234         hull = &loadmodel->brushq1.hulls[0];
2235
2236         in = loadmodel->brush.data_nodes;
2237         out = (dclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(dclipnode_t));
2238
2239         hull->clipnodes = out;
2240         hull->firstclipnode = 0;
2241         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
2242         hull->planes = loadmodel->brush.data_planes;
2243
2244         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
2245         {
2246                 out->planenum = in->plane - loadmodel->brush.data_planes;
2247                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
2248                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
2249         }
2250 }
2251
2252 static void Mod_Q1BSP_LoadLeaffaces(lump_t *l)
2253 {
2254         int i, j;
2255         short *in;
2256
2257         in = (short *)(mod_base + l->fileofs);
2258         if (l->filelen % sizeof(*in))
2259                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
2260         loadmodel->brush.num_leafsurfaces = l->filelen / sizeof(*in);
2261         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
2262
2263         for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
2264         {
2265                 j = (unsigned) LittleShort(in[i]);
2266                 if (j >= loadmodel->num_surfaces)
2267                         Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
2268                 loadmodel->brush.data_leafsurfaces[i] = j;
2269         }
2270 }
2271
2272 static void Mod_Q1BSP_LoadSurfedges(lump_t *l)
2273 {
2274         int             i;
2275         int             *in;
2276
2277         in = (int *)(mod_base + l->fileofs);
2278         if (l->filelen % sizeof(*in))
2279                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
2280         loadmodel->brushq1.numsurfedges = l->filelen / sizeof(*in);
2281         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
2282
2283         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
2284                 loadmodel->brushq1.surfedges[i] = LittleLong(in[i]);
2285 }
2286
2287
2288 static void Mod_Q1BSP_LoadPlanes(lump_t *l)
2289 {
2290         int                     i;
2291         mplane_t        *out;
2292         dplane_t        *in;
2293
2294         in = (dplane_t *)(mod_base + l->fileofs);
2295         if (l->filelen % sizeof(*in))
2296                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
2297
2298         loadmodel->brush.num_planes = l->filelen / sizeof(*in);
2299         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
2300
2301         for (i = 0;i < loadmodel->brush.num_planes;i++, in++, out++)
2302         {
2303                 out->normal[0] = LittleFloat(in->normal[0]);
2304                 out->normal[1] = LittleFloat(in->normal[1]);
2305                 out->normal[2] = LittleFloat(in->normal[2]);
2306                 out->dist = LittleFloat(in->dist);
2307
2308                 PlaneClassify(out);
2309         }
2310 }
2311
2312 static void Mod_Q1BSP_LoadMapBrushes(void)
2313 {
2314 #if 0
2315 // unfinished
2316         int submodel, numbrushes;
2317         qboolean firstbrush;
2318         char *text, *maptext;
2319         char mapfilename[MAX_QPATH];
2320         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
2321         strlcat (mapfilename, ".map", sizeof (mapfilename));
2322         maptext = (qbyte*) FS_LoadFile(mapfilename, tempmempool, false);
2323         if (!maptext)
2324                 return;
2325         text = maptext;
2326         if (!COM_ParseToken(&data, false))
2327                 return; // error
2328         submodel = 0;
2329         for (;;)
2330         {
2331                 if (!COM_ParseToken(&data, false))
2332                         break;
2333                 if (com_token[0] != '{')
2334                         return; // error
2335                 // entity
2336                 firstbrush = true;
2337                 numbrushes = 0;
2338                 maxbrushes = 256;
2339                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
2340                 for (;;)
2341                 {
2342                         if (!COM_ParseToken(&data, false))
2343                                 return; // error
2344                         if (com_token[0] == '}')
2345                                 break; // end of entity
2346                         if (com_token[0] == '{')
2347                         {
2348                                 // brush
2349                                 if (firstbrush)
2350                                 {
2351                                         if (submodel)
2352                                         {
2353                                                 if (submodel > loadmodel->brush.numsubmodels)
2354                                                 {
2355                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
2356                                                         model = NULL;
2357                                                 }
2358                                                 else
2359                                                         model = loadmodel->brush.submodels[submodel];
2360                                         }
2361                                         else
2362                                                 model = loadmodel;
2363                                 }
2364                                 for (;;)
2365                                 {
2366                                         if (!COM_ParseToken(&data, false))
2367                                                 return; // error
2368                                         if (com_token[0] == '}')
2369                                                 break; // end of brush
2370                                         // each brush face should be this format:
2371                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
2372                                         // FIXME: support hl .map format
2373                                         for (pointnum = 0;pointnum < 3;pointnum++)
2374                                         {
2375                                                 COM_ParseToken(&data, false);
2376                                                 for (componentnum = 0;componentnum < 3;componentnum++)
2377                                                 {
2378                                                         COM_ParseToken(&data, false);
2379                                                         point[pointnum][componentnum] = atof(com_token);
2380                                                 }
2381                                                 COM_ParseToken(&data, false);
2382                                         }
2383                                         COM_ParseToken(&data, false);
2384                                         strlcpy(facetexture, com_token, sizeof(facetexture));
2385                                         COM_ParseToken(&data, false);
2386                                         //scroll_s = atof(com_token);
2387                                         COM_ParseToken(&data, false);
2388                                         //scroll_t = atof(com_token);
2389                                         COM_ParseToken(&data, false);
2390                                         //rotate = atof(com_token);
2391                                         COM_ParseToken(&data, false);
2392                                         //scale_s = atof(com_token);
2393                                         COM_ParseToken(&data, false);
2394                                         //scale_t = atof(com_token);
2395                                         TriangleNormal(point[0], point[1], point[2], planenormal);
2396                                         VectorNormalizeDouble(planenormal);
2397                                         planedist = DotProduct(point[0], planenormal);
2398                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
2399                                 }
2400                                 continue;
2401                         }
2402                 }
2403         }
2404 #endif
2405 }
2406
2407
2408 #define MAX_PORTALPOINTS 64
2409
2410 typedef struct portal_s
2411 {
2412         mplane_t plane;
2413         mnode_t *nodes[2];              // [0] = front side of plane
2414         struct portal_s *next[2];
2415         int numpoints;
2416         double points[3*MAX_PORTALPOINTS];
2417         struct portal_s *chain; // all portals are linked into a list
2418 }
2419 portal_t;
2420
2421 static portal_t *portalchain;
2422
2423 /*
2424 ===========
2425 AllocPortal
2426 ===========
2427 */
2428 static portal_t *AllocPortal(void)
2429 {
2430         portal_t *p;
2431         p = (portal_t *)Mem_Alloc(loadmodel->mempool, sizeof(portal_t));
2432         p->chain = portalchain;
2433         portalchain = p;
2434         return p;
2435 }
2436
2437 static void FreePortal(portal_t *p)
2438 {
2439         Mem_Free(p);
2440 }
2441
2442 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
2443 {
2444         // process only nodes (leafs already had their box calculated)
2445         if (!node->plane)
2446                 return;
2447
2448         // calculate children first
2449         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
2450         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
2451
2452         // make combined bounding box from children
2453         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
2454         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
2455         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
2456         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
2457         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
2458         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
2459 }
2460
2461 static void Mod_Q1BSP_FinalizePortals(void)
2462 {
2463         int i, j, numportals, numpoints;
2464         portal_t *p, *pnext;
2465         mportal_t *portal;
2466         mvertex_t *point;
2467         mleaf_t *leaf, *endleaf;
2468
2469         // recalculate bounding boxes for all leafs(because qbsp is very sloppy)
2470         leaf = loadmodel->brush.data_leafs;
2471         endleaf = leaf + loadmodel->brush.num_leafs;
2472         for (;leaf < endleaf;leaf++)
2473         {
2474                 VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
2475                 VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
2476         }
2477         p = portalchain;
2478         while (p)
2479         {
2480                 if (p->numpoints >= 3)
2481                 {
2482                         for (i = 0;i < 2;i++)
2483                         {
2484                                 leaf = (mleaf_t *)p->nodes[i];
2485                                 for (j = 0;j < p->numpoints;j++)
2486                                 {
2487                                         if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
2488                                         if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
2489                                         if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
2490                                         if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
2491                                         if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
2492                                         if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
2493                                 }
2494                         }
2495                 }
2496                 p = p->chain;
2497         }
2498
2499         Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes);
2500
2501         // tally up portal and point counts
2502         p = portalchain;
2503         numportals = 0;
2504         numpoints = 0;
2505         while (p)
2506         {
2507                 // note: this check must match the one below or it will usually corrupt memory
2508                 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
2509                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2510                 {
2511                         numportals += 2;
2512                         numpoints += p->numpoints * 2;
2513                 }
2514                 p = p->chain;
2515         }
2516         loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
2517         loadmodel->brush.num_portals = numportals;
2518         loadmodel->brush.data_portalpoints = (mvertex_t *)((qbyte *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
2519         loadmodel->brush.num_portalpoints = numpoints;
2520         // clear all leaf portal chains
2521         for (i = 0;i < loadmodel->brush.num_leafs;i++)
2522                 loadmodel->brush.data_leafs[i].portals = NULL;
2523         // process all portals in the global portal chain, while freeing them
2524         portal = loadmodel->brush.data_portals;
2525         point = loadmodel->brush.data_portalpoints;
2526         p = portalchain;
2527         portalchain = NULL;
2528         while (p)
2529         {
2530                 pnext = p->chain;
2531
2532                 // note: this check must match the one above or it will usually corrupt memory
2533                 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
2534                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
2535                 {
2536                         // first make the back to front portal(forward portal)
2537                         portal->points = point;
2538                         portal->numpoints = p->numpoints;
2539                         portal->plane.dist = p->plane.dist;
2540                         VectorCopy(p->plane.normal, portal->plane.normal);
2541                         portal->here = (mleaf_t *)p->nodes[1];
2542                         portal->past = (mleaf_t *)p->nodes[0];
2543                         // copy points
2544                         for (j = 0;j < portal->numpoints;j++)
2545                         {
2546                                 VectorCopy(p->points + j*3, point->position);
2547                                 point++;
2548                         }
2549                         BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2550                         PlaneClassify(&portal->plane);
2551
2552                         // link into leaf's portal chain
2553                         portal->next = portal->here->portals;
2554                         portal->here->portals = portal;
2555
2556                         // advance to next portal
2557                         portal++;
2558
2559                         // then make the front to back portal(backward portal)
2560                         portal->points = point;
2561                         portal->numpoints = p->numpoints;
2562                         portal->plane.dist = -p->plane.dist;
2563                         VectorNegate(p->plane.normal, portal->plane.normal);
2564                         portal->here = (mleaf_t *)p->nodes[0];
2565                         portal->past = (mleaf_t *)p->nodes[1];
2566                         // copy points
2567                         for (j = portal->numpoints - 1;j >= 0;j--)
2568                         {
2569                                 VectorCopy(p->points + j*3, point->position);
2570                                 point++;
2571                         }
2572                         BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
2573                         PlaneClassify(&portal->plane);
2574
2575                         // link into leaf's portal chain
2576                         portal->next = portal->here->portals;
2577                         portal->here->portals = portal;
2578
2579                         // advance to next portal
2580                         portal++;
2581                 }
2582                 FreePortal(p);
2583                 p = pnext;
2584         }
2585 }
2586
2587 /*
2588 =============
2589 AddPortalToNodes
2590 =============
2591 */
2592 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
2593 {
2594         if (!front)
2595                 Host_Error("AddPortalToNodes: NULL front node");
2596         if (!back)
2597                 Host_Error("AddPortalToNodes: NULL back node");
2598         if (p->nodes[0] || p->nodes[1])
2599                 Host_Error("AddPortalToNodes: already included");
2600         // note: front == back is handled gracefully, because leaf 0 is the shared solid leaf, it can often have portals with the same leaf on both sides
2601
2602         p->nodes[0] = front;
2603         p->next[0] = (portal_t *)front->portals;
2604         front->portals = (mportal_t *)p;
2605
2606         p->nodes[1] = back;
2607         p->next[1] = (portal_t *)back->portals;
2608         back->portals = (mportal_t *)p;
2609 }
2610
2611 /*
2612 =============
2613 RemovePortalFromNode
2614 =============
2615 */
2616 static void RemovePortalFromNodes(portal_t *portal)
2617 {
2618         int i;
2619         mnode_t *node;
2620         void **portalpointer;
2621         portal_t *t;
2622         for (i = 0;i < 2;i++)
2623         {
2624                 node = portal->nodes[i];
2625
2626                 portalpointer = (void **) &node->portals;
2627                 while (1)
2628                 {
2629                         t = (portal_t *)*portalpointer;
2630                         if (!t)
2631                                 Host_Error("RemovePortalFromNodes: portal not in leaf");
2632
2633                         if (t == portal)
2634                         {
2635                                 if (portal->nodes[0] == node)
2636                                 {
2637                                         *portalpointer = portal->next[0];
2638                                         portal->nodes[0] = NULL;
2639                                 }
2640                                 else if (portal->nodes[1] == node)
2641                                 {
2642                                         *portalpointer = portal->next[1];
2643                                         portal->nodes[1] = NULL;
2644                                 }
2645                                 else
2646                                         Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2647                                 break;
2648                         }
2649
2650                         if (t->nodes[0] == node)
2651                                 portalpointer = (void **) &t->next[0];
2652                         else if (t->nodes[1] == node)
2653                                 portalpointer = (void **) &t->next[1];
2654                         else
2655                                 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
2656                 }
2657         }
2658 }
2659
2660 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
2661 {
2662         int i, side;
2663         mnode_t *front, *back, *other_node;
2664         mplane_t clipplane, *plane;
2665         portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
2666         int numfrontpoints, numbackpoints;
2667         double frontpoints[3*MAX_PORTALPOINTS], backpoints[3*MAX_PORTALPOINTS];
2668
2669         // if a leaf, we're done
2670         if (!node->plane)
2671                 return;
2672
2673         plane = node->plane;
2674
2675         front = node->children[0];
2676         back = node->children[1];
2677         if (front == back)
2678                 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
2679
2680         // create the new portal by generating a polygon for the node plane,
2681         // and clipping it by all of the other portals(which came from nodes above this one)
2682         nodeportal = AllocPortal();
2683         nodeportal->plane = *plane;
2684
2685         PolygonD_QuadForPlane(nodeportal->points, nodeportal->plane.normal[0], nodeportal->plane.normal[1], nodeportal->plane.normal[2], nodeportal->plane.dist, 1024.0*1024.0*1024.0);
2686         nodeportal->numpoints = 4;
2687         side = 0;       // shut up compiler warning
2688         for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
2689         {
2690                 clipplane = portal->plane;
2691                 if (portal->nodes[0] == portal->nodes[1])
2692                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
2693                 if (portal->nodes[0] == node)
2694                         side = 0;
2695                 else if (portal->nodes[1] == node)
2696                 {
2697                         clipplane.dist = -clipplane.dist;
2698                         VectorNegate(clipplane.normal, clipplane.normal);
2699                         side = 1;
2700                 }
2701                 else
2702                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2703
2704                 for (i = 0;i < nodeportal->numpoints*3;i++)
2705                         frontpoints[i] = nodeportal->points[i];
2706                 PolygonD_Divide(nodeportal->numpoints, frontpoints, clipplane.normal[0], clipplane.normal[1], clipplane.normal[2], clipplane.dist, 1.0/32.0, MAX_PORTALPOINTS, nodeportal->points, &nodeportal->numpoints, 0, NULL, NULL);
2707                 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
2708                         break;
2709         }
2710
2711         if (nodeportal->numpoints < 3)
2712         {
2713                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
2714                 nodeportal->numpoints = 0;
2715         }
2716         else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
2717         {
2718                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
2719                 nodeportal->numpoints = 0;
2720         }
2721
2722         AddPortalToNodes(nodeportal, front, back);
2723
2724         // split the portals of this node along this node's plane and assign them to the children of this node
2725         // (migrating the portals downward through the tree)
2726         for (portal = (portal_t *)node->portals;portal;portal = nextportal)
2727         {
2728                 if (portal->nodes[0] == portal->nodes[1])
2729                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
2730                 if (portal->nodes[0] == node)
2731                         side = 0;
2732                 else if (portal->nodes[1] == node)
2733                         side = 1;
2734                 else
2735                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
2736                 nextportal = portal->next[side];
2737                 if (!portal->numpoints)
2738                         continue;
2739
2740                 other_node = portal->nodes[!side];
2741                 RemovePortalFromNodes(portal);
2742
2743                 // cut the portal into two portals, one on each side of the node plane
2744                 PolygonD_Divide(portal->numpoints, portal->points, plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, 1.0/32.0, MAX_PORTALPOINTS, frontpoints, &numfrontpoints, MAX_PORTALPOINTS, backpoints, &numbackpoints);
2745
2746                 if (!numfrontpoints)
2747                 {
2748                         if (side == 0)
2749                                 AddPortalToNodes(portal, back, other_node);
2750                         else
2751                                 AddPortalToNodes(portal, other_node, back);
2752                         continue;
2753                 }
2754                 if (!numbackpoints)
2755                 {
2756                         if (side == 0)
2757                                 AddPortalToNodes(portal, front, other_node);
2758                         else
2759                                 AddPortalToNodes(portal, other_node, front);
2760                         continue;
2761                 }
2762
2763                 // the portal is split
2764                 splitportal = AllocPortal();
2765                 temp = splitportal->chain;
2766                 *splitportal = *portal;
2767                 splitportal->chain = temp;
2768                 for (i = 0;i < numbackpoints*3;i++)
2769                         splitportal->points[i] = backpoints[i];
2770                 splitportal->numpoints = numbackpoints;
2771                 for (i = 0;i < numfrontpoints*3;i++)
2772                         portal->points[i] = frontpoints[i];
2773                 portal->numpoints = numfrontpoints;
2774
2775                 if (side == 0)
2776                 {
2777                         AddPortalToNodes(portal, front, other_node);
2778                         AddPortalToNodes(splitportal, back, other_node);
2779                 }
2780                 else
2781                 {
2782                         AddPortalToNodes(portal, other_node, front);
2783                         AddPortalToNodes(splitportal, other_node, back);
2784                 }
2785         }
2786
2787         Mod_Q1BSP_RecursiveNodePortals(front);
2788         Mod_Q1BSP_RecursiveNodePortals(back);
2789 }
2790
2791 static void Mod_Q1BSP_MakePortals(void)
2792 {
2793         portalchain = NULL;
2794         Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes);
2795         Mod_Q1BSP_FinalizePortals();
2796 }
2797
2798 static void Mod_Q1BSP_BuildLightmapUpdateChains(mempool_t *mempool, model_t *model)
2799 {
2800         int i, j, stylecounts[256], totalcount, remapstyles[256];
2801         msurface_t *surface;
2802         memset(stylecounts, 0, sizeof(stylecounts));
2803         for (i = 0;i < model->nummodelsurfaces;i++)
2804         {
2805                 surface = model->data_surfaces + model->firstmodelsurface + i;
2806                 for (j = 0;j < MAXLIGHTMAPS;j++)
2807                         stylecounts[surface->lightmapinfo->styles[j]]++;
2808         }
2809         totalcount = 0;
2810         model->brushq1.light_styles = 0;
2811         for (i = 0;i < 255;i++)
2812         {
2813                 if (stylecounts[i])
2814                 {
2815                         remapstyles[i] = model->brushq1.light_styles++;
2816                         totalcount += stylecounts[i] + 1;
2817                 }
2818         }
2819         if (!totalcount)
2820                 return;
2821         model->brushq1.light_style = (qbyte *)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(qbyte));
2822         model->brushq1.light_stylevalue = (int *)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(int));
2823         model->brushq1.light_styleupdatechains = (msurface_t ***)Mem_Alloc(mempool, model->brushq1.light_styles * sizeof(msurface_t **));
2824         model->brushq1.light_styleupdatechainsbuffer = (msurface_t **)Mem_Alloc(mempool, totalcount * sizeof(msurface_t *));
2825         model->brushq1.light_styles = 0;
2826         for (i = 0;i < 255;i++)
2827                 if (stylecounts[i])
2828                         model->brushq1.light_style[model->brushq1.light_styles++] = i;
2829         j = 0;
2830         for (i = 0;i < model->brushq1.light_styles;i++)
2831         {
2832                 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2833                 j += stylecounts[model->brushq1.light_style[i]] + 1;
2834         }
2835         for (i = 0;i < model->nummodelsurfaces;i++)
2836         {
2837                 surface = model->data_surfaces + model->firstmodelsurface + i;
2838                 for (j = 0;j < MAXLIGHTMAPS;j++)
2839                         if (surface->lightmapinfo->styles[j] != 255)
2840                                 *model->brushq1.light_styleupdatechains[remapstyles[surface->lightmapinfo->styles[j]]]++ = surface;
2841         }
2842         j = 0;
2843         for (i = 0;i < model->brushq1.light_styles;i++)
2844         {
2845                 *model->brushq1.light_styleupdatechains[i] = NULL;
2846                 model->brushq1.light_styleupdatechains[i] = model->brushq1.light_styleupdatechainsbuffer + j;
2847                 j += stylecounts[model->brushq1.light_style[i]] + 1;
2848         }
2849 }
2850
2851 //Returns PVS data for a given point
2852 //(note: can return NULL)
2853 static qbyte *Mod_Q1BSP_GetPVS(model_t *model, const vec3_t p)
2854 {
2855         mnode_t *node;
2856         node = model->brush.data_nodes;
2857         while (node->plane)
2858                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
2859         if (((mleaf_t *)node)->clusterindex >= 0)
2860                 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2861         else
2862                 return NULL;
2863 }
2864
2865 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbytes, mnode_t *node)
2866 {
2867         while (node->plane)
2868         {
2869                 float d = PlaneDiff(org, node->plane);
2870                 if (d > radius)
2871                         node = node->children[0];
2872                 else if (d < -radius)
2873                         node = node->children[1];
2874                 else
2875                 {
2876                         // go down both sides
2877                         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
2878                         node = node->children[1];
2879                 }
2880         }
2881         // if this leaf is in a cluster, accumulate the pvs bits
2882         if (((mleaf_t *)node)->clusterindex >= 0)
2883         {
2884                 int i;
2885                 qbyte *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
2886                 for (i = 0;i < pvsbytes;i++)
2887                         pvsbuffer[i] |= pvs[i];
2888         }
2889 }
2890
2891 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
2892 //of the given point.
2893 static int Mod_Q1BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, qbyte *pvsbuffer, int pvsbufferlength)
2894 {
2895         int bytes = model->brush.num_pvsclusterbytes;
2896         bytes = min(bytes, pvsbufferlength);
2897         if (r_novis.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
2898         {
2899                 memset(pvsbuffer, 0xFF, bytes);
2900                 return bytes;
2901         }
2902         memset(pvsbuffer, 0, bytes);
2903         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes);
2904         return bytes;
2905 }
2906
2907 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
2908 {
2909         vec3_t size;
2910         const hull_t *hull;
2911
2912         VectorSubtract(inmaxs, inmins, size);
2913         if (cmodel->brush.ismcbsp)
2914         {
2915                 if (size[0] < 3)
2916                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2917                 else if (size[2] < 48) // pick the nearest of 40 or 56
2918                         hull = &cmodel->brushq1.hulls[2]; // 16x16x40
2919                 else
2920                         hull = &cmodel->brushq1.hulls[1]; // 16x16x56
2921         }
2922         else if (cmodel->brush.ishlbsp)
2923         {
2924                 if (size[0] < 3)
2925                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2926                 else if (size[0] <= 32)
2927                 {
2928                         if (size[2] < 54) // pick the nearest of 36 or 72
2929                                 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
2930                         else
2931                                 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
2932                 }
2933                 else
2934                         hull = &cmodel->brushq1.hulls[2]; // 64x64x64
2935         }
2936         else
2937         {
2938                 if (size[0] < 3)
2939                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
2940                 else if (size[0] <= 32)
2941                         hull = &cmodel->brushq1.hulls[1]; // 32x32x56
2942                 else
2943                         hull = &cmodel->brushq1.hulls[2]; // 64x64x88
2944         }
2945         VectorCopy(inmins, outmins);
2946         VectorAdd(inmins, hull->clip_size, outmaxs);
2947 }
2948
2949 void Mod_Q1BSP_Load(model_t *mod, void *buffer, void *bufferend)
2950 {
2951         int i, j, k;
2952         dheader_t *header;
2953         dmodel_t *bm;
2954         mempool_t *mainmempool;
2955         float dist, modelyawradius, modelradius, *vec;
2956         msurface_t *surface;
2957         int numshadowmeshtriangles;
2958         dheader_t _header;
2959         hullinfo_t hullinfo;
2960
2961         mod->type = mod_brushq1;
2962
2963         if (!memcmp (buffer, "MCBSPpad", 8))
2964         {
2965                 qbyte   *index;
2966
2967                 mod->brush.ismcbsp = true;
2968                 mod->brush.ishlbsp = false;
2969
2970                 mod_base = (qbyte*)buffer;
2971
2972                 index = mod_base;
2973                 index += 8;
2974                 i = SB_ReadInt (&index);
2975                 if (i != MCBSPVERSION)
2976                         Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i)", mod->name, i, MCBSPVERSION);
2977
2978         // read hull info
2979                 hullinfo.numhulls = LittleLong(*(int*)index); index += 4;
2980                 hullinfo.filehulls = hullinfo.numhulls;
2981                 VectorClear (hullinfo.hullsizes[0][0]);
2982                 VectorClear (hullinfo.hullsizes[0][1]);
2983                 for (i = 1; i < hullinfo.numhulls; i++)
2984                 {
2985                         hullinfo.hullsizes[i][0][0] = SB_ReadFloat (&index);
2986                         hullinfo.hullsizes[i][0][1] = SB_ReadFloat (&index);
2987                         hullinfo.hullsizes[i][0][2] = SB_ReadFloat (&index);
2988                         hullinfo.hullsizes[i][1][0] = SB_ReadFloat (&index);
2989                         hullinfo.hullsizes[i][1][1] = SB_ReadFloat (&index);
2990                         hullinfo.hullsizes[i][1][2] = SB_ReadFloat (&index);
2991                 }
2992
2993         // read lumps
2994                 _header.version = 0;
2995                 for (i = 0; i < HEADER_LUMPS; i++)
2996                 {
2997                         _header.lumps[i].fileofs = SB_ReadInt (&index);
2998                         _header.lumps[i].filelen = SB_ReadInt (&index);
2999                 }
3000
3001                 header = &_header;
3002         }
3003         else
3004         {
3005                 header = (dheader_t *)buffer;
3006
3007                 i = LittleLong(header->version);
3008                 if (i != BSPVERSION && i != 30)
3009                         Host_Error("Mod_Q1BSP_Load: %s has wrong version number(%i should be %i(Quake) or 30(HalfLife)", mod->name, i, BSPVERSION);
3010                 mod->brush.ishlbsp = i == 30;
3011                 mod->brush.ismcbsp = false;
3012
3013         // fill in hull info
3014                 VectorClear (hullinfo.hullsizes[0][0]);
3015                 VectorClear (hullinfo.hullsizes[0][1]);
3016                 if (mod->brush.ishlbsp)
3017                 {
3018                         hullinfo.numhulls = 4;
3019                         hullinfo.filehulls = 4;
3020                         VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3021                         VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3022                         VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3023                         VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3024                         VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3025                         VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3026                 }
3027                 else
3028                 {
3029                         hullinfo.numhulls = 3;
3030                         hullinfo.filehulls = 4;
3031                         VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3032                         VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3033                         VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3034                         VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3035                 }
3036
3037         // read lumps
3038                 mod_base = (qbyte*)buffer;
3039                 for (i = 0; i < HEADER_LUMPS; i++)
3040                 {
3041                         header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
3042                         header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
3043                 }
3044         }
3045
3046         mod->soundfromcenter = true;
3047         mod->TraceBox = Mod_Q1BSP_TraceBox;
3048         mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3049         mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3050         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3051         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3052         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3053         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3054         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3055         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3056         mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3057         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3058         mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3059         mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3060         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3061
3062         if (loadmodel->isworldmodel)
3063         {
3064                 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
3065                 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
3066         }
3067
3068 // load into heap
3069
3070         // store which lightmap format to use
3071         mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
3072
3073         Mod_Q1BSP_LoadEntities(&header->lumps[LUMP_ENTITIES]);
3074         Mod_Q1BSP_LoadVertexes(&header->lumps[LUMP_VERTEXES]);
3075         Mod_Q1BSP_LoadEdges(&header->lumps[LUMP_EDGES]);
3076         Mod_Q1BSP_LoadSurfedges(&header->lumps[LUMP_SURFEDGES]);
3077         Mod_Q1BSP_LoadTextures(&header->lumps[LUMP_TEXTURES]);
3078         Mod_Q1BSP_LoadLighting(&header->lumps[LUMP_LIGHTING]);
3079         Mod_Q1BSP_LoadPlanes(&header->lumps[LUMP_PLANES]);
3080         Mod_Q1BSP_LoadTexinfo(&header->lumps[LUMP_TEXINFO]);
3081         Mod_Q1BSP_LoadFaces(&header->lumps[LUMP_FACES]);
3082         Mod_Q1BSP_LoadLeaffaces(&header->lumps[LUMP_MARKSURFACES]);
3083         Mod_Q1BSP_LoadVisibility(&header->lumps[LUMP_VISIBILITY]);
3084         // load submodels before leafs because they contain the number of vis leafs
3085         Mod_Q1BSP_LoadSubmodels(&header->lumps[LUMP_MODELS], &hullinfo);
3086         Mod_Q1BSP_LoadLeafs(&header->lumps[LUMP_LEAFS]);
3087         Mod_Q1BSP_LoadNodes(&header->lumps[LUMP_NODES]);
3088         Mod_Q1BSP_LoadClipnodes(&header->lumps[LUMP_CLIPNODES], &hullinfo);
3089
3090         if (!mod->brushq1.lightdata)
3091                 mod->brush.LightPoint = NULL;
3092
3093         if (mod->brushq1.data_compressedpvs)
3094                 Mem_Free(mod->brushq1.data_compressedpvs);
3095         mod->brushq1.data_compressedpvs = NULL;
3096         mod->brushq1.num_compressedpvs = 0;
3097
3098         Mod_Q1BSP_MakeHull0();
3099         Mod_Q1BSP_MakePortals();
3100
3101         mod->numframes = 2;             // regular and alternate animation
3102         mod->numskins = 1;
3103
3104         mainmempool = mod->mempool;
3105
3106         Mod_Q1BSP_LoadLightList();
3107
3108         // make a single combined shadow mesh to allow optimized shadow volume creation
3109         numshadowmeshtriangles = 0;
3110         for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3111         {
3112                 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3113                 numshadowmeshtriangles += surface->num_triangles;
3114         }
3115         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3116         for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
3117                 Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, surface->groupmesh->data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle));
3118         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
3119         Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
3120
3121         if (loadmodel->brush.numsubmodels)
3122                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
3123
3124         if (loadmodel->isworldmodel)
3125         {
3126                 // clear out any stale submodels or worldmodels lying around
3127                 // if we did this clear before now, an error might abort loading and
3128                 // leave things in a bad state
3129                 Mod_RemoveStaleWorldModels(loadmodel);
3130         }
3131
3132         // LordHavoc: to clear the fog around the original quake submodel code, I
3133         // will explain:
3134         // first of all, some background info on the submodels:
3135         // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3136         // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3137         // now the weird for loop itself:
3138         // the loop functions in an odd way, on each iteration it sets up the
3139         // current 'mod' model (which despite the confusing code IS the model of
3140         // the number i), at the end of the loop it duplicates the model to become
3141         // the next submodel, and loops back to set up the new submodel.
3142
3143         // LordHavoc: now the explanation of my sane way (which works identically):
3144         // set up the world model, then on each submodel copy from the world model
3145         // and set up the submodel with the respective model info.
3146         for (i = 0;i < mod->brush.numsubmodels;i++)
3147         {
3148                 // LordHavoc: this code was originally at the end of this loop, but
3149                 // has been transformed to something more readable at the start here.
3150
3151                 if (i > 0)
3152                 {
3153                         char name[10];
3154                         // LordHavoc: only register submodels if it is the world
3155                         // (prevents external bsp models from replacing world submodels with
3156                         //  their own)
3157                         if (!loadmodel->isworldmodel)
3158                                 continue;
3159                         // duplicate the basic information
3160                         sprintf(name, "*%i", i);
3161                         mod = Mod_FindName(name);
3162                         // copy the base model to this one
3163                         *mod = *loadmodel;
3164                         // rename the clone back to its proper name
3165                         strcpy(mod->name, name);
3166                         // textures and memory belong to the main model
3167                         mod->texturepool = NULL;
3168                         mod->mempool = NULL;
3169                 }
3170
3171                 mod->brush.submodel = i;
3172
3173                 if (loadmodel->brush.submodels)
3174                         loadmodel->brush.submodels[i] = mod;
3175
3176                 bm = &mod->brushq1.submodels[i];
3177
3178                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3179                 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3180                 {
3181                         mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3182                         mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3183                 }
3184
3185                 mod->firstmodelsurface = bm->firstface;
3186                 mod->nummodelsurfaces = bm->numfaces;
3187
3188                 // make the model surface list (used by shadowing/lighting)
3189                 mod->surfacelist = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
3190                 for (j = 0;j < mod->nummodelsurfaces;j++)
3191                         mod->surfacelist[j] = mod->firstmodelsurface + j;
3192
3193                 // this gets altered below if sky is used
3194                 mod->DrawSky = NULL;
3195                 mod->Draw = R_Q1BSP_Draw;
3196                 mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3197                 mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3198                 mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3199                 mod->DrawLight = R_Q1BSP_DrawLight;
3200                 if (i != 0)
3201                 {
3202                         mod->brush.GetPVS = NULL;
3203                         mod->brush.FatPVS = NULL;
3204                         mod->brush.BoxTouchingPVS = NULL;
3205                         mod->brush.BoxTouchingLeafPVS = NULL;
3206                         mod->brush.BoxTouchingVisibleLeafs = NULL;
3207                         mod->brush.FindBoxClusters = NULL;
3208                         mod->brush.LightPoint = NULL;
3209                         mod->brush.AmbientSoundLevelsForPoint = NULL;
3210                 }
3211                 Mod_Q1BSP_BuildLightmapUpdateChains(loadmodel->mempool, mod);
3212                 if (mod->nummodelsurfaces)
3213                 {
3214                         // LordHavoc: calculate bmodel bounding box rather than trusting what it says
3215                         mod->normalmins[0] = mod->normalmins[1] = mod->normalmins[2] = 1000000000.0f;
3216                         mod->normalmaxs[0] = mod->normalmaxs[1] = mod->normalmaxs[2] = -1000000000.0f;
3217                         modelyawradius = 0;
3218                         modelradius = 0;
3219                         for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
3220                         {
3221                                 // we only need to have a drawsky function if it is used(usually only on world model)
3222                                 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3223                                         mod->DrawSky = R_Q1BSP_DrawSky;
3224                                 // calculate bounding shapes
3225                                 for (k = 0, vec = (surface->groupmesh->data_vertex3f + 3 * surface->num_firstvertex);k < surface->num_vertices;k++, vec += 3)
3226                                 {
3227                                         if (mod->normalmins[0] > vec[0]) mod->normalmins[0] = vec[0];
3228                                         if (mod->normalmins[1] > vec[1]) mod->normalmins[1] = vec[1];
3229                                         if (mod->normalmins[2] > vec[2]) mod->normalmins[2] = vec[2];
3230                                         if (mod->normalmaxs[0] < vec[0]) mod->normalmaxs[0] = vec[0];
3231                                         if (mod->normalmaxs[1] < vec[1]) mod->normalmaxs[1] = vec[1];
3232                                         if (mod->normalmaxs[2] < vec[2]) mod->normalmaxs[2] = vec[2];
3233                                         dist = vec[0]*vec[0]+vec[1]*vec[1];
3234                                         if (modelyawradius < dist)
3235                                                 modelyawradius = dist;
3236                                         dist += vec[2]*vec[2];
3237                                         if (modelradius < dist)
3238                                                 modelradius = dist;
3239                                 }
3240                         }
3241                         modelyawradius = sqrt(modelyawradius);
3242                         modelradius = sqrt(modelradius);
3243                         mod->yawmins[0] = mod->yawmins[1] = - (mod->yawmaxs[0] = mod->yawmaxs[1] = modelyawradius);
3244                         mod->yawmins[2] = mod->normalmins[2];
3245                         mod->yawmaxs[2] = mod->normalmaxs[2];
3246                         mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
3247                         mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
3248                         mod->radius = modelradius;
3249                         mod->radius2 = modelradius * modelradius;
3250                 }
3251                 else
3252                 {
3253                         // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
3254                         Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
3255                 }
3256                 //mod->brushq1.num_visleafs = bm->visleafs;
3257         }
3258
3259         Mod_Q1BSP_LoadMapBrushes();
3260
3261         //Mod_Q1BSP_ProcessLightList();
3262
3263         if (developer.integer)
3264                 Con_Printf("Some stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals);
3265 }
3266
3267 static void Mod_Q2BSP_LoadEntities(lump_t *l)
3268 {
3269 }
3270
3271 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
3272 {
3273 /*
3274         d_t *in;
3275         m_t *out;
3276         int i, count;
3277
3278         in = (void *)(mod_base + l->fileofs);
3279         if (l->filelen % sizeof(*in))
3280                 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
3281         count = l->filelen / sizeof(*in);
3282         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3283
3284         loadmodel-> = out;
3285         loadmodel->num = count;
3286
3287         for (i = 0;i < count;i++, in++, out++)
3288         {
3289         }
3290 */
3291 }
3292
3293 static void Mod_Q2BSP_LoadVertices(lump_t *l)
3294 {
3295 /*
3296         d_t *in;
3297         m_t *out;
3298         int i, count;
3299
3300         in = (void *)(mod_base + l->fileofs);
3301         if (l->filelen % sizeof(*in))
3302                 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
3303         count = l->filelen / sizeof(*in);
3304         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3305
3306         loadmodel-> = out;
3307         loadmodel->num = count;
3308
3309         for (i = 0;i < count;i++, in++, out++)
3310         {
3311         }
3312 */
3313 }
3314
3315 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
3316 {
3317 /*
3318         d_t *in;
3319         m_t *out;
3320         int i, count;
3321
3322         in = (void *)(mod_base + l->fileofs);
3323         if (l->filelen % sizeof(*in))
3324                 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
3325         count = l->filelen / sizeof(*in);
3326         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3327
3328         loadmodel-> = out;
3329         loadmodel->num = count;
3330
3331         for (i = 0;i < count;i++, in++, out++)
3332         {
3333         }
3334 */
3335 }
3336
3337 static void Mod_Q2BSP_LoadNodes(lump_t *l)
3338 {
3339 /*
3340         d_t *in;
3341         m_t *out;
3342         int i, count;
3343
3344         in = (void *)(mod_base + l->fileofs);
3345         if (l->filelen % sizeof(*in))
3346                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
3347         count = l->filelen / sizeof(*in);
3348         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3349
3350         loadmodel-> = out;
3351         loadmodel->num = count;
3352
3353         for (i = 0;i < count;i++, in++, out++)
3354         {
3355         }
3356 */
3357 }
3358
3359 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
3360 {
3361 /*
3362         d_t *in;
3363         m_t *out;
3364         int i, count;
3365
3366         in = (void *)(mod_base + l->fileofs);
3367         if (l->filelen % sizeof(*in))
3368                 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
3369         count = l->filelen / sizeof(*in);
3370         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3371
3372         loadmodel-> = out;
3373         loadmodel->num = count;
3374
3375         for (i = 0;i < count;i++, in++, out++)
3376         {
3377         }
3378 */
3379 }
3380
3381 static void Mod_Q2BSP_LoadFaces(lump_t *l)
3382 {
3383 /*
3384         d_t *in;
3385         m_t *out;
3386         int i, count;
3387
3388         in = (void *)(mod_base + l->fileofs);
3389         if (l->filelen % sizeof(*in))
3390                 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
3391         count = l->filelen / sizeof(*in);
3392         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3393
3394         loadmodel-> = out;
3395         loadmodel->num = count;
3396
3397         for (i = 0;i < count;i++, in++, out++)
3398         {
3399         }
3400 */
3401 }
3402
3403 static void Mod_Q2BSP_LoadLighting(lump_t *l)
3404 {
3405 /*
3406         d_t *in;
3407         m_t *out;
3408         int i, count;
3409
3410         in = (void *)(mod_base + l->fileofs);
3411         if (l->filelen % sizeof(*in))
3412                 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
3413         count = l->filelen / sizeof(*in);
3414         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3415
3416         loadmodel-> = out;
3417         loadmodel->num = count;
3418
3419         for (i = 0;i < count;i++, in++, out++)
3420         {
3421         }
3422 */
3423 }
3424
3425 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
3426 {
3427 /*
3428         d_t *in;
3429         m_t *out;
3430         int i, count;
3431
3432         in = (void *)(mod_base + l->fileofs);
3433         if (l->filelen % sizeof(*in))
3434                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
3435         count = l->filelen / sizeof(*in);
3436         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3437
3438         loadmodel-> = out;
3439         loadmodel->num = count;
3440
3441         for (i = 0;i < count;i++, in++, out++)
3442         {
3443         }
3444 */
3445 }
3446
3447 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
3448 {
3449 /*
3450         d_t *in;
3451         m_t *out;
3452         int i, count;
3453
3454         in = (void *)(mod_base + l->fileofs);
3455         if (l->filelen % sizeof(*in))
3456                 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
3457         count = l->filelen / sizeof(*in);
3458         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3459
3460         loadmodel-> = out;
3461         loadmodel->num = count;
3462
3463         for (i = 0;i < count;i++, in++, out++)
3464         {
3465         }
3466 */
3467 }
3468
3469 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
3470 {
3471 /*
3472         d_t *in;
3473         m_t *out;
3474         int i, count;
3475
3476         in = (void *)(mod_base + l->fileofs);
3477         if (l->filelen % sizeof(*in))
3478                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
3479         count = l->filelen / sizeof(*in);
3480         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3481
3482         loadmodel-> = out;
3483         loadmodel->num = count;
3484
3485         for (i = 0;i < count;i++, in++, out++)
3486         {
3487         }
3488 */
3489 }
3490
3491 static void Mod_Q2BSP_LoadEdges(lump_t *l)
3492 {
3493 /*
3494         d_t *in;
3495         m_t *out;
3496         int i, count;
3497
3498         in = (void *)(mod_base + l->fileofs);
3499         if (l->filelen % sizeof(*in))
3500                 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
3501         count = l->filelen / sizeof(*in);
3502         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3503
3504         loadmodel-> = out;
3505         loadmodel->num = count;
3506
3507         for (i = 0;i < count;i++, in++, out++)
3508         {
3509         }
3510 */
3511 }
3512
3513 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
3514 {
3515 /*
3516         d_t *in;
3517         m_t *out;
3518         int i, count;
3519
3520         in = (void *)(mod_base + l->fileofs);
3521         if (l->filelen % sizeof(*in))
3522                 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
3523         count = l->filelen / sizeof(*in);
3524         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3525
3526         loadmodel-> = out;
3527         loadmodel->num = count;
3528
3529         for (i = 0;i < count;i++, in++, out++)
3530         {
3531         }
3532 */
3533 }
3534
3535 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
3536 {
3537 /*
3538         d_t *in;
3539         m_t *out;
3540         int i, count;
3541
3542         in = (void *)(mod_base + l->fileofs);
3543         if (l->filelen % sizeof(*in))
3544                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
3545         count = l->filelen / sizeof(*in);
3546         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3547
3548         loadmodel-> = out;
3549         loadmodel->num = count;
3550
3551         for (i = 0;i < count;i++, in++, out++)
3552         {
3553         }
3554 */
3555 }
3556
3557 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
3558 {
3559 /*
3560         d_t *in;
3561         m_t *out;
3562         int i, count;
3563
3564         in = (void *)(mod_base + l->fileofs);
3565         if (l->filelen % sizeof(*in))
3566                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
3567         count = l->filelen / sizeof(*in);
3568         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3569
3570         loadmodel-> = out;
3571         loadmodel->num = count;
3572
3573         for (i = 0;i < count;i++, in++, out++)
3574         {
3575         }
3576 */
3577 }
3578
3579 static void Mod_Q2BSP_LoadAreas(lump_t *l)
3580 {
3581 /*
3582         d_t *in;
3583         m_t *out;
3584         int i, count;
3585
3586         in = (void *)(mod_base + l->fileofs);
3587         if (l->filelen % sizeof(*in))
3588                 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
3589         count = l->filelen / sizeof(*in);
3590         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3591
3592         loadmodel-> = out;
3593         loadmodel->num = count;
3594
3595         for (i = 0;i < count;i++, in++, out++)
3596         {
3597         }
3598 */
3599 }
3600
3601 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
3602 {
3603 /*
3604         d_t *in;
3605         m_t *out;
3606         int i, count;
3607
3608         in = (void *)(mod_base + l->fileofs);
3609         if (l->filelen % sizeof(*in))
3610                 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
3611         count = l->filelen / sizeof(*in);
3612         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3613
3614         loadmodel-> = out;
3615         loadmodel->num = count;
3616
3617         for (i = 0;i < count;i++, in++, out++)
3618         {
3619         }
3620 */
3621 }
3622
3623 static void Mod_Q2BSP_LoadModels(lump_t *l)
3624 {
3625 /*
3626         d_t *in;
3627         m_t *out;
3628         int i, count;
3629
3630         in = (void *)(mod_base + l->fileofs);
3631         if (l->filelen % sizeof(*in))
3632                 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
3633         count = l->filelen / sizeof(*in);
3634         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3635
3636         loadmodel-> = out;
3637         loadmodel->num = count;
3638
3639         for (i = 0;i < count;i++, in++, out++)
3640         {
3641         }
3642 */
3643 }
3644
3645 void static Mod_Q2BSP_Load(model_t *mod, void *buffer, void *bufferend)
3646 {
3647         int i;
3648         q2dheader_t *header;
3649
3650         Host_Error("Mod_Q2BSP_Load: not yet implemented\n");
3651
3652         mod->type = mod_brushq2;
3653
3654         header = (q2dheader_t *)buffer;
3655
3656         i = LittleLong(header->version);
3657         if (i != Q2BSPVERSION)
3658                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
3659         mod->brush.ishlbsp = false;
3660         mod->brush.ismcbsp = false;
3661         if (loadmodel->isworldmodel)
3662         {
3663                 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
3664                 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
3665         }
3666
3667         mod_base = (qbyte *)header;
3668
3669         // swap all the lumps
3670         for (i = 0;i < (int) sizeof(*header) / 4;i++)
3671                 ((int *)header)[i] = LittleLong(((int *)header)[i]);
3672
3673         // store which lightmap format to use
3674         mod->brushq1.lightmaprgba = r_lightmaprgba.integer;
3675
3676         Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
3677         Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
3678         Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
3679         Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
3680         Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
3681         Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
3682         Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
3683         Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
3684         Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
3685         Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
3686         Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
3687         Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
3688         Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
3689         Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
3690         Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
3691         Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
3692         Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
3693         // LordHavoc: must go last because this makes the submodels
3694         Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
3695 }
3696
3697 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents);
3698 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents);
3699
3700 static void Mod_Q3BSP_LoadEntities(lump_t *l)
3701 {
3702         const char *data;
3703         char key[128], value[4096];
3704         float v[3];
3705         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
3706         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
3707         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
3708         if (!l->filelen)
3709                 return;
3710         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen);
3711         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
3712         data = loadmodel->brush.entities;
3713         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
3714         if (data && COM_ParseToken(&data, false) && com_token[0] == '{')
3715         {
3716                 while (1)
3717                 {
3718                         if (!COM_ParseToken(&data, false))
3719                                 break; // error
3720                         if (com_token[0] == '}')
3721                                 break; // end of worldspawn
3722                         if (com_token[0] == '_')
3723                                 strcpy(key, com_token + 1);
3724                         else
3725                                 strcpy(key, com_token);
3726                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
3727                                 key[strlen(key)-1] = 0;
3728                         if (!COM_ParseToken(&data, false))
3729                                 break; // error
3730                         strcpy(value, com_token);
3731                         if (!strcmp("gridsize", key))
3732                         {
3733                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
3734                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
3735                         }
3736                 }
3737         }
3738 }
3739
3740 static void Mod_Q3BSP_LoadTextures(lump_t *l)
3741 {
3742         q3dtexture_t *in;
3743         texture_t *out;
3744         int i, count;
3745         int j, c;
3746         fssearch_t *search;
3747         char *f;
3748         const char *text;
3749         int flags, flags2, numparameters, passnumber;
3750         char shadername[Q3PATHLENGTH];
3751         char sky[Q3PATHLENGTH];
3752         char firstpasstexturename[Q3PATHLENGTH];
3753         char parameter[4][Q3PATHLENGTH];
3754
3755         in = (q3dtexture_t *)(mod_base + l->fileofs);
3756         if (l->filelen % sizeof(*in))
3757                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
3758         count = l->filelen / sizeof(*in);
3759         out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
3760
3761         loadmodel->data_textures = out;
3762         loadmodel->num_textures = count;
3763
3764         for (i = 0;i < count;i++, in++, out++)
3765         {
3766                 strlcpy (out->name, in->name, sizeof (out->name));
3767                 out->surfaceflags = LittleLong(in->surfaceflags);
3768                 out->supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in->contents));
3769                 out->surfaceparms = -1;
3770         }
3771
3772         // do a quick parse of shader files to get surfaceparms
3773         if ((search = FS_Search("scripts/*.shader", true, false)))
3774         {
3775                 for (i = 0;i < search->numfilenames;i++)
3776                 {
3777                         if ((f = (char *)FS_LoadFile(search->filenames[i], tempmempool, false)))
3778                         {
3779                                 text = f;
3780                                 while (COM_ParseToken(&text, false))
3781                                 {
3782                                         strlcpy (shadername, com_token, sizeof (shadername));
3783                                         flags = 0;
3784                                         flags2 = 0;
3785                                         sky[0] = 0;
3786                                         passnumber = 0;
3787                                         firstpasstexturename[0] = 0;
3788                                         if (COM_ParseToken(&text, false) && !strcasecmp(com_token, "{"))
3789                                         {
3790                                                 while (COM_ParseToken(&text, false))
3791                                                 {
3792                                                         if (!strcasecmp(com_token, "}"))
3793                                                                 break;
3794                                                         else if (!strcasecmp(com_token, "{"))
3795                                                         {
3796                                                                 while (COM_ParseToken(&text, false))
3797                                                                 {
3798                                                                         if (!strcasecmp(com_token, "}"))
3799                                                                                 break;
3800                                                                         if (!strcasecmp(com_token, "\n"))
3801                                                                                 continue;
3802                                                                         numparameters = 0;
3803                                                                         for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3804                                                                         {
3805                                                                                 if (j < 4)
3806                                                                                 {
3807                                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3808                                                                                         numparameters = j + 1;
3809                                                                                 }
3810                                                                                 if (!COM_ParseToken(&text, true))
3811                                                                                         break;
3812                                                                         }
3813                                                                         if (developer.integer >= 2)
3814                                                                         {
3815                                                                                 Con_Printf("%s %i: ", shadername, passnumber);
3816                                                                                 for (j = 0;j < numparameters;j++)
3817                                                                                         Con_Printf(" %s", parameter[j]);
3818                                                                                 Con_Print("\n");
3819                                                                         }
3820                                                                         if (passnumber == 0 && numparameters >= 1)
3821                                                                         {
3822                                                                                 if (!strcasecmp(parameter[0], "blendfunc") && (flags & Q3SURFACEPARM_TRANS))
3823                                                                                 {
3824                                                                                         if (numparameters == 2 && !strcasecmp(parameter[1], "add"))
3825                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3826                                                                                         else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_one") && !strcasecmp(parameter[2], "gl_one"))
3827                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3828                                                                                         else if (numparameters == 3 && !strcasecmp(parameter[1], "gl_src_alpha") && !strcasecmp(parameter[2], "gl_one"))
3829                                                                                                 flags2 |= Q3TEXTUREFLAG_ADDITIVE;
3830                                                                                 }
3831                                                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
3832                                                                                         strlcpy(firstpasstexturename, parameter[1], sizeof(firstpasstexturename));
3833                                                                                 else if (numparameters >= 3 && !strcasecmp(parameter[0], "animmap"))
3834                                                                                         strlcpy(firstpasstexturename, parameter[2], sizeof(firstpasstexturename));
3835                                                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
3836                                                                                         flags2 |= Q3TEXTUREFLAG_ALPHATEST;
3837                                                                         }
3838                                                                         // break out a level if it was }
3839                                                                         if (!strcasecmp(com_token, "}"))
3840                                                                                 break;
3841                                                                 }
3842                                                                 passnumber++;
3843                                                                 continue;
3844                                                         }
3845                                                         numparameters = 0;
3846                                                         for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
3847                                                         {
3848                                                                 if (j < 4)
3849                                                                 {
3850                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
3851                                                                         numparameters = j + 1;
3852                                                                 }
3853                                                                 if (!COM_ParseToken(&text, true))
3854                                                                         break;
3855                                                         }
3856                                                         if (i == 0 && !strcasecmp(com_token, "}"))
3857                                                                 break;
3858                                                         if (developer.integer >= 2)
3859                                                         {
3860                                                                 Con_Printf("%s: ", shadername);
3861                                                                 for (j = 0;j < numparameters;j++)
3862                                                                         Con_Printf(" %s", parameter[j]);
3863                                                                 Con_Print("\n");
3864                                                         }
3865                                                         if (numparameters < 1)
3866                                                                 continue;
3867                                                         if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
3868                                                         {
3869                                                                 if (!strcasecmp(parameter[1], "alphashadow"))
3870                                                                         flags |= Q3SURFACEPARM_ALPHASHADOW;
3871                                                                 else if (!strcasecmp(parameter[1], "areaportal"))
3872                                                                         flags |= Q3SURFACEPARM_AREAPORTAL;
3873                                                                 else if (!strcasecmp(parameter[1], "clusterportal"))
3874                                                                         flags |= Q3SURFACEPARM_CLUSTERPORTAL;
3875                                                                 else if (!strcasecmp(parameter[1], "detail"))
3876                                                                         flags |= Q3SURFACEPARM_DETAIL;
3877                                                                 else if (!strcasecmp(parameter[1], "donotenter"))
3878                                                                         flags |= Q3SURFACEPARM_DONOTENTER;
3879                                                                 else if (!strcasecmp(parameter[1], "fog"))
3880                                                                         flags |= Q3SURFACEPARM_FOG;
3881                                                                 else if (!strcasecmp(parameter[1], "lava"))
3882                                                                         flags |= Q3SURFACEPARM_LAVA;
3883                                                                 else if (!strcasecmp(parameter[1], "lightfilter"))
3884                                                                         flags |= Q3SURFACEPARM_LIGHTFILTER;
3885                                                                 else if (!strcasecmp(parameter[1], "metalsteps"))
3886                                                                         flags |= Q3SURFACEPARM_METALSTEPS;
3887                                                                 else if (!strcasecmp(parameter[1], "nodamage"))
3888                                                                         flags |= Q3SURFACEPARM_NODAMAGE;
3889                                                                 else if (!strcasecmp(parameter[1], "nodlight"))
3890                                                                         flags |= Q3SURFACEPARM_NODLIGHT;
3891                                                                 else if (!strcasecmp(parameter[1], "nodraw"))
3892                                                                         flags |= Q3SURFACEPARM_NODRAW;
3893                                                                 else if (!strcasecmp(parameter[1], "nodrop"))
3894                                                                         flags |= Q3SURFACEPARM_NODROP;
3895                                                                 else if (!strcasecmp(parameter[1], "noimpact"))
3896                                                                         flags |= Q3SURFACEPARM_NOIMPACT;
3897                                                                 else if (!strcasecmp(parameter[1], "nolightmap"))
3898                                                                         flags |= Q3SURFACEPARM_NOLIGHTMAP;
3899                                                                 else if (!strcasecmp(parameter[1], "nomarks"))
3900                                                                         flags |= Q3SURFACEPARM_NOMARKS;
3901                                                                 else if (!strcasecmp(parameter[1], "nomipmaps"))
3902                                                                         flags |= Q3SURFACEPARM_NOMIPMAPS;
3903                                                                 else if (!strcasecmp(parameter[1], "nonsolid"))
3904                                                                         flags |= Q3SURFACEPARM_NONSOLID;
3905                                                                 else if (!strcasecmp(parameter[1], "origin"))
3906                                                                         flags |= Q3SURFACEPARM_ORIGIN;
3907                                                                 else if (!strcasecmp(parameter[1], "playerclip"))
3908                                                                         flags |= Q3SURFACEPARM_PLAYERCLIP;
3909                                                                 else if (!strcasecmp(parameter[1], "sky"))
3910                                                                         flags |= Q3SURFACEPARM_SKY;
3911                                                                 else if (!strcasecmp(parameter[1], "slick"))
3912                                                                         flags |= Q3SURFACEPARM_SLICK;
3913                                                                 else if (!strcasecmp(parameter[1], "slime"))
3914                                                                         flags |= Q3SURFACEPARM_SLIME;
3915                                                                 else if (!strcasecmp(parameter[1], "structural"))
3916                                                                         flags |= Q3SURFACEPARM_STRUCTURAL;
3917                                                                 else if (!strcasecmp(parameter[1], "trans"))
3918                                                                         flags |= Q3SURFACEPARM_TRANS;
3919                                                                 else if (!strcasecmp(parameter[1], "water"))
3920                                                                         flags |= Q3SURFACEPARM_WATER;
3921                                                                 else if (!strcasecmp(parameter[1], "pointlight"))
3922                                                                         flags |= Q3SURFACEPARM_POINTLIGHT;
3923                                                                 else
3924                                                                         Con_Printf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[i], parameter[1]);
3925                                                         }
3926                                                         else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
3927                                                                 strlcpy(sky, parameter[1], sizeof(sky));
3928                                                         else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
3929                                                         {
3930                                                                 if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
3931                                                                         strlcpy(sky, parameter[1], sizeof(sky));
3932                                                         }
3933                                                         else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
3934                                                         {
3935                                                                 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
3936                                                                         flags2 |= Q3TEXTUREFLAG_TWOSIDED;
3937                                                         }
3938                                                         else if (!strcasecmp(parameter[0], "nomipmaps"))
3939                                                                 flags2 |= Q3TEXTUREFLAG_NOMIPMAPS;
3940                                                         else if (!strcasecmp(parameter[0], "nopicmip"))
3941                                                                 flags2 |= Q3TEXTUREFLAG_NOPICMIP;
3942                                                         else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
3943                                                         {
3944                                                                 if (!strcasecmp(parameter[1], "autosprite") && numparameters == 2)
3945                                                                         flags2 |= Q3TEXTUREFLAG_AUTOSPRITE;
3946                                                                 if (!strcasecmp(parameter[1], "autosprite2") && numparameters == 2)
3947                                                                         flags2 |= Q3TEXTUREFLAG_AUTOSPRITE2;
3948                                                         }
3949                                                 }
3950                                                 // add shader to list (shadername and flags)
3951                                                 // actually here we just poke into the texture settings
3952                                                 for (j = 0, out = loadmodel->data_textures;j < loadmodel->num_textures;j++, out++)
3953                                                 {
3954                                                         if (!strcasecmp(out->name, shadername))
3955                                                         {
3956                                                                 out->surfaceparms = flags;
3957                                                                 out->textureflags = flags2;
3958                                                                 out->basematerialflags = 0;
3959                                                                 if (out->surfaceparms & Q3SURFACEPARM_NODRAW)
3960                                                                         out->basematerialflags |= MATERIALFLAG_NODRAW;
3961                                                                 else if (out->surfaceparms & Q3SURFACEPARM_SKY)
3962                                                                         out->basematerialflags |= MATERIALFLAG_SKY;
3963                                                                 else if (out->surfaceparms & Q3SURFACEPARM_LAVA)
3964                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_FULLBRIGHT;
3965                                                                 else if (out->surfaceparms & Q3SURFACEPARM_SLIME)
3966                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3967                                                                 else if (out->surfaceparms & Q3SURFACEPARM_WATER)
3968                                                                         out->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_WATERALPHA;
3969                                                                 else
3970                                                                         out->basematerialflags |= MATERIALFLAG_WALL;
3971                                                                 if (out->textureflags & Q3TEXTUREFLAG_ALPHATEST)
3972                                                                 {
3973                                                                         // FIXME: support alpha test?
3974                                                                         out->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
3975                                                                 }
3976                                                                 else if (out->surfaceparms & Q3SURFACEPARM_TRANS)
3977                                                                 {
3978                                                                         if (out->textureflags & Q3TEXTUREFLAG_ADDITIVE)
3979                                                                                 out->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_TRANSPARENT;
3980                                                                         else
3981                                                                                 out->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_TRANSPARENT;
3982                                                                 }
3983                                                                 strlcpy(out->firstpasstexturename, firstpasstexturename, sizeof(out->firstpasstexturename));
3984                                                                 if ((flags & Q3SURFACEPARM_SKY) && sky[0])
3985                                                                 {
3986                                                                         // quake3 seems to append a _ to the skybox name, so this must do so as well
3987                                                                         dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", sky);
3988                                                                 }
3989                                                         }
3990                                                 }
3991                                         }
3992                                         else
3993                                         {
3994                                                 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[i], com_token);
3995                                                 goto parseerror;
3996                                         }
3997                                 }
3998 parseerror:
3999                                 Mem_Free(f);
4000                         }
4001                 }
4002         }
4003
4004         c = 0;
4005         for (j = 0, out = loadmodel->data_textures;j < loadmodel->num_textures;j++, out++)
4006         {
4007                 if (out->surfaceparms == -1)
4008                 {
4009                         c++;
4010                         Con_DPrintf("%s: No shader found for texture \"%s\"\n", loadmodel->name, out->name);
4011                         out->surfaceparms = 0;
4012                         if (out->surfaceflags & Q3SURFACEFLAG_NODRAW)
4013                                 out->basematerialflags |= MATERIALFLAG_NODRAW;
4014                         else if (out->surfaceflags & Q3SURFACEFLAG_SKY)
4015                                 out->basematerialflags |= MATERIALFLAG_SKY;
4016                         else
4017                                 out->basematerialflags |= MATERIALFLAG_WALL;
4018                         // these are defaults
4019                         //if (!strncmp(out->name, "textures/skies/", 15))
4020                         //      out->surfaceparms |= Q3SURFACEPARM_SKY;
4021                         //if (!strcmp(out->name, "caulk") || !strcmp(out->name, "common/caulk") || !strcmp(out->name, "textures/common/caulk")
4022                         // || !strcmp(out->name, "nodraw") || !strcmp(out->name, "common/nodraw") || !strcmp(out->name, "textures/common/nodraw"))
4023                         //      out->surfaceparms |= Q3SURFACEPARM_NODRAW;
4024                         //if (R_TextureHasAlpha(out->skin.base))
4025                         //      out->surfaceparms |= Q3SURFACEPARM_TRANS;
4026                 }
4027                 if (!Mod_LoadSkinFrame(&out->skin, out->name, (((out->textureflags & Q3TEXTUREFLAG_NOMIPMAPS) || (out->surfaceparms & Q3SURFACEPARM_NOMIPMAPS)) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | (out->textureflags & Q3TEXTUREFLAG_NOPICMIP ? 0 : TEXF_PICMIP), false, true))
4028                         if (!Mod_LoadSkinFrame(&out->skin, out->firstpasstexturename, (((out->textureflags & Q3TEXTUREFLAG_NOMIPMAPS) || (out->surfaceparms & Q3SURFACEPARM_NOMIPMAPS)) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | (out->textureflags & Q3TEXTUREFLAG_NOPICMIP ? 0 : TEXF_PICMIP), false, true))
4029                                 if (cls.state != ca_dedicated)
4030                                         Con_Printf("%s: texture loading for shader \"%s\" failed (first layer \"%s\" not found either)\n", loadmodel->name, out->name, out->firstpasstexturename);
4031                 // no animation
4032                 out->currentframe = out;
4033         }
4034         if (c)
4035                 Con_DPrintf("%s: %i textures missing shaders\n", loadmodel->name, c);
4036 }
4037
4038 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4039 {
4040         q3dplane_t *in;
4041         mplane_t *out;
4042         int i, count;
4043
4044         in = (q3dplane_t *)(mod_base + l->fileofs);
4045         if (l->filelen % sizeof(*in))
4046                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4047         count = l->filelen / sizeof(*in);
4048         out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4049
4050         loadmodel->brush.data_planes = out;
4051         loadmodel->brush.num_planes = count;
4052
4053         for (i = 0;i < count;i++, in++, out++)
4054         {
4055                 out->normal[0] = LittleFloat(in->normal[0]);
4056                 out->normal[1] = LittleFloat(in->normal[1]);
4057                 out->normal[2] = LittleFloat(in->normal[2]);
4058                 out->dist = LittleFloat(in->dist);
4059                 PlaneClassify(out);
4060         }
4061 }
4062
4063 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4064 {
4065         q3dbrushside_t *in;
4066         q3mbrushside_t *out;
4067         int i, n, count;
4068
4069         in = (q3dbrushside_t *)(mod_base + l->fileofs);
4070         if (l->filelen % sizeof(*in))
4071                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4072         count = l->filelen / sizeof(*in);
4073         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4074
4075         loadmodel->brush.data_brushsides = out;
4076         loadmodel->brush.num_brushsides = count;
4077
4078         for (i = 0;i < count;i++, in++, out++)
4079         {
4080                 n = LittleLong(in->planeindex);
4081                 if (n < 0 || n >= loadmodel->brush.num_planes)
4082                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
4083                 out->plane = loadmodel->brush.data_planes + n;
4084                 n = LittleLong(in->textureindex);
4085                 if (n < 0 || n >= loadmodel->num_textures)
4086                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)\n", n, loadmodel->num_textures);
4087                 out->texture = loadmodel->data_textures + n;
4088         }
4089 }
4090
4091 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4092 {
4093         q3dbrush_t *in;
4094         q3mbrush_t *out;
4095         int i, j, n, c, count, maxplanes;
4096         mplane_t *planes;
4097
4098         in = (q3dbrush_t *)(mod_base + l->fileofs);
4099         if (l->filelen % sizeof(*in))
4100                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4101         count = l->filelen / sizeof(*in);
4102         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4103
4104         loadmodel->brush.data_brushes = out;
4105         loadmodel->brush.num_brushes = count;
4106
4107         maxplanes = 0;
4108         planes = NULL;
4109
4110         for (i = 0;i < count;i++, in++, out++)
4111         {
4112                 n = LittleLong(in->firstbrushside);
4113                 c = LittleLong(in->numbrushsides);
4114                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4115                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)\n", n, n + c, loadmodel->brush.num_brushsides);
4116                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4117                 out->numbrushsides = c;
4118                 n = LittleLong(in->textureindex);
4119                 if (n < 0 || n >= loadmodel->num_textures)
4120                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)\n", n, loadmodel->num_textures);
4121                 out->texture = loadmodel->data_textures + n;
4122
4123                 // make a list of mplane_t structs to construct a colbrush from
4124                 if (maxplanes < out->numbrushsides)
4125                 {
4126                         maxplanes = out->numbrushsides;
4127                         if (planes)
4128                                 Mem_Free(planes);
4129                         planes = (mplane_t *)Mem_Alloc(tempmempool, sizeof(mplane_t) * maxplanes);
4130                 }
4131                 for (j = 0;j < out->numbrushsides;j++)
4132                 {
4133                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4134                         planes[j].dist = out->firstbrushside[j].plane->dist;
4135                 }
4136                 // make the colbrush from the planes
4137                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents);
4138         }
4139         if (planes)
4140                 Mem_Free(planes);
4141 }
4142
4143 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4144 {
4145         q3deffect_t *in;
4146         q3deffect_t *out;
4147         int i, n, count;
4148
4149         in = (q3deffect_t *)(mod_base + l->fileofs);
4150         if (l->filelen % sizeof(*in))
4151                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4152         count = l->filelen / sizeof(*in);
4153         out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4154
4155         loadmodel->brushq3.data_effects = out;
4156         loadmodel->brushq3.num_effects = count;
4157
4158         for (i = 0;i < count;i++, in++, out++)
4159         {
4160                 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4161                 n = LittleLong(in->brushindex);
4162                 if (n >= loadmodel->brush.num_brushes)
4163                 {
4164                         Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4165                         n = -1;
4166                 }
4167                 out->brushindex = n;
4168                 out->unknown = LittleLong(in->unknown);
4169         }
4170 }
4171
4172 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4173 {
4174         q3dvertex_t *in;
4175         int i, count;
4176
4177         in = (q3dvertex_t *)(mod_base + l->fileofs);
4178         if (l->filelen % sizeof(*in))
4179                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4180         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4181         loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 2 + 2 + 4)));
4182         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_vertex3f + count * 3;
4183         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4184         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4185
4186         for (i = 0;i < count;i++, in++)
4187         {
4188                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4189                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4190                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4191                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4192                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4193                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4194                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4195                 // svector/tvector are calculated later in face loading
4196                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4197                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4198                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4199                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4200         }
4201 }
4202
4203 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4204 {
4205         int *in;
4206         int *out;
4207         int i, count;
4208
4209         in = (int *)(mod_base + l->fileofs);
4210         if (l->filelen % sizeof(int[3]))
4211                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4212         count = l->filelen / sizeof(*in);
4213         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4214
4215         loadmodel->brushq3.num_triangles = count / 3;
4216         loadmodel->brushq3.data_element3i = out;
4217
4218         for (i = 0;i < count;i++, in++, out++)
4219         {
4220                 *out = LittleLong(*in);
4221                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4222                 {
4223                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4224                         *out = 0;
4225                 }
4226         }
4227 }
4228
4229 static void Mod_Q3BSP_LoadLightmaps(lump_t *l)
4230 {
4231         q3dlightmap_t *in;
4232         rtexture_t **out;
4233         int i, count;
4234
4235         if (!l->filelen)
4236                 return;
4237         in = (q3dlightmap_t *)(mod_base + l->fileofs);
4238         if (l->filelen % sizeof(*in))
4239                 Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4240         count = l->filelen / sizeof(*in);
4241         out = (rtexture_t **)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4242
4243         loadmodel->brushq3.data_lightmaps = out;
4244         loadmodel->brushq3.num_lightmaps = count;
4245
4246         for (i = 0;i < count;i++, in++, out++)
4247                 *out = R_LoadTexture2D(loadmodel->texturepool, va("lightmap%04i", i), 128, 128, in->rgb, TEXTYPE_RGB, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
4248 }
4249
4250 static void Mod_Q3BSP_LoadFaces(lump_t *l)
4251 {
4252         q3dface_t *in, *oldin;
4253         msurface_t *out, *oldout;
4254         int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshnum, meshvertices, meshtriangles, numvertices, numtriangles;
4255         //int *originalelement3i;
4256         //int *originalneighbor3i;
4257         float *originalvertex3f;
4258         //float *originalsvector3f;
4259         //float *originaltvector3f;
4260         //float *originalnormal3f;
4261         float *originalcolor4f;
4262         float *originaltexcoordtexture2f;
4263         float *originaltexcoordlightmap2f;
4264         float *v;
4265         surfmesh_t *mesh, *tempmeshlist[1024];
4266
4267         in = (q3dface_t *)(mod_base + l->fileofs);
4268         if (l->filelen % sizeof(*in))
4269                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4270         count = l->filelen / sizeof(*in);
4271         out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4272
4273         loadmodel->data_surfaces = out;
4274         loadmodel->num_surfaces = count;
4275
4276         i = 0;
4277         for (meshnum = 0;i < count;meshnum++)
4278         {
4279                 oldi = i;
4280                 oldin = in;
4281                 oldout = out;
4282                 meshvertices = 0;
4283                 meshtriangles = 0;
4284                 for (;i < count;i++, in++, out++)
4285                 {
4286                         // check face type first
4287                         type = LittleLong(in->type);
4288                         if (type != Q3FACETYPE_POLYGON
4289                          && type != Q3FACETYPE_PATCH
4290                          && type != Q3FACETYPE_MESH
4291                          && type != Q3FACETYPE_FLARE)
4292                         {
4293                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
4294                                 continue;
4295                         }
4296
4297                         n = LittleLong(in->textureindex);
4298                         if (n < 0 || n >= loadmodel->num_textures)
4299                         {
4300                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
4301                                 continue;
4302                         }
4303                         out->texture = loadmodel->data_textures + n;
4304                         n = LittleLong(in->effectindex);
4305                         if (n < -1 || n >= loadmodel->brushq3.num_effects)
4306                         {
4307                                 if (developer.integer >= 2)
4308                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
4309                                 n = -1;
4310                         }
4311                         if (n == -1)
4312                                 out->effect = NULL;
4313                         else
4314                                 out->effect = loadmodel->brushq3.data_effects + n;
4315                         n = LittleLong(in->lightmapindex);
4316                         if (n >= loadmodel->brushq3.num_lightmaps)
4317                         {
4318                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_lightmaps);
4319                                 n = -1;
4320                         }
4321                         else if (n < 0)
4322                                 n = -1;
4323                         if (n == -1)
4324                                 out->lightmaptexture = NULL;
4325                         else
4326                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n];
4327
4328                         firstvertex = LittleLong(in->firstvertex);
4329                         numvertices = LittleLong(in->numvertices);
4330                         firstelement = LittleLong(in->firstelement);
4331                         numtriangles = LittleLong(in->numelements) / 3;
4332                         if (numtriangles * 3 != LittleLong(in->numelements))
4333                         {
4334                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): numelements %i is not a multiple of 3\n", i, out->texture->name, LittleLong(in->numelements));
4335                                 continue;
4336                         }
4337                         if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
4338                         {
4339                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid vertex range %i : %i (%i vertices)\n", i, out->texture->name, firstvertex, firstvertex + numvertices, loadmodel->brushq3.num_vertices);
4340                                 continue;
4341                         }
4342                         if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
4343                         {
4344                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid element range %i : %i (%i elements)\n", i, out->texture->name, firstelement, firstelement + numtriangles * 3, loadmodel->brushq3.num_triangles * 3);
4345                                 continue;
4346                         }
4347                         switch(type)
4348                         {
4349                         case Q3FACETYPE_POLYGON:
4350                         case Q3FACETYPE_MESH:
4351                                 // no processing necessary
4352                                 break;
4353                         case Q3FACETYPE_PATCH:
4354                                 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4355                                 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4356                                 if (numvertices != (patchsize[0] * patchsize[1]) || patchsize[0] < 3 || patchsize[1] < 3 || !(patchsize[0] & 1) || !(patchsize[1] & 1) || patchsize[0] * patchsize[1] >= min(r_subdivisions_maxvertices.integer, r_subdivisions_collision_maxvertices.integer))
4357                                 {
4358                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
4359                                         continue;
4360                                 }
4361                                 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4362                                 // convert patch to Q3FACETYPE_MESH
4363                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4364                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4365                                 // bound to user settings
4366                                 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4367                                 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4368                                 // bound to sanity settings
4369                                 xtess = bound(1, xtess, 1024);
4370                                 ytess = bound(1, ytess, 1024);
4371                                 // bound to user limit on vertices
4372                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4373                                 {
4374                                         if (xtess > ytess)
4375                                                 xtess--;
4376                                         else
4377                                                 ytess--;
4378                                 }
4379                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4380                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4381                                 numvertices = finalwidth * finalheight;
4382                                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4383                                 break;
4384                         case Q3FACETYPE_FLARE:
4385                                 if (developer.integer >= 2)
4386                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
4387                                 // don't render it
4388                                 continue;
4389                         }
4390                         out->num_vertices = numvertices;
4391                         out->num_triangles = numtriangles;
4392                         if (meshvertices + out->num_vertices > 65536)
4393                                 break;
4394                         meshvertices += out->num_vertices;
4395                         meshtriangles += out->num_triangles;
4396                 }
4397
4398                 i = oldi;
4399                 in = oldin;
4400                 out = oldout;
4401                 mesh = tempmeshlist[meshnum] = Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
4402                 meshvertices = 0;
4403                 meshtriangles = 0;
4404                 for (;i < count && meshvertices + out->num_vertices <= mesh->num_vertices;i++, in++, out++)
4405                 {
4406                         if (out->num_vertices < 3 || out->num_triangles < 1)
4407                                 continue;
4408
4409                         type = LittleLong(in->type);
4410                         firstvertex = LittleLong(in->firstvertex);
4411                         firstelement = LittleLong(in->firstelement);
4412                         out->groupmesh = mesh;
4413                         out->num_firstvertex = meshvertices;
4414                         out->num_firsttriangle = meshtriangles;
4415                         switch(type)
4416                         {
4417                         case Q3FACETYPE_POLYGON:
4418                         case Q3FACETYPE_MESH:
4419                                 // no processing necessary
4420                                 for (j = 0;j < out->num_vertices;j++)
4421                                 {
4422                                         (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
4423                                         (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
4424                                         (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
4425                                         (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
4426                                         (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
4427                                         (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
4428                                         (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
4429                                         (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
4430                                         (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
4431                                         (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
4432                                         (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
4433                                 }
4434                                 for (j = 0;j < out->num_triangles*3;j++)
4435                                         (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
4436                                 break;
4437                         case Q3FACETYPE_PATCH:
4438                                 patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
4439                                 patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
4440                                 originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
4441                                 originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
4442                                 originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
4443                                 originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
4444                                 // convert patch to Q3FACETYPE_MESH
4445                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4446                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
4447                                 // bound to user settings
4448                                 xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
4449                                 ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
4450                                 // bound to sanity settings
4451                                 xtess = bound(1, xtess, 1024);
4452                                 ytess = bound(1, ytess, 1024);
4453                                 // bound to user limit on vertices
4454                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_maxvertices.integer, 262144))
4455                                 {
4456                                         if (xtess > ytess)
4457                                                 xtess--;
4458                                         else
4459                                                 ytess--;
4460                                 }
4461                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4462                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4463                                 finalvertices = finalwidth * finalheight;
4464                                 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4465                                 type = Q3FACETYPE_MESH;
4466                                 // generate geometry
4467                                 // (note: normals are skipped because they get recalculated)
4468                                 Q3PatchTesselateFloat(3, sizeof(float[3]), (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4469                                 Q3PatchTesselateFloat(2, sizeof(float[2]), (out->groupmesh->data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
4470                                 Q3PatchTesselateFloat(2, sizeof(float[2]), (out->groupmesh->data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
4471                                 Q3PatchTesselateFloat(4, sizeof(float[4]), (out->groupmesh->data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
4472                                 Q3PatchTriangleElements((out->groupmesh->data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
4473                                 out->num_triangles = Mod_RemoveDegenerateTriangles(out->num_triangles, (out->groupmesh->data_element3i + 3 * out->num_firsttriangle), (out->groupmesh->data_element3i + 3 * out->num_firsttriangle), out->groupmesh->data_vertex3f);
4474                                 if (developer.integer >= 2)
4475                                 {
4476                                         if (out->num_triangles < finaltriangles)
4477                                                 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->num_vertices, finaltriangles, finaltriangles - out->num_triangles, out->num_triangles);
4478                                         else
4479                                                 Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->num_vertices, out->num_triangles);
4480                                 }
4481                                 // q3map does not put in collision brushes for curves... ugh
4482                                 // build the lower quality collision geometry
4483                                 xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4484                                 ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
4485                                 // bound to user settings
4486                                 xtess = bound(r_subdivisions_collision_mintess.integer, xtess, r_subdivisions_collision_maxtess.integer);
4487                                 ytess = bound(r_subdivisions_collision_mintess.integer, ytess, r_subdivisions_collision_maxtess.integer);
4488                                 // bound to sanity settings
4489                                 xtess = bound(1, xtess, 1024);
4490                                 ytess = bound(1, ytess, 1024);
4491                                 // bound to user limit on vertices
4492                                 while ((xtess > 1 || ytess > 1) && (((patchsize[0] - 1) * xtess) + 1) * (((patchsize[1] - 1) * ytess) + 1) > min(r_subdivisions_collision_maxvertices.integer, 262144))
4493                                 {
4494                                         if (xtess > ytess)
4495                                                 xtess--;
4496                                         else
4497                                                 ytess--;
4498                                 }
4499                                 finalwidth = ((patchsize[0] - 1) * xtess) + 1;
4500                                 finalheight = ((patchsize[1] - 1) * ytess) + 1;
4501                                 finalvertices = finalwidth * finalheight;
4502                                 finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
4503
4504                                 out->data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
4505                                 out->data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
4506                                 out->num_collisionvertices = finalvertices;
4507                                 out->num_collisiontriangles = finaltriangles;
4508                                 Q3PatchTesselateFloat(3, sizeof(float[3]), out->data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
4509                                 Q3PatchTriangleElements(out->data_collisionelement3i, finalwidth, finalheight, 0);
4510
4511                                 //Mod_SnapVertices(3, out->num_vertices, (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), 0.25);
4512                                 Mod_SnapVertices(3, out->num_collisionvertices, out->data_collisionvertex3f, 1);
4513
4514                                 oldnumtriangles = out->num_triangles;
4515                                 oldnumtriangles2 = out->num_collisiontriangles;
4516                                 out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(out->num_collisiontriangles, out->data_collisionelement3i, out->data_collisionelement3i, out->data_collisionvertex3f);
4517                                 if (developer.integer)
4518                                         Con_Printf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
4519                                 break;
4520                         default:
4521                                 break;
4522                         }
4523                         meshvertices += out->num_vertices;
4524                         meshtriangles += out->num_triangles;
4525                         for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
4526                                 if ((out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
4527                                         invalidelements++;
4528                         if (invalidelements)
4529                         {
4530                                 Con_Printf("Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
4531                                 for (j = 0;j < out->num_triangles * 3;j++)
4532                                 {
4533                                         Con_Printf(" %i", (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
4534                                         if ((out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
4535                                                 (out->groupmesh->data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
4536                                 }
4537                                 Con_Print("\n");
4538                         }
4539                         // for per pixel lighting
4540                         Mod_BuildTextureVectorsAndNormals(out->num_firstvertex, out->num_vertices, out->num_triangles, out->groupmesh->data_vertex3f, out->groupmesh->data_texcoordtexture2f, (out->groupmesh->data_element3i + 3 * out->num_firsttriangle), out->groupmesh->data_svector3f, out->groupmesh->data_tvector3f, out->groupmesh->data_normal3f, true);
4541                         // calculate a bounding box
4542                         VectorClear(out->mins);
4543                         VectorClear(out->maxs);
4544                         if (out->num_vertices)
4545                         {
4546                                 VectorCopy((out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), out->mins);
4547                                 VectorCopy((out->groupmesh->data_vertex3f + 3 * out->num_firstvertex), out->maxs);
4548                                 for (j = 1, v = (out->groupmesh->data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
4549                                 {
4550                                         out->mins[0] = min(out->mins[0], v[0]);
4551                                         out->maxs[0] = max(out->maxs[0], v[0]);
4552                                         out->mins[1] = min(out->mins[1], v[1]);
4553                                         out->maxs[1] = max(out->maxs[1], v[1]);
4554                                         out->mins[2] = min(out->mins[2], v[2]);
4555                                         out->maxs[2] = max(out->maxs[2], v[2]);
4556                                 }
4557                                 out->mins[0] -= 1.0f;
4558                                 out->mins[1] -= 1.0f;
4559                                 out->mins[2] -= 1.0f;
4560                                 out->maxs[0] += 1.0f;
4561                                 out->maxs[1] += 1.0f;
4562                                 out->maxs[2] += 1.0f;
4563                         }
4564                         // set lightmap styles for consistency with q1bsp
4565                         //out->lightmapinfo->styles[0] = 0;
4566                         //out->lightmapinfo->styles[1] = 255;
4567                         //out->lightmapinfo->styles[2] = 255;
4568                         //out->lightmapinfo->styles[3] = 255;
4569                 }
4570         }
4571
4572         // now store the completed list of meshes
4573         loadmodel->nummeshes = meshnum;
4574         if (loadmodel->nummeshes)
4575         {
4576                 loadmodel->meshlist = (surfmesh_t **)Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4577                 memcpy(loadmodel->meshlist, tempmeshlist, sizeof(surfmesh_t *) * loadmodel->nummeshes);
4578         }
4579
4580         // free the no longer needed vertex data
4581         loadmodel->brushq3.num_vertices = 0;
4582         Mem_Free(loadmodel->brushq3.data_vertex3f);
4583         loadmodel->brushq3.data_vertex3f = NULL;
4584         loadmodel->brushq3.data_texcoordtexture2f = NULL;
4585         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
4586         loadmodel->brushq3.data_color4f = NULL;
4587         // free the no longer needed triangle data
4588         loadmodel->brushq3.num_triangles = 0;
4589         Mem_Free(loadmodel->brushq3.data_element3i);
4590         loadmodel->brushq3.data_element3i = NULL;
4591 }
4592
4593 static void Mod_Q3BSP_LoadModels(lump_t *l)
4594 {
4595         q3dmodel_t *in;
4596         q3dmodel_t *out;
4597         int i, j, n, c, count;
4598
4599         in = (q3dmodel_t *)(mod_base + l->fileofs);
4600         if (l->filelen % sizeof(*in))
4601                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
4602         count = l->filelen / sizeof(*in);
4603         out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4604
4605         loadmodel->brushq3.data_models = out;
4606         loadmodel->brushq3.num_models = count;
4607
4608         for (i = 0;i < count;i++, in++, out++)
4609         {
4610                 for (j = 0;j < 3;j++)
4611                 {
4612                         out->mins[j] = LittleFloat(in->mins[j]);
4613                         out->maxs[j] = LittleFloat(in->maxs[j]);
4614                 }
4615                 n = LittleLong(in->firstface);
4616                 c = LittleLong(in->numfaces);
4617                 if (n < 0 || n + c > loadmodel->num_surfaces)
4618                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)\n", n, n + c, loadmodel->num_surfaces);
4619                 out->firstface = n;
4620                 out->numfaces = c;
4621                 n = LittleLong(in->firstbrush);
4622                 c = LittleLong(in->numbrushes);
4623                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
4624                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)\n", n, n + c, loadmodel->brush.num_brushes);
4625                 out->firstbrush = n;
4626                 out->numbrushes = c;
4627         }
4628 }
4629
4630 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
4631 {
4632         int *in;
4633         int *out;
4634         int i, n, count;
4635
4636         in = (int *)(mod_base + l->fileofs);
4637         if (l->filelen % sizeof(*in))
4638                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4639         count = l->filelen / sizeof(*in);
4640         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4641
4642         loadmodel->brush.data_leafbrushes = out;
4643         loadmodel->brush.num_leafbrushes = count;
4644
4645         for (i = 0;i < count;i++, in++, out++)
4646         {
4647                 n = LittleLong(*in);
4648                 if (n < 0 || n >= loadmodel->brush.num_brushes)
4649                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)\n", n, loadmodel->brush.num_brushes);
4650                 *out = n;
4651         }
4652 }
4653
4654 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
4655 {
4656         int *in;
4657         int *out;
4658         int i, n, count;
4659
4660         in = (int *)(mod_base + l->fileofs);
4661         if (l->filelen % sizeof(*in))
4662                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4663         count = l->filelen / sizeof(*in);
4664         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4665
4666         loadmodel->brush.data_leafsurfaces = out;
4667         loadmodel->brush.num_leafsurfaces = count;
4668
4669         for (i = 0;i < count;i++, in++, out++)
4670         {
4671                 n = LittleLong(*in);
4672                 if (n < 0 || n >= loadmodel->num_surfaces)
4673                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)\n", n, loadmodel->num_surfaces);
4674                 *out = n;
4675         }
4676 }
4677
4678 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
4679 {
4680         q3dleaf_t *in;
4681         mleaf_t *out;
4682         int i, j, n, c, count;
4683
4684         in = (q3dleaf_t *)(mod_base + l->fileofs);
4685         if (l->filelen % sizeof(*in))
4686                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4687         count = l->filelen / sizeof(*in);
4688         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4689
4690         loadmodel->brush.data_leafs = out;
4691         loadmodel->brush.num_leafs = count;
4692
4693         for (i = 0;i < count;i++, in++, out++)
4694         {
4695                 out->parent = NULL;
4696                 out->plane = NULL;
4697                 out->clusterindex = LittleLong(in->clusterindex);
4698                 out->areaindex = LittleLong(in->areaindex);
4699                 for (j = 0;j < 3;j++)
4700                 {
4701                         // yes the mins/maxs are ints
4702                         out->mins[j] = LittleLong(in->mins[j]) - 1;
4703                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4704                 }
4705                 n = LittleLong(in->firstleafface);
4706                 c = LittleLong(in->numleaffaces);
4707                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
4708                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)\n", n, n + c, loadmodel->brush.num_leafsurfaces);
4709                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
4710                 out->numleafsurfaces = c;
4711                 n = LittleLong(in->firstleafbrush);
4712                 c = LittleLong(in->numleafbrushes);
4713                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
4714                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)\n", n, n + c, loadmodel->brush.num_leafbrushes);
4715                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
4716                 out->numleafbrushes = c;
4717         }
4718 }
4719
4720 static void Mod_Q3BSP_LoadNodes(lump_t *l)
4721 {
4722         q3dnode_t *in;
4723         mnode_t *out;
4724         int i, j, n, count;
4725
4726         in = (q3dnode_t *)(mod_base + l->fileofs);
4727         if (l->filelen % sizeof(*in))
4728                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4729         count = l->filelen / sizeof(*in);
4730         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4731
4732         loadmodel->brush.data_nodes = out;
4733         loadmodel->brush.num_nodes = count;
4734
4735         for (i = 0;i < count;i++, in++, out++)
4736         {
4737                 out->parent = NULL;
4738                 n = LittleLong(in->planeindex);
4739                 if (n < 0 || n >= loadmodel->brush.num_planes)
4740                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)\n", n, loadmodel->brush.num_planes);
4741                 out->plane = loadmodel->brush.data_planes + n;
4742                 for (j = 0;j < 2;j++)
4743                 {
4744                         n = LittleLong(in->childrenindex[j]);
4745                         if (n >= 0)
4746                         {
4747                                 if (n >= loadmodel->brush.num_nodes)
4748                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)\n", n, loadmodel->brush.num_nodes);
4749                                 out->children[j] = loadmodel->brush.data_nodes + n;
4750                         }
4751                         else
4752                         {
4753                                 n = -1 - n;
4754                                 if (n >= loadmodel->brush.num_leafs)
4755                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)\n", n, loadmodel->brush.num_leafs);
4756                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
4757                         }
4758                 }
4759                 for (j = 0;j < 3;j++)
4760                 {
4761                         // yes the mins/maxs are ints
4762                         out->mins[j] = LittleLong(in->mins[j]) - 1;
4763                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
4764                 }
4765         }
4766
4767         // set the parent pointers
4768         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
4769 }
4770
4771 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
4772 {
4773         q3dlightgrid_t *in;
4774         q3dlightgrid_t *out;
4775         int count;
4776
4777         in = (q3dlightgrid_t *)(mod_base + l->fileofs);
4778         if (l->filelen % sizeof(*in))
4779                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
4780         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
4781         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
4782         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
4783         loadmodel->brushq3.num_lightgrid_imins[0] = ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4784         loadmodel->brushq3.num_lightgrid_imins[1] = ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4785         loadmodel->brushq3.num_lightgrid_imins[2] = ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4786         loadmodel->brushq3.num_lightgrid_imaxs[0] = floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
4787         loadmodel->brushq3.num_lightgrid_imaxs[1] = floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
4788         loadmodel->brushq3.num_lightgrid_imaxs[2] = floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
4789         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
4790         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
4791         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
4792         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
4793         Matrix4x4_CreateScale3(&loadmodel->brushq3.num_lightgrid_indexfromworld, loadmodel->brushq3.num_lightgrid_scale[0], loadmodel->brushq3.num_lightgrid_scale[1], loadmodel->brushq3.num_lightgrid_scale[2]);
4794         Matrix4x4_ConcatTranslate(&loadmodel->brushq3.num_lightgrid_indexfromworld, -loadmodel->brushq3.num_lightgrid_imins[0] * loadmodel->brushq3.num_lightgrid_cellsize[0], -loadmodel->brushq3.num_lightgrid_imins[1] * loadmodel->brushq3.num_lightgrid_cellsize[1], -loadmodel->brushq3.num_lightgrid_imins[2] * loadmodel->brushq3.num_lightgrid_cellsize[2]);
4795
4796         // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
4797         if (l->filelen)
4798         {
4799                 if (l->filelen < count * (int)sizeof(*in))
4800                         Host_Error("Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)\n", l->filelen, count * sizeof(*in), loadmodel->brushq3.num_lightgrid_dimensions[0], loadmodel->brushq3.num_lightgrid_dimensions[1], loadmodel->brushq3.num_lightgrid_dimensions[2]);
4801                 if (l->filelen != count * (int)sizeof(*in))
4802                         Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", count * sizeof(*in), l->filelen);
4803                 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4804                 loadmodel->brushq3.data_lightgrid = out;
4805                 loadmodel->brushq3.num_lightgrid = count;
4806                 // no swapping or validation necessary
4807                 memcpy(out, in, count * (int)sizeof(*out));
4808         }
4809 }
4810
4811 static void Mod_Q3BSP_LoadPVS(lump_t *l)
4812 {
4813         q3dpvs_t *in;
4814         int totalchains;
4815
4816         if (l->filelen == 0)
4817         {
4818                 int i;
4819                 // unvised maps often have cluster indices even without pvs, so check
4820                 // leafs to find real number of clusters
4821                 loadmodel->brush.num_pvsclusters = 1;
4822                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
4823                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
4824
4825                 // create clusters
4826                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
4827                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4828                 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
4829                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
4830                 return;
4831         }
4832
4833         in = (q3dpvs_t *)(mod_base + l->fileofs);
4834         if (l->filelen < 9)
4835                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
4836
4837         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
4838         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
4839         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
4840                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8\n", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
4841         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
4842         if (l->filelen < totalchains + (int)sizeof(*in))
4843                 Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)\n", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, totalchains + sizeof(*in), l->filelen);
4844
4845         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
4846         memcpy(loadmodel->brush.data_pvsclusters, (qbyte *)(in + 1), totalchains);
4847 }
4848
4849 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
4850 {
4851         int i, j, k, index[3];
4852         float transformed[3], blend1, blend2, blend, yaw, pitch, sinpitch;
4853         q3dlightgrid_t *a, *s;
4854         if (!model->brushq3.num_lightgrid)
4855         {
4856                 ambientcolor[0] = 1;
4857                 ambientcolor[1] = 1;
4858                 ambientcolor[2] = 1;
4859                 return;
4860         }
4861         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
4862         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
4863         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
4864         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
4865         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
4866         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
4867         index[0] = (int)floor(transformed[0]);
4868         index[1] = (int)floor(transformed[1]);
4869         index[2] = (int)floor(transformed[2]);
4870         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
4871         // now lerp the values
4872         VectorClear(diffusenormal);
4873         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
4874         for (k = 0;k < 2;k++)
4875         {
4876                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
4877                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
4878                         continue;
4879                 for (j = 0;j < 2;j++)
4880                 {
4881                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
4882                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
4883                                 continue;
4884                         for (i = 0;i < 2;i++)
4885                         {
4886                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0])));
4887                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
4888                                         continue;
4889                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
4890                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
4891                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
4892                                 pitch = s->diffusepitch * M_PI / 128;
4893                                 yaw = s->diffuseyaw * M_PI / 128;
4894                                 sinpitch = sin(pitch);
4895                                 diffusenormal[0] += blend * (cos(yaw) * sinpitch);
4896                                 diffusenormal[1] += blend * (sin(yaw) * sinpitch);
4897                                 diffusenormal[2] += blend * (cos(pitch));
4898                                 //Con_Printf("blend %f: ambient %i %i %i, diffuse %i %i %i, diffusepitch %i diffuseyaw %i (%f %f, normal %f %f %f)\n", blend, s->ambientrgb[0], s->ambientrgb[1], s->ambientrgb[2], s->diffusergb[0], s->diffusergb[1], s->diffusergb[2], s->diffusepitch, s->diffuseyaw, pitch, yaw, (cos(yaw) * cospitch), (sin(yaw) * cospitch), (-sin(pitch)));
4899                         }
4900                 }
4901         }
4902         VectorNormalize(diffusenormal);
4903         //Con_Printf("result: ambient %f %f %f diffuse %f %f %f diffusenormal %f %f %f\n", ambientcolor[0], ambientcolor[1], ambientcolor[2], diffusecolor[0], diffusecolor[1], diffusecolor[2], diffusenormal[0], diffusenormal[1], diffusenormal[2]);
4904 }
4905
4906 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const vec3_t point, int markframe)
4907 {
4908         int i;
4909         mleaf_t *leaf;
4910         colbrushf_t *brush;
4911         // find which leaf the point is in
4912         while (node->plane)
4913                 node = node->children[DotProduct(point, node->plane->normal) < node->plane->dist];
4914         // point trace the brushes
4915         leaf = (mleaf_t *)node;
4916         for (i = 0;i < leaf->numleafbrushes;i++)
4917         {
4918                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4919                 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
4920                 {
4921                         brush->markframe = markframe;
4922                         Collision_TracePointBrushFloat(trace, point, brush);
4923                 }
4924         }
4925         // can't do point traces on curves (they have no thickness)
4926 }
4927
4928 static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const vec3_t start, const vec3_t end, vec_t startfrac, vec_t endfrac, const vec3_t linestart, const vec3_t lineend, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
4929 {
4930         int i, startside, endside;
4931         float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
4932         mleaf_t *leaf;
4933         msurface_t *surface;
4934         colbrushf_t *brush;
4935         if (startfrac > trace->realfraction)
4936                 return;
4937         // note: all line fragments past first impact fraction are ignored
4938         if (VectorCompare(start, end))
4939         {
4940                 // find which leaf the point is in
4941                 while (node->plane)
4942                         node = node->children[DotProduct(start, node->plane->normal) < node->plane->dist];
4943         }
4944         else
4945         {
4946                 // find which nodes the line is in and recurse for them
4947                 while (node->plane)
4948                 {
4949                         // recurse down node sides
4950                         dist1 = PlaneDiff(start, node->plane);
4951                         dist2 = PlaneDiff(end, node->plane);
4952                         startside = dist1 < 0;
4953                         endside = dist2 < 0;
4954                         if (startside == endside)
4955                         {
4956                                 // most of the time the line fragment is on one side of the plane
4957                                 node = node->children[startside];
4958                         }
4959                         else
4960                         {
4961                                 // line crosses node plane, split the line
4962                                 midfrac = dist1 / (dist1 - dist2);
4963                                 VectorLerp(start, midfrac, end, mid);
4964                                 // take the near side first
4965                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4966                                 if (midfrac <= trace->realfraction)
4967                                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
4968                                 return;
4969                         }
4970                 }
4971         }
4972         // hit a leaf
4973         nodesegmentmins[0] = min(start[0], end[0]);
4974         nodesegmentmins[1] = min(start[1], end[1]);
4975         nodesegmentmins[2] = min(start[2], end[2]);
4976         nodesegmentmaxs[0] = max(start[0], end[0]);
4977         nodesegmentmaxs[1] = max(start[1], end[1]);
4978         nodesegmentmaxs[2] = max(start[2], end[2]);
4979         // line trace the brushes
4980         leaf = (mleaf_t *)node;
4981         for (i = 0;i < leaf->numleafbrushes;i++)
4982         {
4983                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
4984                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
4985                 {
4986                         brush->markframe = markframe;
4987                         Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
4988                         if (startfrac > trace->realfraction)
4989                                 return;
4990                 }
4991         }
4992         // can't do point traces on curves (they have no thickness)
4993         if (mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
4994         {
4995                 // line trace the curves
4996                 for (i = 0;i < leaf->numleafsurfaces;i++)
4997                 {
4998                         surface = model->data_surfaces + leaf->firstleafsurface[i];
4999                         if (surface->num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
5000                         {
5001                                 surface->collisionmarkframe = markframe;
5002                                 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5003                                 if (startfrac > trace->realfraction)
5004                                         return;
5005                         }
5006                 }
5007         }
5008 }
5009
5010 static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, model_t *model, mnode_t *node, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
5011 {
5012         int i;
5013         //int sides;
5014         float nodesegmentmins[3], nodesegmentmaxs[3];
5015         mleaf_t *leaf;
5016         colbrushf_t *brush;
5017         msurface_t *surface;
5018         /*
5019                 // find which nodes the line is in and recurse for them
5020                 while (node->plane)
5021                 {
5022                         // recurse down node sides
5023                         int startside, endside;
5024                         float dist1near, dist1far, dist2near, dist2far;
5025                         BoxPlaneCornerDistances(thisbrush_start->mins, thisbrush_start->maxs, node->plane, &dist1near, &dist1far);
5026                         BoxPlaneCornerDistances(thisbrush_end->mins, thisbrush_end->maxs, node->plane, &dist2near, &dist2far);
5027                         startside = dist1near < 0;
5028                         startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
5029                         endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
5030                         if (startside == 2 || endside == 2)
5031                         {
5032                                 // brushes cross plane
5033                                 // do not clip anything, just take both sides
5034                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5035                                 node = node->children[1];
5036                                 continue;
5037                         }
5038                         if (startside == 0)
5039                         {
5040                                 if (endside == 0)
5041                                 {
5042                                         node = node->children[0];
5043                                         continue;
5044                                 }
5045                                 else
5046                                 {
5047                                         //midf0 = dist1near / (dist1near - dist2near);
5048                                         //midf1 = dist1far / (dist1far - dist2far);
5049                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5050                                         node = node->children[1];
5051                                         continue;
5052                                 }
5053                         }
5054                         else
5055                         {
5056                                 if (endside == 0)
5057                                 {
5058                                         //midf0 = dist1near / (dist1near - dist2near);
5059                                         //midf1 = dist1far / (dist1far - dist2far);
5060                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5061                                         node = node->children[1];
5062                                         continue;
5063                                 }
5064                                 else
5065                                 {
5066                                         node = node->children[1];
5067                                         continue;
5068                                 }
5069                         }
5070
5071                         if (dist1near <  0 && dist2near <  0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
5072                         if (dist1near <  0 && dist2near <  0 && dist1far <  0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5073                         if (dist1near <  0 && dist2near <  0 && dist1far >= 0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5074                         if (dist1near <  0 && dist2near <  0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5075                         if (dist1near <  0 && dist2near >= 0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
5076                         if (dist1near <  0 && dist2near >= 0 && dist1far <  0 && dist2far >= 0){}
5077                         if (dist1near <  0 && dist2near >= 0 && dist1far >= 0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5078                         if (dist1near <  0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5079                         if (dist1near >= 0 && dist2near <  0 && dist1far <  0 && dist2far <  0){node = node->children[1];continue;}
5080                         if (dist1near >= 0 && dist2near <  0 && dist1far <  0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5081                         if (dist1near >= 0 && dist2near <  0 && dist1far >= 0 && dist2far <  0){}
5082                         if (dist1near >= 0 && dist2near <  0 && dist1far >= 0 && dist2far >= 0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5083                         if (dist1near >= 0 && dist2near >= 0 && dist1far <  0 && dist2far <  0){Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);node = node->children[1];continue;}
5084                         if (dist1near >= 0 && dist2near >= 0 && dist1far <  0 && dist2far >= 0){node = node->children[0];continue;}
5085                         if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far <  0){node = node->children[0];continue;}
5086                         if (dist1near >= 0 && dist2near >= 0 && dist1far >= 0 && dist2far >= 0){node = node->children[0];continue;}
5087                         {
5088                                 if (dist2near < 0) // d1n<0 && d2n<0
5089                                 {
5090                                         if (dist2near < 0) // d1n<0 && d2n<0
5091                                         {
5092                                                 if (dist2near < 0) // d1n<0 && d2n<0
5093                                                 {
5094                                                 }
5095                                                 else // d1n<0 && d2n>0
5096                                                 {
5097                                                 }
5098                                         }
5099                                         else // d1n<0 && d2n>0
5100                                         {
5101                                                 if (dist2near < 0) // d1n<0 && d2n<0
5102                                                 {
5103                                                 }
5104                                                 else // d1n<0 && d2n>0
5105                                                 {
5106                                                 }
5107                                         }
5108                                 }
5109                                 else // d1n<0 && d2n>0
5110                                 {
5111                                 }
5112                         }
5113                         else // d1n>0
5114                         {
5115                                 if (dist2near < 0) // d1n>0 && d2n<0
5116                                 {
5117                                 }
5118                                 else // d1n>0 && d2n>0
5119                                 {
5120                                 }
5121                         }
5122                         if (dist1near < 0 == dist1far < 0 == dist2near < 0 == dist2far < 0)
5123                         {
5124                                 node = node->children[startside];
5125                                 continue;
5126                         }
5127                         if (dist1near < dist2near)
5128                         {
5129                                 // out
5130                                 if (dist1near >= 0)
5131                                 {
5132                                         node = node->children[0];
5133                                         continue;
5134                                 }
5135                                 if (dist2far < 0)
5136                                 {
5137                                         node = node->children[1];
5138                                         continue;
5139                                 }
5140                                 // dist1near < 0 && dist2far >= 0
5141                         }
5142                         else
5143                         {
5144                                 // in
5145                         }
5146                         startside = dist1near < 0 ? (dist1far < 0 ? 1 : 2) : (dist1far < 0 ? 2 : 0);
5147                         endside = dist2near < 0 ? (dist2far < 0 ? 1 : 2) : (dist2far < 0 ? 2 : 0);
5148                         if (startside == 2 || endside == 2)
5149                         {
5150                                 // brushes cross plane
5151                                 // do not clip anything, just take both sides
5152                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5153                                 node = node->children[1];
5154                         }
5155                         else if (startside == endside)
5156                                 node = node->children[startside];
5157                         else if (startside == 0) // endside = 1 (start infront, end behind)
5158                         {
5159                         }
5160                         else // startside == 1 endside = 0 (start behind, end infront)
5161                         {
5162                         }
5163                         == endside)
5164                         {
5165                                 if (startside < 2)
5166                                         node = node->children[startside];
5167                                 else
5168                                 {
5169                                         // start and end brush cross plane
5170                                 }
5171                         }
5172                         else
5173                         {
5174                         }
5175                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5176                                 node = node->children[1];
5177                         else if (dist1near < 0 && dist1far < 0 && dist2near >= 0 && dist2far >= 0)
5178                         else if (dist1near >= 0 && dist1far >= 0 && dist2near < 0 && dist2far < 0)
5179                         else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5180                                 node = node->children[0];
5181                         else
5182                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5183                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5184                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5185                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5186                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5187                         {
5188                         }
5189                         else if (dist1near >= 0 && dist1far >= 0)
5190                         {
5191                         }
5192                         else // mixed (lying on plane)
5193                         {
5194                         }
5195                         {
5196                                 if (dist2near < 0 && dist2far < 0)
5197                                 {
5198                                 }
5199                                 else
5200                                         node = node->children[1];
5201                         }
5202                         if (dist1near < 0 && dist1far < 0 && dist2near < 0 && dist2far < 0)
5203                                 node = node->children[0];
5204                         else if (dist1near >= 0 && dist1far >= 0 && dist2near >= 0 && dist2far >= 0)
5205                                 node = node->children[1];
5206                         else
5207                         {
5208                                 // both sides
5209                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5210                                 node = node->children[1];
5211                         }
5212                         sides = dist1near || dist1near < 0 | dist1far < 0 | dist2near < 0 | dist
5213                         startside = dist1 < 0;
5214                         endside = dist2 < 0;
5215                         if (startside == endside)
5216                         {
5217                                 // most of the time the line fragment is on one side of the plane
5218                                 node = node->children[startside];
5219                         }
5220                         else
5221                         {
5222                                 // line crosses node plane, split the line
5223                                 midfrac = dist1 / (dist1 - dist2);
5224                                 VectorLerp(start, midfrac, end, mid);
5225                                 // take the near side first
5226                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5227                                 if (midfrac <= trace->fraction)
5228                                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
5229                                 return;
5230                         }
5231                 }
5232         */
5233 #if 1
5234         for (;;)
5235         {
5236                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5237                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5238                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5239                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5240                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5241                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5242                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5243                         return;
5244                 if (!node->plane)
5245                         break;
5246                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5247                 node = node->children[1];
5248         }
5249 #elif 0
5250         // FIXME: could be made faster by copying TraceLine code and making it use
5251         // box plane distances...  (variant on the BoxOnPlaneSide code)
5252         for (;;)
5253         {
5254                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5255                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5256                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5257                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5258                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5259                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5260                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5261                         return;
5262                 if (!node->plane)
5263                         break;
5264                 if (mod_q3bsp_debugtracebrush.integer == 2)
5265                 {
5266                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5267                         node = node->children[1];
5268                         continue;
5269                 }
5270                 else if (mod_q3bsp_debugtracebrush.integer == 1)
5271                 {
5272                         // recurse down node sides
5273                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5274                         if (sides == 3)
5275                         {
5276                                 // segment box crosses plane
5277                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5278                                 node = node->children[1];
5279                                 continue;
5280                         }
5281                         // take whichever side the segment box is on
5282                         node = node->children[sides - 1];
5283                         continue;
5284                 }
5285                 else
5286                 {
5287                         // recurse down node sides
5288                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5289                         if (sides == 3)
5290                         {
5291                                 // segment box crosses plane
5292                                 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5293                                 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5294                                 if (sides == 3)
5295                                 {
5296                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5297                                         node = node->children[1];
5298                                         continue;
5299                                 }
5300                         }
5301                         // take whichever side the segment box is on
5302                         node = node->children[sides - 1];
5303                         continue;
5304                 }
5305                 return;
5306         }
5307 #else
5308         // FIXME: could be made faster by copying TraceLine code and making it use
5309         // box plane distances...  (variant on the BoxOnPlaneSide code)
5310         for (;;)
5311         {
5312                 nodesegmentmins[0] = max(segmentmins[0], node->mins[0]);
5313                 nodesegmentmins[1] = max(segmentmins[1], node->mins[1]);
5314                 nodesegmentmins[2] = max(segmentmins[2], node->mins[2]);
5315                 nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0]);
5316                 nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1]);
5317                 nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2]);
5318                 if (nodesegmentmins[0] > nodesegmentmaxs[0] || nodesegmentmins[1] > nodesegmentmaxs[1] || nodesegmentmins[2] > nodesegmentmaxs[2])
5319                         return;
5320                 if (!node->plane)
5321                         break;
5322                 if (mod_q3bsp_debugtracebrush.integer == 2)
5323                 {
5324                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5325                         node = node->children[1];
5326                 }
5327                 else if (mod_q3bsp_debugtracebrush.integer == 1)
5328                 {
5329                         // recurse down node sides
5330                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5331                         if (sides == 3)
5332                         {
5333                                 // segment box crosses plane
5334                                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5335                                 node = node->children[1];
5336                         }
5337                         else
5338                         {
5339                                 // take whichever side the segment box is on
5340                                 node = node->children[sides - 1];
5341                         }
5342                 }
5343                 else
5344                 {
5345                         // recurse down node sides
5346                         sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, node->plane);
5347                         if (sides == 3)
5348                         {
5349                                 // segment box crosses plane
5350                                 // now check start and end brush boxes to handle a lot of 'diagonal' cases more efficiently...
5351                                 sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, node->plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, node->plane);
5352                                 if (sides == 3)
5353                                 {
5354                                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
5355                                         sides = 2;
5356                                 }
5357                         }
5358                         // take whichever side the segment box is on
5359                         node = node->children[sides - 1];
5360                 }
5361         }
5362 #endif
5363         // hit a leaf
5364         leaf = (mleaf_t *)node;
5365         for (i = 0;i < leaf->numleafbrushes;i++)
5366         {
5367                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
5368                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
5369                 {
5370                         brush->markframe = markframe;
5371                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
5372                 }
5373         }
5374         if (mod_q3bsp_curves_collisions.integer)
5375         {
5376                 for (i = 0;i < leaf->numleafsurfaces;i++)
5377                 {
5378                         surface = model->data_surfaces + leaf->firstleafsurface[i];
5379                         if (surface->num_collisiontriangles && surface->collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
5380                         {
5381                                 surface->collisionmarkframe = markframe;
5382                                 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5383                         }
5384                 }
5385         }
5386 }
5387
5388 static void Mod_Q3BSP_TraceBox(model_t *model, int frame, trace_t *trace, const vec3_t boxstartmins, const vec3_t boxstartmaxs, const vec3_t boxendmins, const vec3_t boxendmaxs, int hitsupercontentsmask)
5389 {
5390         int i;
5391         float segmentmins[3], segmentmaxs[3];
5392         colbrushf_t *thisbrush_start, *thisbrush_end;
5393         matrix4x4_t startmatrix, endmatrix;
5394         static int markframe = 0;
5395         msurface_t *surface;
5396         q3mbrush_t *brush;
5397         memset(trace, 0, sizeof(*trace));
5398         trace->fraction = 1;
5399         trace->realfraction = 1;
5400         trace->hitsupercontentsmask = hitsupercontentsmask;
5401         Matrix4x4_CreateIdentity(&startmatrix);
5402         Matrix4x4_CreateIdentity(&endmatrix);
5403         segmentmins[0] = min(boxstartmins[0], boxendmins[0]);
5404         segmentmins[1] = min(boxstartmins[1], boxendmins[1]);
5405         segmentmins[2] = min(boxstartmins[2], boxendmins[2]);
5406         segmentmaxs[0] = max(boxstartmaxs[0], boxendmaxs[0]);
5407         segmentmaxs[1] = max(boxstartmaxs[1], boxendmaxs[1]);
5408         segmentmaxs[2] = max(boxstartmaxs[2], boxendmaxs[2]);
5409         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(boxstartmins, boxstartmaxs) && VectorCompare(boxendmins, boxendmaxs))
5410         {
5411                 if (VectorCompare(boxstartmins, boxendmins))
5412                 {
5413                         // point trace
5414                         if (model->brush.submodel)
5415                         {
5416                                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5417                                         if (brush->colbrushf)
5418                                                 Collision_TracePointBrushFloat(trace, boxstartmins, brush->colbrushf);
5419                         }
5420                         else
5421                                 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, ++markframe);
5422                 }
5423                 else
5424                 {
5425                         // line trace
5426                         if (model->brush.submodel)
5427                         {
5428                                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5429                                         if (brush->colbrushf)
5430                                                 Collision_TraceLineBrushFloat(trace, boxstartmins, boxendmins, brush->colbrushf, brush->colbrushf);
5431                                 if (mod_q3bsp_curves_collisions.integer)
5432                                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5433                                                 if (surface->num_collisiontriangles)
5434                                                         Collision_TraceLineTriangleMeshFloat(trace, boxstartmins, boxendmins, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5435                         }
5436                         else
5437                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, boxstartmins, boxendmins, 0, 1, boxstartmins, boxendmins, ++markframe, segmentmins, segmentmaxs);
5438                 }
5439         }
5440         else
5441         {
5442                 // box trace, performed as brush trace
5443                 thisbrush_start = Collision_BrushForBox(&startmatrix, boxstartmins, boxstartmaxs);
5444                 thisbrush_end = Collision_BrushForBox(&endmatrix, boxendmins, boxendmaxs);
5445                 if (model->brush.submodel)
5446                 {
5447                         for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
5448                                 if (brush->colbrushf)
5449                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush->colbrushf, brush->colbrushf);
5450                         if (mod_q3bsp_curves_collisions.integer)
5451                                 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
5452                                         if (surface->num_collisiontriangles)
5453                                                 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->data_collisionelement3i, surface->data_collisionvertex3f, surface->texture->supercontents, segmentmins, segmentmaxs);
5454                 }
5455                 else
5456                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, thisbrush_start, thisbrush_end, ++markframe, segmentmins, segmentmaxs);
5457         }
5458 }
5459
5460 static int Mod_Q3BSP_SuperContentsFromNativeContents(model_t *model, int nativecontents)
5461 {
5462         int supercontents = 0;
5463         if (nativecontents & CONTENTSQ3_SOLID)
5464                 supercontents |= SUPERCONTENTS_SOLID;
5465         if (nativecontents & CONTENTSQ3_WATER)
5466                 supercontents |= SUPERCONTENTS_WATER;
5467         if (nativecontents & CONTENTSQ3_SLIME)
5468                 supercontents |= SUPERCONTENTS_SLIME;
5469         if (nativecontents & CONTENTSQ3_LAVA)
5470                 supercontents |= SUPERCONTENTS_LAVA;
5471         if (nativecontents & CONTENTSQ3_BODY)
5472                 supercontents |= SUPERCONTENTS_BODY;
5473         if (nativecontents & CONTENTSQ3_CORPSE)
5474                 supercontents |= SUPERCONTENTS_CORPSE;
5475         if (nativecontents & CONTENTSQ3_NODROP)
5476                 supercontents |= SUPERCONTENTS_NODROP;
5477         if (nativecontents & CONTENTSQ3_PLAYERCLIP)
5478                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
5479         if (nativecontents & CONTENTSQ3_MONSTERCLIP)
5480                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
5481         if (nativecontents & CONTENTSQ3_DONOTENTER)
5482                 supercontents |= SUPERCONTENTS_DONOTENTER;
5483         return supercontents;
5484 }
5485
5486 static int Mod_Q3BSP_NativeContentsFromSuperContents(model_t *model, int supercontents)
5487 {
5488         int nativecontents = 0;
5489         if (supercontents & SUPERCONTENTS_SOLID)
5490                 nativecontents |= CONTENTSQ3_SOLID;
5491         if (supercontents & SUPERCONTENTS_WATER)
5492                 nativecontents |= CONTENTSQ3_WATER;
5493         if (supercontents & SUPERCONTENTS_SLIME)
5494                 nativecontents |= CONTENTSQ3_SLIME;
5495         if (supercontents & SUPERCONTENTS_LAVA)
5496                 nativecontents |= CONTENTSQ3_LAVA;
5497         if (supercontents & SUPERCONTENTS_BODY)
5498                 nativecontents |= CONTENTSQ3_BODY;
5499         if (supercontents & SUPERCONTENTS_CORPSE)
5500                 nativecontents |= CONTENTSQ3_CORPSE;
5501         if (supercontents & SUPERCONTENTS_NODROP)
5502                 nativecontents |= CONTENTSQ3_NODROP;
5503         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
5504                 nativecontents |= CONTENTSQ3_PLAYERCLIP;
5505         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
5506                 nativecontents |= CONTENTSQ3_MONSTERCLIP;
5507         if (supercontents & SUPERCONTENTS_DONOTENTER)
5508                 nativecontents |= CONTENTSQ3_DONOTENTER;
5509         return nativecontents;
5510 }
5511
5512 void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
5513 {
5514         int numleafs;
5515         while (node->plane)
5516         {
5517                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
5518                 node = node->children[1];
5519         }
5520         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
5521         if (loadmodel->brush.num_leafs < numleafs)
5522                 loadmodel->brush.num_leafs = numleafs;
5523 }
5524
5525 void Mod_Q3BSP_Load(model_t *mod, void *buffer, void *bufferend)
5526 {
5527         int i, j, numshadowmeshtriangles;
5528         q3dheader_t *header;
5529         float corner[3], yawradius, modelradius;
5530         msurface_t *surface;
5531
5532         mod->type = mod_brushq3;
5533         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
5534         mod->numskins = 1;
5535
5536         header = (q3dheader_t *)buffer;
5537
5538         i = LittleLong(header->version);
5539         if (i != Q3BSPVERSION)
5540                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
5541         mod->brush.ishlbsp = false;
5542         mod->brush.ismcbsp = false;
5543         if (loadmodel->isworldmodel)
5544         {
5545                 Cvar_SetValue("halflifebsp", mod->brush.ishlbsp);
5546                 Cvar_SetValue("mcbsp", mod->brush.ismcbsp);
5547         }
5548
5549         mod->soundfromcenter = true;
5550         mod->TraceBox = Mod_Q3BSP_TraceBox;
5551         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
5552         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
5553         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
5554         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
5555         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
5556         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
5557         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
5558         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
5559         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
5560         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5561         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
5562         mod->Draw = R_Q1BSP_Draw;
5563         mod->GetLightInfo = R_Q1BSP_GetLightInfo;
5564         mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
5565         mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
5566         mod->DrawLight = R_Q1BSP_DrawLight;
5567
5568         mod_base = (qbyte *)header;
5569
5570         // swap all the lumps
5571         header->ident = LittleLong(header->ident);
5572         header->version = LittleLong(header->version);
5573         for (i = 0;i < Q3HEADER_LUMPS;i++)
5574         {
5575                 header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs);
5576                 header->lumps[i].filelen = LittleLong(header->lumps[i].filelen);
5577         }
5578
5579         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
5580         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
5581         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
5582         Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
5583         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
5584         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
5585         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
5586         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
5587         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS]);
5588         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
5589         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
5590         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
5591         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
5592         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
5593         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
5594         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
5595         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
5596         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
5597
5598         // the MakePortals code works fine on the q3bsp data as well
5599         Mod_Q1BSP_MakePortals();
5600
5601         // make a single combined shadow mesh to allow optimized shadow volume creation
5602         numshadowmeshtriangles = 0;
5603         for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
5604         {
5605                 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
5606                 numshadowmeshtriangles += surface->num_triangles;
5607         }
5608         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Begin(loadmodel->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
5609         for (j = 0, surface = loadmodel->data_surfaces;j < loadmodel->num_surfaces;j++, surface++)
5610                 if (surface->groupmesh)
5611                         Mod_ShadowMesh_AddMesh(loadmodel->mempool, loadmodel->brush.shadowmesh, NULL, NULL, NULL, surface->groupmesh->data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle));
5612         loadmodel->brush.shadowmesh = Mod_ShadowMesh_Finish(loadmodel->mempool, loadmodel->brush.shadowmesh, false, true);
5613         Mod_BuildTriangleNeighbors(loadmodel->brush.shadowmesh->neighbor3i, loadmodel->brush.shadowmesh->element3i, loadmodel->brush.shadowmesh->numtriangles);
5614
5615         loadmodel->brush.num_leafs = 0;
5616         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
5617
5618         if (loadmodel->isworldmodel)
5619         {
5620                 // clear out any stale submodels or worldmodels lying around
5621                 // if we did this clear before now, an error might abort loading and
5622                 // leave things in a bad state
5623                 Mod_RemoveStaleWorldModels(loadmodel);
5624         }
5625
5626         mod = loadmodel;
5627         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
5628         {
5629                 if (i > 0)
5630                 {
5631                         char name[10];
5632                         // LordHavoc: only register submodels if it is the world
5633                         // (prevents external bsp models from replacing world submodels with
5634                         //  their own)
5635                         if (!loadmodel->isworldmodel)
5636                                 continue;
5637                         // duplicate the basic information
5638                         sprintf(name, "*%i", i);
5639                         mod = Mod_FindName(name);
5640                         *mod = *loadmodel;
5641                         strcpy(mod->name, name);
5642                         // textures and memory belong to the main model
5643                         mod->texturepool = NULL;
5644                         mod->mempool = NULL;
5645                         mod->brush.GetPVS = NULL;
5646                         mod->brush.FatPVS = NULL;
5647                         mod->brush.BoxTouchingPVS = NULL;
5648                         mod->brush.BoxTouchingLeafPVS = NULL;
5649                         mod->brush.BoxTouchingVisibleLeafs = NULL;
5650                         mod->brush.FindBoxClusters = NULL;
5651                         mod->brush.LightPoint = NULL;
5652                         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
5653                 }
5654                 mod->brush.submodel = i;
5655
5656                 // make the model surface list (used by shadowing/lighting)
5657                 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
5658                 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
5659                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
5660                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
5661                 mod->surfacelist = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->surfacelist));
5662                 for (j = 0;j < mod->nummodelsurfaces;j++)
5663                         mod->surfacelist[j] = mod->firstmodelsurface + j;
5664
5665                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
5666                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
5667                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5668                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5669                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5670                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
5671                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
5672                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5673                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
5674                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
5675                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
5676                 mod->yawmins[2] = mod->normalmins[2];
5677                 mod->yawmaxs[2] = mod->normalmaxs[2];
5678                 mod->radius = modelradius;
5679                 mod->radius2 = modelradius * modelradius;
5680
5681                 for (j = 0;j < mod->nummodelsurfaces;j++)
5682                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->surfaceflags & Q3SURFACEFLAG_SKY)
5683                                 break;
5684                 if (j < mod->nummodelsurfaces)
5685                         mod->DrawSky = R_Q1BSP_DrawSky;
5686         }
5687 }
5688
5689 void Mod_IBSP_Load(model_t *mod, void *buffer, void *bufferend)
5690 {
5691         int i = LittleLong(((int *)buffer)[1]);
5692         if (i == Q3BSPVERSION)
5693                 Mod_Q3BSP_Load(mod,buffer, bufferend);
5694         else if (i == Q2BSPVERSION)
5695                 Mod_Q2BSP_Load(mod,buffer, bufferend);
5696         else
5697                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i\n", i);
5698 }
5699
5700 void Mod_MAP_Load(model_t *mod, void *buffer, void *bufferend)
5701 {
5702         Host_Error("Mod_MAP_Load: not yet implemented\n");
5703 }
5704