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