got rid of Mod_CheckLoaded, changed how model system restart works to make this work...
[xonotic/darkplaces.git] / model_brush.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "curves.h"
26 #include "wad.h"
27
28
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128"};
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);