]> icculus.org git repositories - divverent/darkplaces.git/blob - collision.c
corrected an error message
[divverent/darkplaces.git] / collision.c
1
2 #include "quakedef.h"
3 #include "polygon.h"
4
5 #define COLLISION_SNAPSCALE (8.0f)
6 #define COLLISION_SNAP (1.0f / COLLISION_SNAPSCALE)
7
8 cvar_t collision_impactnudge = {0, "collision_impactnudge", "0.03125"};
9 cvar_t collision_startnudge = {0, "collision_startnudge", "0"};
10 cvar_t collision_endnudge = {0, "collision_endnudge", "0"};
11 cvar_t collision_enternudge = {0, "collision_enternudge", "0"};
12 cvar_t collision_leavenudge = {0, "collision_leavenudge", "0"};
13
14 #if 0
15 typedef struct
16 {
17         // the hull we're tracing through
18         const hull_t *hull;
19
20         // the trace structure to fill in
21         trace_t *trace;
22
23         // start and end of the trace (in model space)
24         double start[3];
25         double end[3];
26
27         // end - start
28         double dist[3];
29
30         // overrides the CONTENTS_SOLID in the box bsp tree
31         int boxsupercontents;
32 }
33 RecursiveHullCheckTraceInfo_t;
34
35 #define HULLCHECKSTATE_EMPTY 0
36 #define HULLCHECKSTATE_SOLID 1
37 #define HULLCHECKSTATE_DONE 2
38
39 static int RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
40 {
41         // status variables, these don't need to be saved on the stack when
42         // recursing...  but are because this should be thread-safe
43         // (note: tracing against a bbox is not thread-safe, yet)
44         int ret;
45         mplane_t *plane;
46         double t1, t2;
47
48         // variables that need to be stored on the stack when recursing
49         dclipnode_t *node;
50         int side;
51         double midf, mid[3];
52
53         // LordHavoc: a goto!  everyone flee in terror... :)
54 loc0:
55         // check for empty
56         if (num < 0)
57         {
58                 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
59                 if (!t->trace->startfound)
60                 {
61                         t->trace->startfound = true;
62                         t->trace->startsupercontents |= num;
63                 }
64                 if (num & SUPERCONTENTS_LIQUIDSMASK)
65                         t->trace->inwater = true;
66                 if (num == 0)
67                         t->trace->inopen = true;
68                 if (num & t->trace->hitsupercontentsmask)
69                 {
70                         // if the first leaf is solid, set startsolid
71                         if (t->trace->allsolid)
72                                 t->trace->startsolid = true;
73 #if COLLISIONPARANOID >= 3
74                         Con_Print("S");
75 #endif
76                         return HULLCHECKSTATE_SOLID;
77                 }
78                 else
79                 {
80                         t->trace->allsolid = false;
81 #if COLLISIONPARANOID >= 3
82                         Con_Print("E");
83 #endif
84                         return HULLCHECKSTATE_EMPTY;
85                 }
86         }
87
88         // find the point distances
89         node = t->hull->clipnodes + num;
90
91         plane = t->hull->planes + node->planenum;
92         if (plane->type < 3)
93         {
94                 t1 = p1[plane->type] - plane->dist;
95                 t2 = p2[plane->type] - plane->dist;
96         }
97         else
98         {
99                 t1 = DotProduct (plane->normal, p1) - plane->dist;
100                 t2 = DotProduct (plane->normal, p2) - plane->dist;
101         }
102
103         if (t1 < 0)
104         {
105                 if (t2 < 0)
106                 {
107 #if COLLISIONPARANOID >= 3
108                         Con_Print("<");
109 #endif
110                         num = node->children[1];
111                         goto loc0;
112                 }
113                 side = 1;
114         }
115         else
116         {
117                 if (t2 >= 0)
118                 {
119 #if COLLISIONPARANOID >= 3
120                         Con_Print(">");
121 #endif
122                         num = node->children[0];
123                         goto loc0;
124                 }
125                 side = 0;
126         }
127
128         // the line intersects, find intersection point
129         // LordHavoc: this uses the original trace for maximum accuracy
130 #if COLLISIONPARANOID >= 3
131         Con_Print("M");
132 #endif
133         if (plane->type < 3)
134         {
135                 t1 = t->start[plane->type] - plane->dist;
136                 t2 = t->end[plane->type] - plane->dist;
137         }
138         else
139         {
140                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
141                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
142         }
143
144         midf = t1 / (t1 - t2);
145         midf = bound(p1f, midf, p2f);
146         VectorMA(t->start, midf, t->dist, mid);
147
148         // recurse both sides, front side first
149         ret = RecursiveHullCheck (t, node->children[side], p1f, midf, p1, mid);
150         // if this side is not empty, return what it is (solid or done)
151         if (ret != HULLCHECKSTATE_EMPTY)
152                 return ret;
153
154         ret = RecursiveHullCheck (t, node->children[side ^ 1], midf, p2f, mid, p2);
155         // if other side is not solid, return what it is (empty or done)
156         if (ret != HULLCHECKSTATE_SOLID)
157                 return ret;
158
159         // front is air and back is solid, this is the impact point...
160         if (side)
161         {
162                 t->trace->plane.dist = -plane->dist;
163                 VectorNegate (plane->normal, t->trace->plane.normal);
164         }
165         else
166         {
167                 t->trace->plane.dist = plane->dist;
168                 VectorCopy (plane->normal, t->trace->plane.normal);
169         }
170
171         // calculate the true fraction
172         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist - collision_startnudge.value;
173         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist - collision_endnudge.value;
174         midf = t1 / (t1 - t2);
175         t->trace->realfraction = bound(0, midf, 1);
176
177         // calculate the return fraction which is nudged off the surface a bit
178         midf = (t1 - collision_impactnudge.value) / (t1 - t2);
179         t->trace->fraction = bound(0, midf, 1);
180
181 #if COLLISIONPARANOID >= 3
182         Con_Print("D");
183 #endif
184         return HULLCHECKSTATE_DONE;
185 }
186
187 static hull_t box_hull;
188 static dclipnode_t box_clipnodes[6];
189 static mplane_t box_planes[6];
190
191 void Mod_Q1BSP_Collision_Init (void)
192 {
193         int             i;
194         int             side;
195
196         //Set up the planes and clipnodes so that the six floats of a bounding box
197         //can just be stored out and get a proper hull_t structure.
198
199         box_hull.clipnodes = box_clipnodes;
200         box_hull.planes = box_planes;
201         box_hull.firstclipnode = 0;
202         box_hull.lastclipnode = 5;
203
204         for (i = 0;i < 6;i++)
205         {
206                 box_clipnodes[i].planenum = i;
207
208                 side = i&1;
209
210                 box_clipnodes[i].children[side] = CONTENTS_EMPTY;
211                 if (i != 5)
212                         box_clipnodes[i].children[side^1] = i + 1;
213                 else
214                         box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
215
216                 box_planes[i].type = i>>1;
217                 box_planes[i].normal[i>>1] = 1;
218         }
219 }
220
221 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)
222 {
223         RecursiveHullCheckTraceInfo_t rhc;
224         // fill in a default trace
225         memset(&rhc, 0, sizeof(rhc));
226         memset(trace, 0, sizeof(trace_t));
227         //To keep everything totally uniform, bounding boxes are turned into small
228         //BSP trees instead of being compared directly.
229         // create a temp hull from bounding box sizes
230         box_planes[0].dist = cmaxs[0] - mins[0];
231         box_planes[1].dist = cmins[0] - maxs[0];
232         box_planes[2].dist = cmaxs[1] - mins[1];
233         box_planes[3].dist = cmins[1] - maxs[1];
234         box_planes[4].dist = cmaxs[2] - mins[2];
235         box_planes[5].dist = cmins[2] - maxs[2];
236         // trace a line through the generated clipping hull
237         rhc.boxsupercontents = boxsupercontents;
238         rhc.hull = &box_hull;
239         rhc.trace = trace;
240         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
241         rhc.trace->fraction = 1;
242         rhc.trace->realfraction = 1;
243         rhc.trace->allsolid = true;
244         VectorCopy(start, rhc.start);
245         VectorCopy(end, rhc.end);
246         VectorSubtract(rhc.end, rhc.start, rhc.dist);
247         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
248         VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
249         if (rhc.trace->startsupercontents)
250                 rhc.trace->startsupercontents = boxsupercontents;
251 }
252 #endif
253
254 void Collision_Init (void)
255 {
256         Cvar_RegisterVariable(&collision_impactnudge);
257         Cvar_RegisterVariable(&collision_startnudge);
258         Cvar_RegisterVariable(&collision_endnudge);
259         Cvar_RegisterVariable(&collision_enternudge);
260         Cvar_RegisterVariable(&collision_leavenudge);
261 }
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276 void Collision_PrintBrushAsQHull(colbrushf_t *brush, const char *name)
277 {
278         int i;
279         Con_Printf("3 %s\n%i\n", name, brush->numpoints);
280         for (i = 0;i < brush->numpoints;i++)
281                 Con_Printf("%f %f %f\n", brush->points[i].v[0], brush->points[i].v[1], brush->points[i].v[2]);
282         // FIXME: optimize!
283         Con_Printf("4\n%i\n", brush->numplanes);
284         for (i = 0;i < brush->numplanes;i++)
285                 Con_Printf("%f %f %f %f\n", brush->planes[i].normal[0], brush->planes[i].normal[1], brush->planes[i].normal[2], brush->planes[i].dist);
286 }
287
288 void Collision_ValidateBrush(colbrushf_t *brush)
289 {
290         int j, k, pointsoffplanes, pointonplanes, pointswithinsufficientplanes, printbrush;
291         float d;
292         printbrush = false;
293         if (!brush->numpoints)
294         {
295                 Con_Print("Collision_ValidateBrush: brush with no points!\n");
296                 printbrush = true;
297         }
298 #if 0
299         // it's ok for a brush to have one point and no planes...
300         if (brush->numplanes == 0 && brush->numpoints != 1)
301         {
302                 Con_Print("Collision_ValidateBrush: brush with no planes and more than one point!\n");
303                 printbrush = true;
304         }
305 #endif
306         if (brush->numplanes)
307         {
308                 pointsoffplanes = 0;
309                 pointswithinsufficientplanes = 0;
310                 for (k = 0;k < brush->numplanes;k++)
311                         if (DotProduct(brush->planes[k].normal, brush->planes[k].normal) < 0.0001f)
312                                 Con_Printf("Collision_ValidateBrush: plane #%i (%f %f %f %f) is degenerate\n", k, brush->planes[k].normal[0], brush->planes[k].normal[1], brush->planes[k].normal[2], brush->planes[k].dist);
313                 for (j = 0;j < brush->numpoints;j++)
314                 {
315                         pointonplanes = 0;
316                         for (k = 0;k < brush->numplanes;k++)
317                         {
318                                 d = DotProduct(brush->points[j].v, brush->planes[k].normal) - brush->planes[k].dist;
319                                 if (d > (1.0f / 8.0f))
320                                 {
321                                         Con_Printf("Collision_ValidateBrush: point #%i (%f %f %f) infront of plane #%i (%f %f %f %f)\n", j, brush->points[j].v[0], brush->points[j].v[1], brush->points[j].v[2], k, brush->planes[k].normal[0], brush->planes[k].normal[1], brush->planes[k].normal[2], brush->planes[k].dist);
322                                         printbrush = true;
323                                 }
324                                 if (fabs(d) > 0.125f)
325                                         pointsoffplanes++;
326                                 else
327                                         pointonplanes++;
328                         }
329                         if (pointonplanes < 3)
330                                 pointswithinsufficientplanes++;
331                 }
332                 if (pointswithinsufficientplanes)
333                 {
334                         Con_Print("Collision_ValidateBrush: some points have insufficient planes, every point must be on at least 3 planes to form a corner.\n");
335                         printbrush = true;
336                 }
337                 if (pointsoffplanes == 0) // all points are on all planes
338                 {
339                         Con_Print("Collision_ValidateBrush: all points lie on all planes (degenerate, no brush volume!)\n");
340                         printbrush = true;
341                 }
342         }
343         if (printbrush)
344                 Collision_PrintBrushAsQHull(brush, "unnamed");
345 }
346
347 float nearestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
348 {
349         float dist, bestdist;
350         bestdist = DotProduct(points->v, normal);
351         points++;
352         while(--numpoints)
353         {
354                 dist = DotProduct(points->v, normal);
355                 bestdist = min(bestdist, dist);
356                 points++;
357         }
358         return bestdist;
359 }
360
361 float furthestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
362 {
363         float dist, bestdist;
364         bestdist = DotProduct(points->v, normal);
365         points++;
366         while(--numpoints)
367         {
368                 dist = DotProduct(points->v, normal);
369                 bestdist = max(bestdist, dist);
370                 points++;
371         }
372         return bestdist;
373 }
374
375
376 colbrushf_t *Collision_NewBrushFromPlanes(mempool_t *mempool, int numoriginalplanes, const mplane_t *originalplanes, int supercontents)
377 {
378         int j, k, m, w;
379         int numpointsbuf = 0, maxpointsbuf = 256, numplanesbuf = 0, maxplanesbuf = 256, numelementsbuf = 0, maxelementsbuf = 256;
380         colbrushf_t *brush;
381         colpointf_t pointsbuf[256];
382         colplanef_t planesbuf[256];
383         int elementsbuf[1024];
384         int polypointbuf[256];
385         int pmaxpoints = 64;
386         int pnumpoints;
387         double p[2][3*64];
388 #if 0
389         // enable these if debugging to avoid seeing garbage in unused data
390         memset(pointsbuf, 0, sizeof(pointsbuf));
391         memset(planesbuf, 0, sizeof(planesbuf));
392         memset(elementsbuf, 0, sizeof(elementsbuf));
393         memset(polypointbuf, 0, sizeof(polypointbuf));
394         memset(p, 0, sizeof(p));
395 #endif
396         // construct a collision brush (points, planes, and renderable mesh) from
397         // a set of planes, this also optimizes out any unnecessary planes (ones
398         // whose polygon is clipped away by the other planes)
399         for (j = 0;j < numoriginalplanes;j++)
400         {
401                 // add the plane uniquely (no duplicates)
402                 for (k = 0;k < numplanesbuf;k++)
403                         if (VectorCompare(planesbuf[k].normal, originalplanes[j].normal) && planesbuf[k].dist == originalplanes[j].dist)
404                                 break;
405                 // if the plane is a duplicate, skip it
406                 if (k < numplanesbuf)
407                         continue;
408                 // check if there are too many and skip the brush
409                 if (numplanesbuf >= maxplanesbuf)
410                 {
411                         Con_Print("Collision_NewBrushFromPlanes: failed to build collision brush: too many planes for buffer\n");
412                         return NULL;
413                 }
414
415                 // create a large polygon from the plane
416                 w = 0;
417                 PolygonD_QuadForPlane(p[w], originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist, 1024.0*1024.0*1024.0);
418                 pnumpoints = 4;
419                 // clip it by all other planes
420                 for (k = 0;k < numoriginalplanes && pnumpoints && pnumpoints <= pmaxpoints;k++)
421                 {
422                         if (k != j)
423                         {
424                                 // we want to keep the inside of the brush plane so we flip
425                                 // the cutting plane
426                                 PolygonD_Divide(pnumpoints, p[w], -originalplanes[k].normal[0], -originalplanes[k].normal[1], -originalplanes[k].normal[2], -originalplanes[k].dist, 1.0/32.0, pmaxpoints, p[!w], &pnumpoints, 0, NULL, NULL);
427                                 w = !w;
428                         }
429                 }
430                 // if nothing is left, skip it
431                 if (pnumpoints < 3)
432                 {
433                         //Con_Printf("Collision_NewBrushFromPlanes: warning: polygon for plane %f %f %f %f clipped away\n", originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist);
434                         continue;
435                 }
436
437                 for (k = 0;k < pnumpoints;k++)
438                 {
439                         int l, m;
440                         m = 0;
441                         for (l = 0;l < numoriginalplanes;l++)
442                                 if (fabs(DotProduct(&p[w][k*3], originalplanes[l].normal) - originalplanes[l].dist) < 1.0/8.0)
443                                         m++;
444                         if (m < 3)
445                                 break;
446                 }
447                 if (k < pnumpoints)
448                 {
449                         Con_Printf("Collision_NewBrushFromPlanes: warning: polygon point does not lie on at least 3 planes\n");
450                         //return NULL;
451                 }
452
453                 // check if there are too many polygon vertices for buffer
454                 if (pnumpoints > pmaxpoints)
455                 {
456                         Con_Print("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
457                         return NULL;
458                 }
459
460                 // check if there are too many triangle elements for buffer
461                 if (numelementsbuf + (pnumpoints - 2) * 3 > maxelementsbuf)
462                 {
463                         Con_Print("Collision_NewBrushFromPlanes: failed to build collision brush: too many triangle elements for buffer\n");
464                         return NULL;
465                 }
466
467                 for (k = 0;k < pnumpoints;k++)
468                 {
469                         // check if there is already a matching point (no duplicates)
470                         for (m = 0;m < numpointsbuf;m++)
471                                 if (VectorDistance2(&p[w][k*3], pointsbuf[m].v) < COLLISION_SNAP)
472                                         break;
473
474                         // if there is no match, add a new one
475                         if (m == numpointsbuf)
476                         {
477                                 // check if there are too many and skip the brush
478                                 if (numpointsbuf >= maxpointsbuf)
479                                 {
480                                         Con_Print("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
481                                         return NULL;
482                                 }
483                                 // add the new one
484                                 VectorCopy(&p[w][k*3], pointsbuf[numpointsbuf].v);
485                                 numpointsbuf++;
486                         }
487
488                         // store the index into a buffer
489                         polypointbuf[k] = m;
490                 }
491
492                 // add the triangles for the polygon
493                 // (this particular code makes a triangle fan)
494                 for (k = 0;k < pnumpoints - 2;k++)
495                 {
496                         elementsbuf[numelementsbuf++] = polypointbuf[0];
497                         elementsbuf[numelementsbuf++] = polypointbuf[k + 1];
498                         elementsbuf[numelementsbuf++] = polypointbuf[k + 2];
499                 }
500
501                 // add the new plane
502                 VectorCopy(originalplanes[j].normal, planesbuf[numplanesbuf].normal);
503                 planesbuf[numplanesbuf].dist = originalplanes[j].dist;
504                 numplanesbuf++;
505         }
506
507         // validate plane distances
508         for (j = 0;j < numplanesbuf;j++)
509         {
510                 float d = furthestplanedist_float(planesbuf[j].normal, pointsbuf, numpointsbuf);
511                 if (fabs(planesbuf[j].dist - d) > (1.0f/32.0f))
512                         Con_Printf("plane %f %f %f %f mismatches dist %f\n", planesbuf[j].normal[0], planesbuf[j].normal[1], planesbuf[j].normal[2], planesbuf[j].dist, d);
513         }
514
515         // if nothing is left, there's nothing to allocate
516         if (numelementsbuf < 12 || numplanesbuf < 4 || numpointsbuf < 4)
517         {
518                 Con_Printf("Collision_NewBrushFromPlanes: failed to build collision brush: %i triangles, %i planes (input was %i planes), %i vertices\n", numelementsbuf / 3, numplanesbuf, numoriginalplanes, numpointsbuf);
519                 return NULL;
520         }
521
522         // allocate the brush and copy to it
523         brush = Collision_AllocBrushFloat(mempool, numpointsbuf, numplanesbuf, numelementsbuf / 3, supercontents);
524         for (j = 0;j < brush->numpoints;j++)
525         {
526                 brush->points[j].v[0] = pointsbuf[j].v[0];
527                 brush->points[j].v[1] = pointsbuf[j].v[1];
528                 brush->points[j].v[2] = pointsbuf[j].v[2];
529         }
530         for (j = 0;j < brush->numplanes;j++)
531         {
532                 brush->planes[j].normal[0] = planesbuf[j].normal[0];
533                 brush->planes[j].normal[1] = planesbuf[j].normal[1];
534                 brush->planes[j].normal[2] = planesbuf[j].normal[2];
535                 brush->planes[j].dist = planesbuf[j].dist;
536         }
537         for (j = 0;j < brush->numtriangles * 3;j++)
538                 brush->elements[j] = elementsbuf[j];
539         VectorCopy(brush->points[0].v, brush->mins);
540         VectorCopy(brush->points[0].v, brush->maxs);
541         for (j = 1;j < brush->numpoints;j++)
542         {
543                 brush->mins[0] = min(brush->mins[0], brush->points[j].v[0]);
544                 brush->mins[1] = min(brush->mins[1], brush->points[j].v[1]);
545                 brush->mins[2] = min(brush->mins[2], brush->points[j].v[2]);
546                 brush->maxs[0] = max(brush->maxs[0], brush->points[j].v[0]);
547                 brush->maxs[1] = max(brush->maxs[1], brush->points[j].v[1]);
548                 brush->maxs[2] = max(brush->maxs[2], brush->points[j].v[2]);
549         }
550         brush->mins[0] -= 1;
551         brush->mins[1] -= 1;
552         brush->mins[2] -= 1;
553         brush->maxs[0] += 1;
554         brush->maxs[1] += 1;
555         brush->maxs[2] += 1;
556         Collision_ValidateBrush(brush);
557         return brush;
558 }
559
560
561
562 colbrushf_t *Collision_AllocBrushFloat(mempool_t *mempool, int numpoints, int numplanes, int numtriangles, int supercontents)
563 {
564         colbrushf_t *brush;
565         brush = Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colpointf_t) * numpoints + sizeof(colplanef_t) * numplanes + sizeof(int[3]) * numtriangles);
566         brush->supercontents = supercontents;
567         brush->numplanes = numplanes;
568         brush->numpoints = numpoints;
569         brush->numtriangles = numtriangles;
570         brush->planes = (void *)(brush + 1);
571         brush->points = (void *)(brush->planes + brush->numplanes);
572         brush->elements = (void *)(brush->points + brush->numpoints);
573         return brush;
574 }
575
576 void Collision_CalcPlanesForPolygonBrushFloat(colbrushf_t *brush)
577 {
578         int i;
579         float edge0[3], edge1[3], edge2[3], normal[3], dist, bestdist;
580         colpointf_t *p, *p2;
581
582         // FIXME: these probably don't actually need to be normalized if the collision code does not care
583         if (brush->numpoints == 3)
584         {
585                 // optimized triangle case
586                 TriangleNormal(brush->points[0].v, brush->points[1].v, brush->points[2].v, brush->planes[0].normal);
587                 if (DotProduct(brush->planes[0].normal, brush->planes[0].normal) < 0.0001f)
588                 {
589                         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
590                         brush->numplanes = 0;
591                         return;
592                 }
593                 else
594                 {
595                         brush->numplanes = 5;
596                         VectorNormalize(brush->planes[0].normal);
597                         brush->planes[0].dist = DotProduct(brush->points->v, brush->planes[0].normal);
598                         VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
599                         brush->planes[1].dist = -brush->planes[0].dist;
600                         VectorSubtract(brush->points[2].v, brush->points[0].v, edge0);
601                         VectorSubtract(brush->points[0].v, brush->points[1].v, edge1);
602                         VectorSubtract(brush->points[1].v, brush->points[2].v, edge2);
603 #if 1
604                         {
605                                 float projectionnormal[3], projectionedge0[3], projectionedge1[3], projectionedge2[3];
606                                 int i, best;
607                                 float dist, bestdist;
608                                 bestdist = fabs(brush->planes[0].normal[0]);
609                                 best = 0;
610                                 for (i = 1;i < 3;i++)
611                                 {
612                                         dist = fabs(brush->planes[0].normal[i]);
613                                         if (bestdist < dist)
614                                         {
615                                                 bestdist = dist;
616                                                 best = i;
617                                         }
618                                 }
619                                 VectorClear(projectionnormal);
620                                 if (brush->planes[0].normal[best] < 0)
621                                         projectionnormal[best] = -1;
622                                 else
623                                         projectionnormal[best] = 1;
624                                 VectorCopy(edge0, projectionedge0);
625                                 VectorCopy(edge1, projectionedge1);
626                                 VectorCopy(edge2, projectionedge2);
627                                 projectionedge0[best] = 0;
628                                 projectionedge1[best] = 0;
629                                 projectionedge2[best] = 0;
630                                 CrossProduct(projectionedge0, projectionnormal, brush->planes[2].normal);
631                                 CrossProduct(projectionedge1, projectionnormal, brush->planes[3].normal);
632                                 CrossProduct(projectionedge2, projectionnormal, brush->planes[4].normal);
633                         }
634 #else
635                         CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
636                         CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
637                         CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
638 #endif
639                         VectorNormalize(brush->planes[2].normal);
640                         VectorNormalize(brush->planes[3].normal);
641                         VectorNormalize(brush->planes[4].normal);
642                         brush->planes[2].dist = DotProduct(brush->points[2].v, brush->planes[2].normal);
643                         brush->planes[3].dist = DotProduct(brush->points[0].v, brush->planes[3].normal);
644                         brush->planes[4].dist = DotProduct(brush->points[1].v, brush->planes[4].normal);
645
646                         if (developer.integer)
647                         {
648                                 // validation code
649 #if 0
650                                 float temp[3];
651
652                                 VectorSubtract(brush->points[0].v, brush->points[1].v, edge0);
653                                 VectorSubtract(brush->points[2].v, brush->points[1].v, edge1);
654                                 CrossProduct(edge0, edge1, normal);
655                                 VectorNormalize(normal);
656                                 VectorSubtract(normal, brush->planes[0].normal, temp);
657                                 if (VectorLength(temp) > 0.01f)
658                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: TriangleNormal gave wrong answer (%f %f %f != correct answer %f %f %f)\n", brush->planes->normal[0], brush->planes->normal[1], brush->planes->normal[2], normal[0], normal[1], normal[2]);
659                                 if (fabs(DotProduct(brush->planes[1].normal, brush->planes[0].normal) - -1.0f) > 0.01f || fabs(brush->planes[1].dist - -brush->planes[0].dist) > 0.01f)
660                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: plane 1 (%f %f %f %f) is not opposite plane 0 (%f %f %f %f)\n", brush->planes[1].normal[0], brush->planes[1].normal[1], brush->planes[1].normal[2], brush->planes[1].dist, brush->planes[0].normal[0], brush->planes[0].normal[1], brush->planes[0].normal[2], brush->planes[0].dist);
661 #if 0
662                                 if (fabs(DotProduct(brush->planes[2].normal, brush->planes[0].normal)) > 0.01f)
663                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: plane 2 (%f %f %f %f) is not perpendicular to plane 0 (%f %f %f %f)\n", brush->planes[2].normal[0], brush->planes[2].normal[1], brush->planes[2].normal[2], brush->planes[2].dist, brush->planes[0].normal[0], brush->planes[0].normal[1], brush->planes[0].normal[2], brush->planes[2].dist);
664                                 if (fabs(DotProduct(brush->planes[3].normal, brush->planes[0].normal)) > 0.01f)
665                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: plane 3 (%f %f %f %f) is not perpendicular to plane 0 (%f %f %f %f)\n", brush->planes[3].normal[0], brush->planes[3].normal[1], brush->planes[3].normal[2], brush->planes[3].dist, brush->planes[0].normal[0], brush->planes[0].normal[1], brush->planes[0].normal[2], brush->planes[3].dist);
666                                 if (fabs(DotProduct(brush->planes[4].normal, brush->planes[0].normal)) > 0.01f)
667                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: plane 4 (%f %f %f %f) is not perpendicular to plane 0 (%f %f %f %f)\n", brush->planes[4].normal[0], brush->planes[4].normal[1], brush->planes[4].normal[2], brush->planes[4].dist, brush->planes[0].normal[0], brush->planes[0].normal[1], brush->planes[0].normal[2], brush->planes[4].dist);
668                                 if (fabs(DotProduct(brush->planes[2].normal, edge0)) > 0.01f)
669                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: plane 2 (%f %f %f %f) is not perpendicular to edge 0 (%f %f %f to %f %f %f)\n", brush->planes[2].normal[0], brush->planes[2].normal[1], brush->planes[2].normal[2], brush->planes[2].dist, brush->points[2].v[0], brush->points[2].v[1], brush->points[2].v[2], brush->points[0].v[0], brush->points[0].v[1], brush->points[0].v[2]);
670                                 if (fabs(DotProduct(brush->planes[3].normal, edge1)) > 0.01f)
671                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: plane 3 (%f %f %f %f) is not perpendicular to edge 1 (%f %f %f to %f %f %f)\n", brush->planes[3].normal[0], brush->planes[3].normal[1], brush->planes[3].normal[2], brush->planes[3].dist, brush->points[0].v[0], brush->points[0].v[1], brush->points[0].v[2], brush->points[1].v[0], brush->points[1].v[1], brush->points[1].v[2]);
672                                 if (fabs(DotProduct(brush->planes[4].normal, edge2)) > 0.01f)
673                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: plane 4 (%f %f %f %f) is not perpendicular to edge 2 (%f %f %f to %f %f %f)\n", brush->planes[4].normal[0], brush->planes[4].normal[1], brush->planes[4].normal[2], brush->planes[4].dist, brush->points[1].v[0], brush->points[1].v[1], brush->points[1].v[2], brush->points[2].v[0], brush->points[2].v[1], brush->points[2].v[2]);
674 #endif
675 #endif
676                                 if (fabs(DotProduct(brush->points[0].v, brush->planes[0].normal) - brush->planes[0].dist) > 0.01f || fabs(DotProduct(brush->points[1].v, brush->planes[0].normal) - brush->planes[0].dist) > 0.01f || fabs(DotProduct(brush->points[2].v, brush->planes[0].normal) - brush->planes[0].dist) > 0.01f)
677                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: edges (%f %f %f to %f %f %f to %f %f %f) off front plane 0 (%f %f %f %f)\n", brush->points[0].v[0], brush->points[0].v[1], brush->points[0].v[2], brush->points[1].v[0], brush->points[1].v[1], brush->points[1].v[2], brush->points[2].v[0], brush->points[2].v[1], brush->points[2].v[2], brush->planes[0].normal[0], brush->planes[0].normal[1], brush->planes[0].normal[2], brush->planes[0].dist);
678                                 if (fabs(DotProduct(brush->points[0].v, brush->planes[1].normal) - brush->planes[1].dist) > 0.01f || fabs(DotProduct(brush->points[1].v, brush->planes[1].normal) - brush->planes[1].dist) > 0.01f || fabs(DotProduct(brush->points[2].v, brush->planes[1].normal) - brush->planes[1].dist) > 0.01f)
679                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: edges (%f %f %f to %f %f %f to %f %f %f) off back plane 1 (%f %f %f %f)\n", brush->points[0].v[0], brush->points[0].v[1], brush->points[0].v[2], brush->points[1].v[0], brush->points[1].v[1], brush->points[1].v[2], brush->points[2].v[0], brush->points[2].v[1], brush->points[2].v[2], brush->planes[1].normal[0], brush->planes[1].normal[1], brush->planes[1].normal[2], brush->planes[1].dist);
680                                 if (fabs(DotProduct(brush->points[2].v, brush->planes[2].normal) - brush->planes[2].dist) > 0.01f || fabs(DotProduct(brush->points[0].v, brush->planes[2].normal) - brush->planes[2].dist) > 0.01f)
681                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: edge 0 (%f %f %f to %f %f %f) off front plane 2 (%f %f %f %f)\n", brush->points[2].v[0], brush->points[2].v[1], brush->points[2].v[2], brush->points[0].v[0], brush->points[0].v[1], brush->points[0].v[2], brush->planes[2].normal[0], brush->planes[2].normal[1], brush->planes[2].normal[2], brush->planes[2].dist);
682                                 if (fabs(DotProduct(brush->points[0].v, brush->planes[3].normal) - brush->planes[3].dist) > 0.01f || fabs(DotProduct(brush->points[1].v, brush->planes[3].normal) - brush->planes[3].dist) > 0.01f)
683                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: edge 0 (%f %f %f to %f %f %f) off front plane 2 (%f %f %f %f)\n", brush->points[0].v[0], brush->points[0].v[1], brush->points[0].v[2], brush->points[1].v[0], brush->points[1].v[1], brush->points[1].v[2], brush->planes[3].normal[0], brush->planes[3].normal[1], brush->planes[3].normal[2], brush->planes[3].dist);
684                                 if (fabs(DotProduct(brush->points[1].v, brush->planes[4].normal) - brush->planes[4].dist) > 0.01f || fabs(DotProduct(brush->points[2].v, brush->planes[4].normal) - brush->planes[4].dist) > 0.01f)
685                                         Con_Printf("Collision_CalcPlanesForPolygonBrushFloat: edge 0 (%f %f %f to %f %f %f) off front plane 2 (%f %f %f %f)\n", brush->points[1].v[0], brush->points[1].v[1], brush->points[1].v[2], brush->points[2].v[0], brush->points[2].v[1], brush->points[2].v[2], brush->planes[4].normal[0], brush->planes[4].normal[1], brush->planes[4].normal[2], brush->planes[4].dist);
686                         }
687                 }
688         }
689         else
690         {
691                 // choose best surface normal for polygon's plane
692                 bestdist = 0;
693                 for (i = 0, p = brush->points + 1;i < brush->numpoints - 2;i++, p++)
694                 {
695                         VectorSubtract(p[-1].v, p[0].v, edge0);
696                         VectorSubtract(p[1].v, p[0].v, edge1);
697                         CrossProduct(edge0, edge1, normal);
698                         //TriangleNormal(p[-1].v, p[0].v, p[1].v, normal);
699                         dist = DotProduct(normal, normal);
700                         if (i == 0 || bestdist < dist)
701                         {
702                                 bestdist = dist;
703                                 VectorCopy(normal, brush->planes->normal);
704                         }
705                 }
706                 if (bestdist < 0.0001f)
707                 {
708                         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
709                         brush->numplanes = 0;
710                         return;
711                 }
712                 else
713                 {
714                         brush->numplanes = brush->numpoints + 2;
715                         VectorNormalize(brush->planes->normal);
716                         brush->planes->dist = DotProduct(brush->points->v, brush->planes->normal);
717
718                         // negate plane to create other side
719                         VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
720                         brush->planes[1].dist = -brush->planes[0].dist;
721                         for (i = 0, p = brush->points + (brush->numpoints - 1), p2 = brush->points;i < brush->numpoints;i++, p = p2, p2++)
722                         {
723                                 VectorSubtract(p->v, p2->v, edge0);
724                                 CrossProduct(edge0, brush->planes->normal, brush->planes[i + 2].normal);
725                                 VectorNormalize(brush->planes[i + 2].normal);
726                                 brush->planes[i + 2].dist = DotProduct(p->v, brush->planes[i + 2].normal);
727                         }
728                 }
729         }
730
731         if (developer.integer)
732         {
733                 // validity check - will be disabled later
734                 Collision_ValidateBrush(brush);
735                 for (i = 0;i < brush->numplanes;i++)
736                 {
737                         int j;
738                         for (j = 0, p = brush->points;j < brush->numpoints;j++, p++)
739                                 if (DotProduct(p->v, brush->planes[i].normal) > brush->planes[i].dist + (1.0 / 32.0))
740                                         Con_Printf("Error in brush plane generation, plane %i\n", i);
741                 }
742         }
743 }
744
745 colbrushf_t *Collision_AllocBrushFromPermanentPolygonFloat(mempool_t *mempool, int numpoints, float *points, int supercontents)
746 {
747         colbrushf_t *brush;
748         brush = Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colplanef_t) * (numpoints + 2));
749         brush->supercontents = supercontents;
750         brush->numpoints = numpoints;
751         brush->numplanes = numpoints + 2;
752         brush->planes = (void *)(brush + 1);
753         brush->points = (colpointf_t *)points;
754         Host_Error("Collision_AllocBrushFromPermanentPolygonFloat: FIXME: this code needs to be updated to generate a mesh...\n");
755         return brush;
756 }
757
758 // NOTE: start and end of each brush pair must have same numplanes/numpoints
759 void Collision_TraceBrushBrushFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, const colbrushf_t *thatbrush_start, const colbrushf_t *thatbrush_end)
760 {
761         int nplane, nplane2, fstartsolid, fendsolid, brushsolid;
762         float enterfrac, leavefrac, d1, d2, f, imove, newimpactnormal[3], enterfrac2;
763         const colplanef_t *startplane, *endplane;
764
765         enterfrac = -1;
766         enterfrac2 = -1;
767         leavefrac = 1;
768         fstartsolid = true;
769         fendsolid = true;
770
771         for (nplane = 0;nplane < thatbrush_start->numplanes + thisbrush_start->numplanes;nplane++)
772         {
773                 nplane2 = nplane;
774                 if (nplane2 >= thatbrush_start->numplanes)
775                 {
776                         nplane2 -= thatbrush_start->numplanes;
777                         startplane = thisbrush_start->planes + nplane2;
778                         endplane = thisbrush_end->planes + nplane2;
779                         if (developer.integer)
780                         {
781                                 // any brush with degenerate planes is not worth handling
782                                 if (DotProduct(startplane->normal, startplane->normal) < 0.9f || DotProduct(endplane->normal, endplane->normal) < 0.9f)
783                                 {
784                                         Con_Print("Collision_TraceBrushBrushFloat: degenerate thisbrush plane!\n");
785                                         return;
786                                 }
787                                 f = furthestplanedist_float(startplane->normal, thisbrush_start->points, thisbrush_start->numpoints);
788                                 if (fabs(f - startplane->dist) > 0.125f)
789                                         Con_Printf("startplane->dist %f != calculated %f (thisbrush_start)\n", startplane->dist, f);
790                         }
791                         d1 = nearestplanedist_float(startplane->normal, thisbrush_start->points, thisbrush_start->numpoints) - furthestplanedist_float(startplane->normal, thatbrush_start->points, thatbrush_start->numpoints) - collision_startnudge.value;
792                         d2 = nearestplanedist_float(endplane->normal, thisbrush_end->points, thisbrush_end->numpoints) - furthestplanedist_float(endplane->normal, thatbrush_end->points, thatbrush_end->numpoints) - collision_endnudge.value;
793                 }
794                 else
795                 {
796                         startplane = thatbrush_start->planes + nplane2;
797                         endplane = thatbrush_end->planes + nplane2;
798                         if (developer.integer)
799                         {
800                                 // any brush with degenerate planes is not worth handling
801                                 if (DotProduct(startplane->normal, startplane->normal) < 0.9f || DotProduct(endplane->normal, endplane->normal) < 0.9f)
802                                 {
803                                         Con_Print("Collision_TraceBrushBrushFloat: degenerate thatbrush plane!\n");
804                                         return;
805                                 }
806                                 f = furthestplanedist_float(startplane->normal, thatbrush_start->points, thatbrush_start->numpoints);
807                                 if (fabs(f - startplane->dist) > 0.125f)
808                                         Con_Printf("startplane->dist %f != calculated %f (thatbrush_start)\n", startplane->dist, f);
809                         }
810                         d1 = nearestplanedist_float(startplane->normal, thisbrush_start->points, thisbrush_start->numpoints) - startplane->dist - collision_startnudge.value;
811                         d2 = nearestplanedist_float(endplane->normal, thisbrush_end->points, thisbrush_end->numpoints) - endplane->dist - collision_endnudge.value;
812                 }
813                 //Con_Printf("%c%i: d1 = %f, d2 = %f, d1 / (d1 - d2) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, d1, d2, d1 / (d1 - d2));
814
815                 if(d1 > d2)
816                 {
817                         // moving into brush
818                         if(d2 > 0)
819                                 return;
820                         if(d1 > 0)
821                         {
822                                 // enter
823                                 fstartsolid = false;
824                                 imove = 1 / (d1 - d2);
825                                 f = (d1 - collision_enternudge.value) * imove;
826                                 if (enterfrac < f)
827                                 {
828                                         enterfrac = f;
829                                         enterfrac2 = f - collision_impactnudge.value * imove;
830                                         VectorLerp(startplane->normal, enterfrac, endplane->normal, newimpactnormal);
831                                 }
832                         }
833                 }
834                 else
835                 {
836                         // moving out of brush
837                         if(d1 > 0)
838                                 return;
839                         if(d2 > 0)
840                         {
841                                 // leave
842                                 fendsolid = false;
843                                 f = (d1 + collision_leavenudge.value) / (d1 - d2);
844                                 if (leavefrac > f)
845                                         leavefrac = f;
846                         }
847                 }
848         }
849
850         brushsolid = trace->hitsupercontentsmask & thatbrush_start->supercontents;
851         if (fstartsolid)
852         {
853                 trace->startsupercontents |= thatbrush_start->supercontents;
854                 if (brushsolid)
855                 {
856                         trace->startsolid = true;
857                         if (fendsolid)
858                                 trace->allsolid = true;
859                 }
860         }
861
862         // LordHavoc: we need an epsilon nudge here because for a point trace the
863         // penetrating line segment is normally zero length if this brush was
864         // generated from a polygon (infinitely thin), and could even be slightly
865         // positive or negative due to rounding errors in that case.
866         if (brushsolid && enterfrac > -1 && enterfrac < trace->realfraction && enterfrac - (1.0f / 1024.0f) <= leavefrac)
867         {
868 #if 0
869                 // broken
870                 if (thatbrush_start->ispolygon)
871                 {
872                         d1 = nearestplanedist_float(thatbrush_start->planes[0].normal, thisbrush_start->points, thisbrush_start->numpoints) - thatbrush_start->planes[0].dist - collision_startnudge.value;
873                         d2 = nearestplanedist_float(thatbrush_end->planes[0].normal, thisbrush_end->points, thisbrush_end->numpoints) - thatbrush_end->planes[0].dist - collision_endnudge.value;
874                         move = d1 - d2;
875                         if (move <= 0 || d2 > collision_enternudge.value || d1 < 0)
876                                 return;
877                         // enter
878                         imove = 1 / move;
879                         enterfrac = (d1 - collision_enternudge.value) * imove;
880                         if (enterfrac < trace->realfraction)
881                         {
882                                 enterfrac2 = enterfrac - collision_impactnudge.value * imove;
883                                 trace->realfraction = bound(0, enterfrac, 1);
884                                 trace->fraction = bound(0, enterfrac2, 1);
885                                 VectorLerp(thatbrush_start->planes[0].normal, enterfrac, thatbrush_end->planes[0].normal, trace->plane.normal);
886                         }
887                 }
888                 else
889 #endif
890                 {
891                         trace->realfraction = bound(0, enterfrac, 1);
892                         trace->fraction = bound(0, enterfrac2, 1);
893                         VectorCopy(newimpactnormal, trace->plane.normal);
894                 }
895         }
896 }
897
898 // NOTE: start and end brush pair must have same numplanes/numpoints
899 void Collision_TraceLineBrushFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const colbrushf_t *thatbrush_start, const colbrushf_t *thatbrush_end)
900 {
901         int nplane, fstartsolid, fendsolid, brushsolid;
902         float enterfrac, leavefrac, d1, d2, f, imove, newimpactnormal[3], enterfrac2;
903         const colplanef_t *startplane, *endplane;
904
905         enterfrac = -1;
906         enterfrac2 = -1;
907         leavefrac = 1;
908         fstartsolid = true;
909         fendsolid = true;
910
911         for (nplane = 0;nplane < thatbrush_start->numplanes;nplane++)
912         {
913                 startplane = thatbrush_start->planes + nplane;
914                 endplane = thatbrush_end->planes + nplane;
915                 d1 = DotProduct(startplane->normal, linestart) - startplane->dist - collision_startnudge.value;
916                 d2 = DotProduct(endplane->normal, lineend) - endplane->dist - collision_endnudge.value;
917                 if (developer.integer)
918                 {
919                         // any brush with degenerate planes is not worth handling
920                         if (DotProduct(startplane->normal, startplane->normal) < 0.9f || DotProduct(endplane->normal, endplane->normal) < 0.9f)
921                         {
922                                 Con_Print("Collision_TraceLineBrushFloat: degenerate plane!\n");
923                                 return;
924                         }
925                         if (thatbrush_start->numpoints)
926                         {
927                                 f = furthestplanedist_float(startplane->normal, thatbrush_start->points, thatbrush_start->numpoints);
928                                 if (fabs(f - startplane->dist) > 0.125f)
929                                         Con_Printf("startplane->dist %f != calculated %f\n", startplane->dist, f);
930                         }
931                 }
932
933                 if (d1 > d2)
934                 {
935                         // moving into brush
936                         if (d2 > 0)
937                                 return;
938                         if (d1 > 0)
939                         {
940                                 // enter
941                                 fstartsolid = false;
942                                 imove = 1 / (d1 - d2);
943                                 f = (d1 - collision_enternudge.value) * imove;
944                                 if (enterfrac < f)
945                                 {
946                                         enterfrac = f;
947                                         enterfrac2 = f - collision_impactnudge.value * imove;
948                                         VectorLerp(startplane->normal, enterfrac, endplane->normal, newimpactnormal);
949                                 }
950                         }
951                 }
952                 else
953                 {
954                         // moving out of brush
955                         if (d1 > 0)
956                                 return;
957                         if (d2 > 0)
958                         {
959                                 // leave
960                                 fendsolid = false;
961                                 f = (d1 + collision_leavenudge.value) / (d1 - d2);
962                                 if (leavefrac > f)
963                                         leavefrac = f;
964                         }
965                 }
966         }
967
968         brushsolid = trace->hitsupercontentsmask & thatbrush_start->supercontents;
969         if (fstartsolid)
970         {
971                 trace->startsupercontents |= thatbrush_start->supercontents;
972                 if (brushsolid)
973                 {
974                         trace->startsolid = true;
975                         if (fendsolid)
976                                 trace->allsolid = true;
977                 }
978         }
979
980         // LordHavoc: we need an epsilon nudge here because for a point trace the
981         // penetrating line segment is normally zero length if this brush was
982         // generated from a polygon (infinitely thin), and could even be slightly
983         // positive or negative due to rounding errors in that case.
984         if (brushsolid && enterfrac > -1 && enterfrac < trace->realfraction && enterfrac - (1.0f / 1024.0f) <= leavefrac)
985         {
986 #if 0
987                 // broken
988                 if (thatbrush_start->ispolygon)
989                 {
990                         d1 = DotProduct(thatbrush_start->planes[0].normal, linestart) - thatbrush_start->planes[0].dist - collision_startnudge.value;
991                         d2 = DotProduct(thatbrush_end->planes[0].normal, lineend) - thatbrush_end->planes[0].dist - collision_endnudge.value;
992                         move = d1 - d2;
993                         if (move <= 0 || d2 > collision_enternudge.value || d1 < 0)
994                                 return;
995                         // enter
996                         imove = 1 / move;
997                         enterfrac = (d1 - collision_enternudge.value) * imove;
998                         if (enterfrac < trace->realfraction)
999                         {
1000                                 enterfrac2 = enterfrac - collision_impactnudge.value * imove;
1001                                 trace->realfraction = bound(0, enterfrac, 1);
1002                                 trace->fraction = bound(0, enterfrac2, 1);
1003                                 VectorLerp(thatbrush_start->planes[0].normal, enterfrac, thatbrush_end->planes[0].normal, trace->plane.normal);
1004                         }
1005                 }
1006                 else
1007 #endif
1008                 {
1009                         trace->realfraction = bound(0, enterfrac, 1);
1010                         trace->fraction = bound(0, enterfrac2, 1);
1011                         VectorCopy(newimpactnormal, trace->plane.normal);
1012                 }
1013         }
1014 }
1015
1016 void Collision_TracePointBrushFloat(trace_t *trace, const vec3_t point, const colbrushf_t *thatbrush)
1017 {
1018         int nplane;
1019         const colplanef_t *plane;
1020
1021         for (nplane = 0, plane = thatbrush->planes;nplane < thatbrush->numplanes;nplane++, plane++)
1022                 if (DotProduct(plane->normal, point) > plane->dist)
1023                         return;
1024
1025         trace->startsupercontents |= thatbrush->supercontents;
1026         if (trace->hitsupercontentsmask & thatbrush->supercontents)
1027         {
1028                 trace->startsolid = true;
1029                 trace->allsolid = true;
1030         }
1031 }
1032
1033 static colpointf_t polyf_points[256];
1034 static colplanef_t polyf_planes[256 + 2];
1035 static colbrushf_t polyf_brush;
1036
1037 void Collision_SnapCopyPoints(int numpoints, const colpointf_t *in, colpointf_t *out, float fractionprecision, float invfractionprecision)
1038 {
1039         while (numpoints--)
1040         {
1041                 out->v[0] = floor(in->v[0] * fractionprecision + 0.5f) * invfractionprecision;
1042                 out->v[1] = floor(in->v[1] * fractionprecision + 0.5f) * invfractionprecision;
1043                 out->v[2] = floor(in->v[2] * fractionprecision + 0.5f) * invfractionprecision;
1044         }
1045 }
1046
1047 void Collision_TraceBrushPolygonFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int numpoints, const float *points, int supercontents)
1048 {
1049         if (numpoints > 256)
1050         {
1051                 Con_Print("Polygon with more than 256 points not supported yet (fixme!)\n");
1052                 return;
1053         }
1054         polyf_brush.numpoints = numpoints;
1055         polyf_brush.numplanes = numpoints + 2;
1056         //polyf_brush.points = (colpointf_t *)points;
1057         polyf_brush.planes = polyf_planes;
1058         polyf_brush.supercontents = supercontents;
1059         polyf_brush.points = polyf_points;
1060         Collision_SnapCopyPoints(numpoints, (colpointf_t *)points, polyf_points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1061         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
1062         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
1063         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &polyf_brush, &polyf_brush);
1064 }
1065
1066 void Collision_TraceBrushTriangleMeshFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int numtriangles, const int *element3i, const float *vertex3f, int supercontents, const vec3_t segmentmins, const vec3_t segmentmaxs)
1067 {
1068         int i;
1069         float facemins[3], facemaxs[3];
1070         polyf_brush.numpoints = 3;
1071         polyf_brush.numplanes = 5;
1072         polyf_brush.points = polyf_points;
1073         polyf_brush.planes = polyf_planes;
1074         polyf_brush.supercontents = supercontents;
1075         for (i = 0;i < numtriangles;i++, element3i += 3)
1076         {
1077                 VectorCopy(vertex3f + element3i[0] * 3, polyf_points[0].v);
1078                 VectorCopy(vertex3f + element3i[1] * 3, polyf_points[1].v);
1079                 VectorCopy(vertex3f + element3i[2] * 3, polyf_points[2].v);
1080                 Collision_SnapCopyPoints(3, polyf_points, polyf_points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1081                 facemins[0] = min(polyf_points[0].v[0], min(polyf_points[1].v[0], polyf_points[2].v[0])) - 1;
1082                 facemins[1] = min(polyf_points[0].v[1], min(polyf_points[1].v[1], polyf_points[2].v[1])) - 1;
1083                 facemins[2] = min(polyf_points[0].v[2], min(polyf_points[1].v[2], polyf_points[2].v[2])) - 1;
1084                 facemaxs[0] = max(polyf_points[0].v[0], max(polyf_points[1].v[0], polyf_points[2].v[0])) + 1;
1085                 facemaxs[1] = max(polyf_points[0].v[1], max(polyf_points[1].v[1], polyf_points[2].v[1])) + 1;
1086                 facemaxs[2] = max(polyf_points[0].v[2], max(polyf_points[1].v[2], polyf_points[2].v[2])) + 1;
1087                 if (BoxesOverlap(segmentmins, segmentmaxs, facemins, facemaxs))
1088                 {
1089                         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
1090                         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
1091                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &polyf_brush, &polyf_brush);
1092                 }
1093         }
1094 }
1095
1096 void Collision_TraceLinePolygonFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, int numpoints, const float *points, int supercontents)
1097 {
1098         if (numpoints > 256)
1099         {
1100                 Con_Print("Polygon with more than 256 points not supported yet (fixme!)\n");
1101                 return;
1102         }
1103         polyf_brush.numpoints = numpoints;
1104         polyf_brush.numplanes = numpoints + 2;
1105         //polyf_brush.points = (colpointf_t *)points;
1106         polyf_brush.points = polyf_points;
1107         Collision_SnapCopyPoints(numpoints, (colpointf_t *)points, polyf_points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1108         polyf_brush.planes = polyf_planes;
1109         polyf_brush.supercontents = supercontents;
1110         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
1111         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
1112         Collision_TraceLineBrushFloat(trace, linestart, lineend, &polyf_brush, &polyf_brush);
1113 }
1114
1115 void Collision_TraceLineTriangleMeshFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, int numtriangles, const int *element3i, const float *vertex3f, int supercontents, const vec3_t segmentmins, const vec3_t segmentmaxs)
1116 {
1117         int i;
1118 #if 1
1119         // FIXME: snap vertices?
1120         for (i = 0;i < numtriangles;i++, element3i += 3)
1121                 Collision_TraceLineTriangleFloat(trace, linestart, lineend, vertex3f + element3i[0] * 3, vertex3f + element3i[1] * 3, vertex3f + element3i[2] * 3);
1122 #else
1123         polyf_brush.numpoints = 3;
1124         polyf_brush.numplanes = 5;
1125         polyf_brush.points = polyf_points;
1126         polyf_brush.planes = polyf_planes;
1127         polyf_brush.supercontents = supercontents;
1128         for (i = 0;i < numtriangles;i++, element3i += 3)
1129         {
1130                 float facemins[3], facemaxs[3];
1131                 VectorCopy(vertex3f + element3i[0] * 3, polyf_points[0].v);
1132                 VectorCopy(vertex3f + element3i[1] * 3, polyf_points[1].v);
1133                 VectorCopy(vertex3f + element3i[2] * 3, polyf_points[2].v);
1134                 Collision_SnapCopyPoints(numpoints, polyf_points, polyf_points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1135                 facemins[0] = min(polyf_points[0].v[0], min(polyf_points[1].v[0], polyf_points[2].v[0])) - 1;
1136                 facemins[1] = min(polyf_points[0].v[1], min(polyf_points[1].v[1], polyf_points[2].v[1])) - 1;
1137                 facemins[2] = min(polyf_points[0].v[2], min(polyf_points[1].v[2], polyf_points[2].v[2])) - 1;
1138                 facemaxs[0] = max(polyf_points[0].v[0], max(polyf_points[1].v[0], polyf_points[2].v[0])) + 1;
1139                 facemaxs[1] = max(polyf_points[0].v[1], max(polyf_points[1].v[1], polyf_points[2].v[1])) + 1;
1140                 facemaxs[2] = max(polyf_points[0].v[2], max(polyf_points[1].v[2], polyf_points[2].v[2])) + 1;
1141                 if (BoxesOverlap(segmentmins, segmentmaxs, facemins, facemaxs))
1142                 {
1143                         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
1144                         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
1145                         Collision_TraceLineBrushFloat(trace, linestart, lineend, &polyf_brush, &polyf_brush);
1146                 }
1147         }
1148 #endif
1149 }
1150
1151
1152 static colpointf_t polyf_pointsstart[256], polyf_pointsend[256];
1153 static colplanef_t polyf_planesstart[256 + 2], polyf_planesend[256 + 2];
1154 static colbrushf_t polyf_brushstart, polyf_brushend;
1155
1156 void Collision_TraceBrushPolygonTransformFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int numpoints, const float *points, const matrix4x4_t *polygonmatrixstart, const matrix4x4_t *polygonmatrixend, int supercontents)
1157 {
1158         int i;
1159         if (numpoints > 256)
1160         {
1161                 Con_Print("Polygon with more than 256 points not supported yet (fixme!)\n");
1162                 return;
1163         }
1164         polyf_brushstart.numpoints = numpoints;
1165         polyf_brushstart.numplanes = numpoints + 2;
1166         polyf_brushstart.points = polyf_pointsstart;//(colpointf_t *)points;
1167         polyf_brushstart.planes = polyf_planesstart;
1168         polyf_brushstart.supercontents = supercontents;
1169         for (i = 0;i < numpoints;i++)
1170                 Matrix4x4_Transform(polygonmatrixstart, points + i * 3, polyf_brushstart.points[i].v);
1171         polyf_brushend.numpoints = numpoints;
1172         polyf_brushend.numplanes = numpoints + 2;
1173         polyf_brushend.points = polyf_pointsend;//(colpointf_t *)points;
1174         polyf_brushend.planes = polyf_planesend;
1175         polyf_brushend.supercontents = supercontents;
1176         for (i = 0;i < numpoints;i++)
1177                 Matrix4x4_Transform(polygonmatrixend, points + i * 3, polyf_brushend.points[i].v);
1178         Collision_SnapCopyPoints(numpoints, polyf_pointsstart, polyf_pointsstart, COLLISION_SNAPSCALE, COLLISION_SNAP);
1179         Collision_SnapCopyPoints(numpoints, polyf_pointsend, polyf_pointsend, COLLISION_SNAPSCALE, COLLISION_SNAP);
1180         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brushstart);
1181         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brushend);
1182
1183         //Collision_PrintBrushAsQHull(&polyf_brushstart, "polyf_brushstart");
1184         //Collision_PrintBrushAsQHull(&polyf_brushend, "polyf_brushend");
1185
1186         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &polyf_brushstart, &polyf_brushend);
1187 }
1188
1189
1190
1191 #define MAX_BRUSHFORBOX 16
1192 static int brushforbox_index = 0;
1193 static colpointf_t brushforbox_point[MAX_BRUSHFORBOX*8];
1194 static colplanef_t brushforbox_plane[MAX_BRUSHFORBOX*6];
1195 static colbrushf_t brushforbox_brush[MAX_BRUSHFORBOX];
1196 static colbrushf_t brushforpoint_brush[MAX_BRUSHFORBOX];
1197
1198 void Collision_InitBrushForBox(void)
1199 {
1200         int i;
1201         for (i = 0;i < MAX_BRUSHFORBOX;i++)
1202         {
1203                 brushforbox_brush[i].supercontents = SUPERCONTENTS_SOLID;
1204                 brushforbox_brush[i].numpoints = 8;
1205                 brushforbox_brush[i].numplanes = 6;
1206                 brushforbox_brush[i].points = brushforbox_point + i * 8;
1207                 brushforbox_brush[i].planes = brushforbox_plane + i * 6;
1208                 brushforpoint_brush[i].supercontents = SUPERCONTENTS_SOLID;
1209                 brushforpoint_brush[i].numpoints = 1;
1210                 brushforpoint_brush[i].numplanes = 0;
1211                 brushforpoint_brush[i].points = brushforbox_point + i * 8;
1212                 brushforpoint_brush[i].planes = brushforbox_plane + i * 6;
1213         }
1214 }
1215
1216 colbrushf_t *Collision_BrushForBox(const matrix4x4_t *matrix, const vec3_t mins, const vec3_t maxs)
1217 {
1218         int i, j;
1219         vec3_t v;
1220         colbrushf_t *brush;
1221         if (brushforbox_brush[0].numpoints == 0)
1222                 Collision_InitBrushForBox();
1223         // FIXME: these probably don't actually need to be normalized if the collision code does not care
1224         if (VectorCompare(mins, maxs))
1225         {
1226                 // point brush
1227                 brush = brushforpoint_brush + ((brushforbox_index++) % MAX_BRUSHFORBOX);
1228                 VectorCopy(mins, brush->points->v);
1229         }
1230         else
1231         {
1232                 brush = brushforbox_brush + ((brushforbox_index++) % MAX_BRUSHFORBOX);
1233                 // FIXME: optimize
1234                 for (i = 0;i < 8;i++)
1235                 {
1236                         v[0] = i & 1 ? maxs[0] : mins[0];
1237                         v[1] = i & 2 ? maxs[1] : mins[1];
1238                         v[2] = i & 4 ? maxs[2] : mins[2];
1239                         Matrix4x4_Transform(matrix, v, brush->points[i].v);
1240                 }
1241                 // FIXME: optimize!
1242                 for (i = 0;i < 6;i++)
1243                 {
1244                         VectorClear(v);
1245                         v[i >> 1] = i & 1 ? 1 : -1;
1246                         Matrix4x4_Transform3x3(matrix, v, brush->planes[i].normal);
1247                         VectorNormalize(brush->planes[i].normal);
1248                 }
1249         }
1250         for (j = 0;j < brush->numplanes;j++)
1251                 brush->planes[j].dist = furthestplanedist_float(brush->planes[j].normal, brush->points, brush->numpoints);
1252         VectorCopy(brush->points[0].v, brush->mins);
1253         VectorCopy(brush->points[0].v, brush->maxs);
1254         for (j = 1;j < brush->numpoints;j++)
1255         {
1256                 brush->mins[0] = min(brush->mins[0], brush->points[j].v[0]);
1257                 brush->mins[1] = min(brush->mins[1], brush->points[j].v[1]);
1258                 brush->mins[2] = min(brush->mins[2], brush->points[j].v[2]);
1259                 brush->maxs[0] = max(brush->maxs[0], brush->points[j].v[0]);
1260                 brush->maxs[1] = max(brush->maxs[1], brush->points[j].v[1]);
1261                 brush->maxs[2] = max(brush->maxs[2], brush->points[j].v[2]);
1262         }
1263         brush->mins[0] -= 1;
1264         brush->mins[1] -= 1;
1265         brush->mins[2] -= 1;
1266         brush->maxs[0] += 1;
1267         brush->maxs[1] += 1;
1268         brush->maxs[2] += 1;
1269         Collision_ValidateBrush(brush);
1270         return brush;
1271 }
1272
1273 void Collision_ClipTrace_BrushBox(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)
1274 {
1275         colbrushf_t *boxbrush, *thisbrush_start, *thisbrush_end;
1276         matrix4x4_t identitymatrix;
1277         vec3_t startmins, startmaxs, endmins, endmaxs;
1278
1279         // create brushes for the collision
1280         VectorAdd(start, mins, startmins);
1281         VectorAdd(start, maxs, startmaxs);
1282         VectorAdd(end, mins, endmins);
1283         VectorAdd(end, maxs, endmaxs);
1284         Matrix4x4_CreateIdentity(&identitymatrix);
1285         boxbrush = Collision_BrushForBox(&identitymatrix, cmins, cmaxs);
1286         thisbrush_start = Collision_BrushForBox(&identitymatrix, startmins, startmaxs);
1287         thisbrush_end = Collision_BrushForBox(&identitymatrix, endmins, endmaxs);
1288
1289         memset(trace, 0, sizeof(trace_t));
1290         trace->hitsupercontentsmask = hitsupercontentsmask;
1291         trace->fraction = 1;
1292         trace->realfraction = 1;
1293         trace->allsolid = true;
1294         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, boxbrush, boxbrush);
1295 }
1296
1297 // LordHavoc: currently unused and not yet tested
1298 // note: this can be used for tracing a moving sphere vs a stationary sphere,
1299 // by simply adding the moving sphere's radius to the sphereradius parameter,
1300 // all the results are correct (impactpoint, impactnormal, and fraction)
1301 float Collision_ClipTrace_Line_Sphere(double *linestart, double *lineend, double *sphereorigin, double sphereradius, double *impactpoint, double *impactnormal)
1302 {
1303         double dir[3], scale, v[3], deviationdist, impactdist, linelength;
1304         // make sure the impactpoint and impactnormal are valid even if there is
1305         // no collision
1306         impactpoint[0] = lineend[0];
1307         impactpoint[1] = lineend[1];
1308         impactpoint[2] = lineend[2];
1309         impactnormal[0] = 0;
1310         impactnormal[1] = 0;
1311         impactnormal[2] = 0;
1312         // calculate line direction
1313         dir[0] = lineend[0] - linestart[0];
1314         dir[1] = lineend[1] - linestart[1];
1315         dir[2] = lineend[2] - linestart[2];
1316         // normalize direction
1317         linelength = sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]);
1318         if (linelength)
1319         {
1320                 scale = 1.0 / linelength;
1321                 dir[0] *= scale;
1322                 dir[1] *= scale;
1323                 dir[2] *= scale;
1324         }
1325         // this dotproduct calculates the distance along the line at which the
1326         // sphere origin is (nearest point to the sphere origin on the line)
1327         impactdist = dir[0] * (sphereorigin[0] - linestart[0]) + dir[1] * (sphereorigin[1] - linestart[1]) + dir[2] * (sphereorigin[2] - linestart[2]);
1328         // calculate point on line at that distance, and subtract the
1329         // sphereorigin from it, so we have a vector to measure for the distance
1330         // of the line from the sphereorigin (deviation, how off-center it is)
1331         v[0] = linestart[0] + impactdist * dir[0] - sphereorigin[0];
1332         v[1] = linestart[1] + impactdist * dir[1] - sphereorigin[1];
1333         v[2] = linestart[2] + impactdist * dir[2] - sphereorigin[2];
1334         deviationdist = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
1335         // if outside the radius, it's a miss for sure
1336         // (we do this comparison using squared radius to avoid a sqrt)
1337         if (deviationdist > sphereradius*sphereradius)
1338                 return 1; // miss (off to the side)
1339         // nudge back to find the correct impact distance
1340         impactdist += (sqrt(deviationdist) - sphereradius);
1341         if (impactdist >= linelength)
1342                 return 1; // miss (not close enough)
1343         if (impactdist < 0)
1344                 return 1; // miss (linestart is past or inside sphere)
1345         // calculate new impactpoint
1346         impactpoint[0] = linestart[0] + impactdist * dir[0];
1347         impactpoint[1] = linestart[1] + impactdist * dir[1];
1348         impactpoint[2] = linestart[2] + impactdist * dir[2];
1349         // calculate impactnormal (surface normal at point of impact)
1350         impactnormal[0] = impactpoint[0] - sphereorigin[0];
1351         impactnormal[1] = impactpoint[1] - sphereorigin[1];
1352         impactnormal[2] = impactpoint[2] - sphereorigin[2];
1353         // normalize impactnormal
1354         scale = impactnormal[0] * impactnormal[0] + impactnormal[1] * impactnormal[1] + impactnormal[2] * impactnormal[2];
1355         if (scale)
1356         {
1357                 scale = 1.0 / sqrt(scale);
1358                 impactnormal[0] *= scale;
1359                 impactnormal[1] *= scale;
1360                 impactnormal[2] *= scale;
1361         }
1362         // return fraction of movement distance
1363         return impactdist / linelength;
1364 }
1365
1366 void Collision_TraceLineTriangleFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const float *point0, const float *point1, const float *point2)
1367 {
1368 #if 1
1369         // more optimized
1370         float d1, d2, d, f, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, faceplanenormallength2, edge01[3], edge21[3], edge02[3];
1371
1372         // this function executes:
1373         // 32 ops when line starts behind triangle
1374         // 38 ops when line ends infront of triangle
1375         // 43 ops when line fraction is already closer than this triangle
1376         // 72 ops when line is outside edge 01
1377         // 92 ops when line is outside edge 21
1378         // 115 ops when line is outside edge 02
1379         // 123 ops when line impacts triangle and updates trace results
1380
1381         // this code is designed for clockwise triangles, conversion to
1382         // counterclockwise would require swapping some things around...
1383         // it is easier to simply swap the point0 and point2 parameters to this
1384         // function when calling it than it is to rewire the internals.
1385
1386         // calculate the faceplanenormal of the triangle, this represents the front side
1387         // 15 ops
1388         VectorSubtract(point0, point1, edge01);
1389         VectorSubtract(point2, point1, edge21);
1390         CrossProduct(edge01, edge21, faceplanenormal);
1391         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
1392         // 6 ops
1393         faceplanenormallength2 = DotProduct(faceplanenormal, faceplanenormal);
1394         if (faceplanenormallength2 < 0.0001f)
1395                 return;
1396         // calculate the distance
1397         // 5 ops
1398         faceplanedist = DotProduct(point0, faceplanenormal);
1399
1400         // if start point is on the back side there is no collision
1401         // (we don't care about traces going through the triangle the wrong way)
1402
1403         // calculate the start distance
1404         // 6 ops
1405         d1 = DotProduct(faceplanenormal, linestart);
1406         if (d1 <= faceplanedist)
1407                 return;
1408
1409         // calculate the end distance
1410         // 6 ops
1411         d2 = DotProduct(faceplanenormal, lineend);
1412         // if both are in front, there is no collision
1413         if (d2 >= faceplanedist)
1414                 return;
1415
1416         // from here on we know d1 is >= 0 and d2 is < 0
1417         // this means the line starts infront and ends behind, passing through it
1418
1419         // calculate the recipricol of the distance delta,
1420         // so we can use it multiple times cheaply (instead of division)
1421         // 2 ops
1422         d = 1.0f / (d1 - d2);
1423         // calculate the impact fraction by taking the start distance (> 0)
1424         // and subtracting the face plane distance (this is the distance of the
1425         // triangle along that same normal)
1426         // then multiply by the recipricol distance delta
1427         // 2 ops
1428         f = (d1 - faceplanedist) * d;
1429         // skip out if this impact is further away than previous ones
1430         // 1 ops
1431         if (f > trace->realfraction)
1432                 return;
1433         // calculate the perfect impact point for classification of insidedness
1434         // 9 ops
1435         impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1436         impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1437         impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1438
1439         // calculate the edge normal and reject if impact is outside triangle
1440         // (an edge normal faces away from the triangle, to get the desired normal
1441         //  a crossproduct with the faceplanenormal is used, and because of the way
1442         // the insidedness comparison is written it does not need to be normalized)
1443
1444         // first use the two edges from the triangle plane math
1445         // the other edge only gets calculated if the point survives that long
1446
1447         // 20 ops
1448         CrossProduct(edge01, faceplanenormal, edgenormal);
1449         if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1450                 return;
1451
1452         // 20 ops
1453         CrossProduct(faceplanenormal, edge21, edgenormal);
1454         if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1455                 return;
1456
1457         // 23 ops
1458         VectorSubtract(point0, point2, edge02);
1459         CrossProduct(faceplanenormal, edge02, edgenormal);
1460         if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1461                 return;
1462
1463         // 8 ops (rare)
1464
1465         // store the new trace fraction
1466         trace->realfraction = f;
1467
1468         // calculate a nudged fraction to keep it out of the surface
1469         // (the main fraction remains perfect)
1470         trace->fraction = f - collision_impactnudge.value * d;
1471
1472         // store the new trace plane (because collisions only happen from
1473         // the front this is always simply the triangle normal, never flipped)
1474         d = 1.0 / sqrt(faceplanenormallength2);
1475         VectorScale(faceplanenormal, d, trace->plane.normal);
1476         trace->plane.dist = faceplanedist * d;
1477 #else
1478         float d1, d2, d, f, fnudged, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, edge[3];
1479
1480         // this code is designed for clockwise triangles, conversion to
1481         // counterclockwise would require swapping some things around...
1482         // it is easier to simply swap the point0 and point2 parameters to this
1483         // function when calling it than it is to rewire the internals.
1484
1485         // calculate the unnormalized faceplanenormal of the triangle,
1486         // this represents the front side
1487         TriangleNormal(point0, point1, point2, faceplanenormal);
1488         // there's no point in processing a degenerate triangle
1489         // (GIGO - Garbage In, Garbage Out)
1490         if (DotProduct(faceplanenormal, faceplanenormal) < 0.0001f)
1491                 return;
1492         // calculate the unnormalized distance
1493         faceplanedist = DotProduct(point0, faceplanenormal);
1494
1495         // calculate the unnormalized start distance
1496         d1 = DotProduct(faceplanenormal, linestart) - faceplanedist;
1497         // if start point is on the back side there is no collision
1498         // (we don't care about traces going through the triangle the wrong way)
1499         if (d1 <= 0)
1500                 return;
1501
1502         // calculate the unnormalized end distance
1503         d2 = DotProduct(faceplanenormal, lineend) - faceplanedist;
1504         // if both are in front, there is no collision
1505         if (d2 >= 0)
1506                 return;
1507
1508         // from here on we know d1 is >= 0 and d2 is < 0
1509         // this means the line starts infront and ends behind, passing through it
1510
1511         // calculate the recipricol of the distance delta,
1512         // so we can use it multiple times cheaply (instead of division)
1513         d = 1.0f / (d1 - d2);
1514         // calculate the impact fraction by taking the start distance (> 0)
1515         // and subtracting the face plane distance (this is the distance of the
1516         // triangle along that same normal)
1517         // then multiply by the recipricol distance delta
1518         f = d1 * d;
1519         // skip out if this impact is further away than previous ones
1520         if (f > trace->realfraction)
1521                 return;
1522         // calculate the perfect impact point for classification of insidedness
1523         impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1524         impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1525         impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1526
1527         // calculate the edge normal and reject if impact is outside triangle
1528         // (an edge normal faces away from the triangle, to get the desired normal
1529         //  a crossproduct with the faceplanenormal is used, and because of the way
1530         // the insidedness comparison is written it does not need to be normalized)
1531
1532         VectorSubtract(point2, point0, edge);
1533         CrossProduct(edge, faceplanenormal, edgenormal);
1534         if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1535                 return;
1536
1537         VectorSubtract(point0, point1, edge);
1538         CrossProduct(edge, faceplanenormal, edgenormal);
1539         if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1540                 return;
1541
1542         VectorSubtract(point1, point2, edge);
1543         CrossProduct(edge, faceplanenormal, edgenormal);
1544         if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1545                 return;
1546
1547         // store the new trace fraction
1548         trace->realfraction = bound(0, f, 1);
1549
1550         // store the new trace plane (because collisions only happen from
1551         // the front this is always simply the triangle normal, never flipped)
1552         VectorNormalize(faceplanenormal);
1553         VectorCopy(faceplanenormal, trace->plane.normal);
1554         trace->plane.dist = DotProduct(point0, faceplanenormal);
1555
1556         // calculate the normalized start and end distances
1557         d1 = DotProduct(trace->plane.normal, linestart) - trace->plane.dist;
1558         d2 = DotProduct(trace->plane.normal, lineend) - trace->plane.dist;
1559
1560         // calculate a nudged fraction to keep it out of the surface
1561         // (the main fraction remains perfect)
1562         fnudged = (d1 - collision_impactnudge.value) / (d1 - d2);
1563         trace->fraction = bound(0, fnudged, 1);
1564
1565         // store the new trace endpos
1566         // not needed, it's calculated later when the trace is finished
1567         //trace->endpos[0] = linestart[0] + fnudged * (lineend[0] - linestart[0]);
1568         //trace->endpos[1] = linestart[1] + fnudged * (lineend[1] - linestart[1]);
1569         //trace->endpos[2] = linestart[2] + fnudged * (lineend[2] - linestart[2]);
1570 #endif
1571 }
1572
1573 typedef struct colbspnode_s
1574 {
1575         mplane_t plane;
1576         struct colbspnode_s *children[2];
1577         // the node is reallocated or split if max is reached
1578         int numcolbrushf;
1579         int maxcolbrushf;
1580         colbrushf_t **colbrushflist;
1581         //int numcolbrushd;
1582         //int maxcolbrushd;
1583         //colbrushd_t **colbrushdlist;
1584 }
1585 colbspnode_t;
1586
1587 typedef struct colbsp_s
1588 {
1589         mempool_t *mempool;
1590         colbspnode_t *nodes;
1591 }
1592 colbsp_t;
1593
1594 colbsp_t *Collision_CreateCollisionBSP(mempool_t *mempool)
1595 {
1596         colbsp_t *bsp;
1597         bsp = Mem_Alloc(mempool, sizeof(colbsp_t));
1598         bsp->mempool = mempool;
1599         bsp->nodes = Mem_Alloc(bsp->mempool, sizeof(colbspnode_t));
1600         return bsp;
1601 }
1602
1603 void Collision_FreeCollisionBSPNode(colbspnode_t *node)
1604 {
1605         if (node->children[0])
1606                 Collision_FreeCollisionBSPNode(node->children[0]);
1607         if (node->children[1])
1608                 Collision_FreeCollisionBSPNode(node->children[1]);
1609         while (--node->numcolbrushf)
1610                 Mem_Free(node->colbrushflist[node->numcolbrushf]);
1611         //while (--node->numcolbrushd)
1612         //      Mem_Free(node->colbrushdlist[node->numcolbrushd]);
1613         Mem_Free(node);
1614 }
1615
1616 void Collision_FreeCollisionBSP(colbsp_t *bsp)
1617 {
1618         Collision_FreeCollisionBSPNode(bsp->nodes);
1619         Mem_Free(bsp);
1620 }
1621
1622 void Collision_BoundingBoxOfBrushTraceSegment(const colbrushf_t *start, const colbrushf_t *end, vec3_t mins, vec3_t maxs, float startfrac, float endfrac)
1623 {
1624         int i;
1625         colpointf_t *ps, *pe;
1626         float tempstart[3], tempend[3];
1627         VectorLerp(start->points[0].v, startfrac, end->points[0].v, mins);
1628         VectorCopy(mins, maxs);
1629         for (i = 0, ps = start->points, pe = end->points;i < start->numpoints;i++, ps++, pe++)
1630         {
1631                 VectorLerp(ps->v, startfrac, pe->v, tempstart);
1632                 VectorLerp(ps->v, endfrac, pe->v, tempend);
1633                 mins[0] = min(mins[0], min(tempstart[0], tempend[0]));
1634                 mins[1] = min(mins[1], min(tempstart[1], tempend[1]));
1635                 mins[2] = min(mins[2], min(tempstart[2], tempend[2]));
1636                 maxs[0] = min(maxs[0], min(tempstart[0], tempend[0]));
1637                 maxs[1] = min(maxs[1], min(tempstart[1], tempend[1]));
1638                 maxs[2] = min(maxs[2], min(tempstart[2], tempend[2]));
1639         }
1640         mins[0] -= 1;
1641         mins[1] -= 1;
1642         mins[2] -= 1;
1643         maxs[0] += 1;
1644         maxs[1] += 1;
1645         maxs[2] += 1;
1646 }
1647