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