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