]> icculus.org git repositories - divverent/darkplaces.git/blob - collision.c
no more uses of %g in printf as it tends to lose precision too often (this caused...
[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;
293         if (!brush->numpoints)
294         {
295                 Con_Printf("Collision_ValidateBrush: brush with no points!\n");
296                 Collision_PrintBrushAsQHull(brush, "unnamed");
297                 return;
298         }
299         // it's ok for a brush to have one point and no planes...
300         if (brush->numplanes == 0 && brush->numpoints != 1)
301         {
302                 Con_Printf("Collision_ValidateBrush: brush with no planes and more than one point!\n");
303                 Collision_PrintBrushAsQHull(brush, "unnamed");
304                 return;
305         }
306         for (k = 0;k < brush->numplanes;k++)
307         {
308                 for (j = 0;j < brush->numpoints;j++)
309                 {
310                         if (DotProduct(brush->points[j].v, brush->planes[k].normal) - brush->planes[k].dist > (1.0f / 8.0f))
311                         {
312                                 Con_Printf("Collision_NewBrushFromPlanes: 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);
313                                 Collision_PrintBrushAsQHull(brush, "unnamed");
314                                 return;
315                         }
316                 }
317         }
318 }
319
320
321 colbrushf_t *Collision_NewBrushFromPlanes(mempool_t *mempool, int numoriginalplanes, const mplane_t *originalplanes, int supercontents)
322 {
323         int j, k, m;
324         int numpoints, maxpoints, numplanes, maxplanes, numelements, maxelements, numtriangles, numpolypoints, maxpolypoints;
325         winding_t *w;
326         colbrushf_t *brush;
327         colpointf_t pointsbuf[256];
328         colplanef_t planesbuf[256];
329         int elementsbuf[1024];
330         int polypointbuf[256];
331         // construct a collision brush (points, planes, and renderable mesh) from
332         // a set of planes, this also optimizes out any unnecessary planes (ones
333         // whose polygon is clipped away by the other planes)
334         numpoints = 0;maxpoints = 256;
335         numplanes = 0;maxplanes = 256;
336         numelements = 0;maxelements = 1024;
337         numtriangles = 0;
338         maxpolypoints = 256;
339         for (j = 0;j < numoriginalplanes;j++)
340         {
341                 // add the plane uniquely (no duplicates)
342                 for (k = 0;k < numplanes;k++)
343                         if (VectorCompare(planesbuf[k].normal, originalplanes[j].normal) && planesbuf[k].dist == originalplanes[j].dist)
344                                 break;
345                 // if the plane is a duplicate, skip it
346                 if (k < numplanes)
347                         continue;
348                 // check if there are too many and skip the brush
349                 if (numplanes >= 256)
350                 {
351                         Con_Printf("Mod_Q3BSP_LoadBrushes: failed to build collision brush: too many planes for buffer\n");
352                         return NULL;
353                 }
354
355                 // create a large polygon from the plane
356                 w = Winding_NewFromPlane(originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist);
357                 // clip it by all other planes
358                 for (k = 0;k < numoriginalplanes && w;k++)
359                 {
360                         if (k != j)
361                         {
362                                 // we want to keep the inside of the brush plane so we flip
363                                 // the cutting plane
364                                 w = Winding_Clip(w, -originalplanes[k].normal[0], -originalplanes[k].normal[1], -originalplanes[k].normal[2], -originalplanes[k].dist, true);
365                         }
366                 }
367                 // if nothing is left, skip it
368                 if (!w)
369                         continue;
370
371                 // copy off the number of points for later when the winding is freed
372                 numpolypoints = w->numpoints;
373
374                 // check if there are too many polygon vertices for buffer
375                 if (numpolypoints > maxpolypoints)
376                 {
377                         Con_Printf("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
378                         return NULL;
379                 }
380
381                 // check if there are too many triangle elements for buffer
382                 if (numelements + (w->numpoints - 2) * 3 > maxelements)
383                 {
384                         Con_Printf("Collision_NewBrushFromPlanes: failed to build collision brush: too many triangle elements for buffer\n");
385                         return NULL;
386                 }
387
388                 for (k = 0;k < w->numpoints;k++)
389                 {
390                         // check if there is already a matching point (no duplicates)
391                         for (m = 0;m < numpoints;m++)
392                                 if (VectorDistance2(w->points[k], pointsbuf[m].v) < DIST_EPSILON)
393                                         break;
394
395                         // if there is no match, add a new one
396                         if (m == numpoints)
397                         {
398                                 // check if there are too many and skip the brush
399                                 if (numpoints >= 256)
400                                 {
401                                         Con_Printf("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
402                                         Winding_Free(w);
403                                         return NULL;
404                                 }
405                                 // add the new one
406                                 VectorCopy(w->points[k], pointsbuf[numpoints].v);
407                                 numpoints++;
408                         }
409
410                         // store the index into a buffer
411                         polypointbuf[k] = m;
412                 }
413                 Winding_Free(w);
414                 w = NULL;
415
416                 // add the triangles for the polygon
417                 // (this particular code makes a triangle fan)
418                 for (k = 0;k < numpolypoints - 2;k++)
419                 {
420                         numtriangles++;
421                         elementsbuf[numelements++] = polypointbuf[0];
422                         elementsbuf[numelements++] = polypointbuf[k + 1];
423                         elementsbuf[numelements++] = polypointbuf[k + 2];
424                 }
425
426                 // add the new plane
427                 VectorCopy(originalplanes[j].normal, planesbuf[numplanes].normal);
428                 planesbuf[numplanes].dist = originalplanes[j].dist;
429                 numplanes++;
430         }
431
432         // if nothing is left, there's nothing to allocate
433         if (numtriangles < 4 || numplanes < 4 || numpoints < 4)
434                 return NULL;
435
436         // allocate the brush and copy to it
437         brush = Collision_AllocBrushFloat(mempool, numpoints, numplanes, numtriangles, supercontents);
438         memcpy(brush->points, pointsbuf, numpoints * sizeof(colpointf_t));
439         memcpy(brush->planes, planesbuf, numplanes * sizeof(colplanef_t));
440         memcpy(brush->elements, elementsbuf, numtriangles * sizeof(int[3]));
441         Collision_ValidateBrush(brush);
442         return brush;
443 }
444
445
446
447 colbrushf_t *Collision_AllocBrushFloat(mempool_t *mempool, int numpoints, int numplanes, int numtriangles, int supercontents)
448 {
449         colbrushf_t *brush;
450         brush = Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colpointf_t) * numpoints + sizeof(colplanef_t) * numplanes + sizeof(int[3]) * numtriangles);
451         brush->supercontents = supercontents;
452         brush->numplanes = numplanes;
453         brush->numpoints = numpoints;
454         brush->numtriangles = numtriangles;
455         brush->planes = (void *)(brush + 1);
456         brush->points = (void *)(brush->planes + brush->numplanes);
457         brush->elements = (void *)(brush->points + brush->numpoints);
458         return brush;
459 }
460
461 void Collision_CalcPlanesForPolygonBrushFloat(colbrushf_t *brush)
462 {
463         int i;
464         float edge0[3], edge1[3], normal[3], dist, bestdist;
465         colpointf_t *p, *p2;
466
467         // choose best surface normal for polygon's plane
468         bestdist = 0;
469         for (i = 0, p = brush->points + 1;i < brush->numpoints - 2;i++, p++)
470         {
471                 VectorSubtract(p[-1].v, p[0].v, edge0);
472                 VectorSubtract(p[1].v, p[0].v, edge1);
473                 CrossProduct(edge0, edge1, normal);
474                 dist = DotProduct(normal, normal);
475                 if (i == 0 || bestdist < dist)
476                 {
477                         bestdist = dist;
478                         VectorCopy(normal, brush->planes->normal);
479                 }
480         }
481
482         VectorNormalize(brush->planes->normal);
483         brush->planes->dist = DotProduct(brush->points->v, brush->planes->normal);
484
485         // negate plane to create other side
486         VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
487         brush->planes[1].dist = -brush->planes[0].dist;
488         for (i = 0, p = brush->points + (brush->numpoints - 1), p2 = brush->points;i < brush->numpoints;i++, p = p2, p2++)
489         {
490                 VectorSubtract(p->v, p2->v, edge0);
491                 CrossProduct(edge0, brush->planes->normal, brush->planes[i + 2].normal);
492                 VectorNormalize(brush->planes[i + 2].normal);
493                 brush->planes[i + 2].dist = DotProduct(p->v, brush->planes[i + 2].normal);
494         }
495
496 #if 1
497         // validity check - will be disabled later
498         for (i = 0;i < brush->numplanes;i++)
499         {
500                 int j;
501                 for (j = 0, p = brush->points;j < brush->numpoints;j++, p++)
502                         if (DotProduct(p->v, brush->planes[i].normal) > brush->planes[i].dist + (1.0 / 32.0))
503                                 Con_Printf("Error in brush plane generation, plane %i\n", i);
504         }
505 #endif
506 }
507
508 colbrushf_t *Collision_AllocBrushFromPermanentPolygonFloat(mempool_t *mempool, int numpoints, float *points, int supercontents)
509 {
510         colbrushf_t *brush;
511         brush = Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colplanef_t) * (numpoints + 2));
512         brush->supercontents = supercontents;
513         brush->numpoints = numpoints;
514         brush->numplanes = numpoints + 2;
515         brush->planes = (void *)(brush + 1);
516         brush->points = (colpointf_t *)points;
517         Host_Error("Collision_AllocBrushFromPermanentPolygonFloat: FIXME: this code needs to be updated to generate a mesh...\n");
518         return brush;
519 }
520
521 float nearestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
522 {
523         float dist, bestdist;
524         bestdist = DotProduct(points->v, normal);
525         points++;
526         while(--numpoints)
527         {
528                 dist = DotProduct(points->v, normal);
529                 bestdist = min(bestdist, dist);
530                 points++;
531         }
532         return bestdist;
533 }
534
535 float furthestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
536 {
537         float dist, bestdist;
538         bestdist = DotProduct(points->v, normal);
539         points++;
540         while(--numpoints)
541         {
542                 dist = DotProduct(points->v, normal);
543                 bestdist = max(bestdist, dist);
544                 points++;
545         }
546         return bestdist;
547 }
548
549 #define COLLISIONEPSILON (1.0f / 32.0f)
550 #define COLLISIONEPSILON2 0//(1.0f / 32.0f)
551
552 // NOTE: start and end of each brush pair must have same numplanes/numpoints
553 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)
554 {
555         int nplane, nplane2, fstartsolid, fendsolid, brushsolid;
556         float enterfrac, leavefrac, d1, d2, f, newimpactnormal[3];
557         const colplanef_t *startplane, *endplane;
558
559         enterfrac = -1;
560         leavefrac = 1;
561         fstartsolid = true;
562         fendsolid = true;
563
564         for (nplane = 0;nplane < thatbrush_start->numplanes + thisbrush_start->numplanes;nplane++)
565         {
566                 nplane2 = nplane;
567                 if (nplane2 >= thatbrush_start->numplanes)
568                 {
569                         nplane2 -= thatbrush_start->numplanes;
570                         startplane = thisbrush_start->planes + nplane2;
571                         endplane = thisbrush_end->planes + nplane2;
572                 }
573                 else
574                 {
575                         startplane = thatbrush_start->planes + nplane2;
576                         endplane = thatbrush_end->planes + nplane2;
577                 }
578                 d1 = nearestplanedist_float(startplane->normal, thisbrush_start->points, thisbrush_start->numpoints) - furthestplanedist_float(startplane->normal, thatbrush_start->points, thatbrush_start->numpoints);
579                 d2 = nearestplanedist_float(endplane->normal, thisbrush_end->points, thisbrush_end->numpoints) - furthestplanedist_float(endplane->normal, thatbrush_end->points, thatbrush_end->numpoints) - COLLISIONEPSILON2;
580                 //Con_Printf("%c%i: d1 = %f, d2 = %f, d1 / (d1 - d2) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, d1, d2, d1 / (d1 - d2));
581
582                 f = d1 - d2;
583                 if (f >= 0)
584                 {
585                         // moving into brush
586                         if (d2 > 0)
587                                 return;
588                         if (d1 < 0)
589                                 continue;
590                         // enter
591                         fstartsolid = false;
592                         f = (d1 - COLLISIONEPSILON) / f;
593                         f = bound(0, f, 1);
594                         if (enterfrac < f)
595                         {
596                                 enterfrac = f;
597                                 VectorBlend(startplane->normal, endplane->normal, enterfrac, newimpactnormal);
598                         }
599                 }
600                 else if (f < 0)
601                 {
602                         // moving out of brush
603                         if (d1 > 0)
604                                 return;
605                         if (d2 < 0)
606                                 continue;
607                         // leave
608                         fendsolid = false;
609                         f = (d1 + COLLISIONEPSILON) / f;
610                         f = bound(0, f, 1);
611                         if (leavefrac > f)
612                                 leavefrac = f;
613                 }
614         }
615
616         brushsolid = trace->hitsupercontentsmask & thatbrush_start->supercontents;
617         if (fstartsolid)
618         {
619                 trace->startsupercontents |= thatbrush_start->supercontents;
620                 if (brushsolid)
621                 {
622                         trace->startsolid = true;
623                         if (fendsolid)
624                                 trace->allsolid = true;
625                 }
626         }
627
628         // LordHavoc: we need an epsilon nudge here because for a point trace the
629         // penetrating line segment is normally zero length if this brush was
630         // generated from a polygon (infinitely thin), and could even be slightly
631         // positive or negative due to rounding errors in that case.
632         if (brushsolid && enterfrac > -1 && enterfrac < trace->fraction && enterfrac - (1.0f / 1024.0f) <= leavefrac)
633         {
634                 trace->fraction = bound(0, enterfrac, 1);
635                 VectorCopy(newimpactnormal, trace->plane.normal);
636         }
637 }
638
639 // NOTE: start and end of brush pair must have same numplanes/numpoints
640 void Collision_TraceLineBrushFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const colbrushf_t *thatbrush_start, const colbrushf_t *thatbrush_end)
641 {
642         int nplane, fstartsolid, fendsolid, brushsolid;
643         float enterfrac, leavefrac, d1, d2, f, newimpactnormal[3];
644         const colplanef_t *startplane, *endplane;
645
646         enterfrac = -1;
647         leavefrac = 1;
648         fstartsolid = true;
649         fendsolid = true;
650
651         for (nplane = 0;nplane < thatbrush_start->numplanes;nplane++)
652         {
653                 startplane = thatbrush_start->planes + nplane;
654                 endplane = thatbrush_end->planes + nplane;
655                 d1 = DotProduct(startplane->normal, linestart) - startplane->dist;
656                 d2 = DotProduct(endplane->normal, lineend) - endplane->dist;
657
658                 f = d1 - d2;
659                 if (f >= 0)
660                 {
661                         // moving into brush
662                         if (d2 > 0)
663                                 return;
664                         if (d1 < 0)
665                                 continue;
666                         // enter
667                         fstartsolid = false;
668                         f = (d1 - COLLISIONEPSILON) / f;
669                         f = bound(0, f, 1);
670                         if (enterfrac < f)
671                         {
672                                 enterfrac = f;
673                                 VectorBlend(startplane->normal, endplane->normal, enterfrac, newimpactnormal);
674                         }
675                 }
676                 else if (f < 0)
677                 {
678                         // moving out of brush
679                         if (d1 > 0)
680                                 return;
681                         if (d2 < 0)
682                                 continue;
683                         // leave
684                         fendsolid = false;
685                         f = (d1 + COLLISIONEPSILON) / f;
686                         f = bound(0, f, 1);
687                         if (leavefrac > f)
688                                 leavefrac = f;
689                 }
690         }
691
692         brushsolid = trace->hitsupercontentsmask & thatbrush_start->supercontents;
693         if (fstartsolid)
694         {
695                 trace->startsupercontents |= thatbrush_start->supercontents;
696                 if (brushsolid)
697                 {
698                         trace->startsolid = true;
699                         if (fendsolid)
700                                 trace->allsolid = true;
701                 }
702         }
703
704         // LordHavoc: we need an epsilon nudge here because for a point trace the
705         // penetrating line segment is normally zero length if this brush was
706         // generated from a polygon (infinitely thin), and could even be slightly
707         // positive or negative due to rounding errors in that case.
708         if (brushsolid && enterfrac > -1 && enterfrac < trace->fraction && enterfrac - (1.0f / 1024.0f) <= leavefrac)
709         {
710                 trace->fraction = bound(0, enterfrac, 1);
711                 VectorCopy(newimpactnormal, trace->plane.normal);
712         }
713 }
714
715 static colplanef_t polyf_planes[256 + 2];
716 static colbrushf_t polyf_brush;
717
718 void Collision_TraceBrushPolygonFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int numpoints, const float *points)
719 {
720         if (numpoints > 256)
721         {
722                 Con_Printf("Polygon with more than 256 points not supported yet (fixme!)\n");
723                 return;
724         }
725         polyf_brush.numpoints = numpoints;
726         polyf_brush.numplanes = numpoints + 2;
727         polyf_brush.points = (colpointf_t *)points;
728         polyf_brush.planes = polyf_planes;
729         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
730         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
731         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &polyf_brush, &polyf_brush);
732 }
733
734 static colpointf_t polyf_pointsstart[256], polyf_pointsend[256];
735 static colplanef_t polyf_planesstart[256 + 2], polyf_planesend[256 + 2];
736 static colbrushf_t polyf_brushstart, polyf_brushend;
737
738 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)
739 {
740         int i;
741         if (numpoints > 256)
742         {
743                 Con_Printf("Polygon with more than 256 points not supported yet (fixme!)\n");
744                 return;
745         }
746         polyf_brushstart.numpoints = numpoints;
747         polyf_brushstart.numplanes = numpoints + 2;
748         polyf_brushstart.points = polyf_pointsstart;//(colpointf_t *)points;
749         polyf_brushstart.planes = polyf_planesstart;
750         for (i = 0;i < numpoints;i++)
751                 Matrix4x4_Transform(polygonmatrixstart, points + i * 3, polyf_brushstart.points[i].v);
752         polyf_brushend.numpoints = numpoints;
753         polyf_brushend.numplanes = numpoints + 2;
754         polyf_brushend.points = polyf_pointsend;//(colpointf_t *)points;
755         polyf_brushend.planes = polyf_planesend;
756         for (i = 0;i < numpoints;i++)
757                 Matrix4x4_Transform(polygonmatrixend, points + i * 3, polyf_brushend.points[i].v);
758         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brushstart);
759         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brushend);
760
761         //Collision_PrintBrushAsQHull(&polyf_brushstart, "polyf_brushstart");
762         //Collision_PrintBrushAsQHull(&polyf_brushend, "polyf_brushend");
763
764         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &polyf_brushstart, &polyf_brushend);
765 }
766
767
768
769 #define MAX_BRUSHFORBOX 16
770 static int brushforbox_index = 0;
771 static colpointf_t brushforbox_point[MAX_BRUSHFORBOX*8];
772 static colplanef_t brushforbox_plane[MAX_BRUSHFORBOX*6];
773 static colbrushf_t brushforbox_brush[MAX_BRUSHFORBOX];
774
775 void Collision_InitBrushForBox(void)
776 {
777         int i;
778         for (i = 0;i < MAX_BRUSHFORBOX;i++)
779         {
780                 brushforbox_brush[i].supercontents = SUPERCONTENTS_SOLID;
781                 brushforbox_brush[i].numpoints = 8;
782                 brushforbox_brush[i].numplanes = 6;
783                 brushforbox_brush[i].points = brushforbox_point + i * 8;
784                 brushforbox_brush[i].planes = brushforbox_plane + i * 6;
785         }
786 }
787
788 colbrushf_t *Collision_BrushForBox(const matrix4x4_t *matrix, const vec3_t mins, const vec3_t maxs)
789 {
790         int i;
791         vec3_t v;
792         colbrushf_t *brush;
793         if (brushforbox_brush[0].numpoints == 0)
794                 Collision_InitBrushForBox();
795         brush = brushforbox_brush + ((brushforbox_index++) % MAX_BRUSHFORBOX);
796         // FIXME: optimize
797         for (i = 0;i < 8;i++)
798         {
799                 v[0] = i & 1 ? maxs[0] : mins[0];
800                 v[1] = i & 2 ? maxs[1] : mins[1];
801                 v[2] = i & 4 ? maxs[2] : mins[2];
802                 Matrix4x4_Transform(matrix, v, brush->points[i].v);
803         }
804         // FIXME: optimize!
805         for (i = 0;i < 6;i++)
806         {
807                 VectorClear(v);
808                 v[i >> 1] = i & 1 ? 1 : -1;
809                 Matrix4x4_Transform3x3(matrix, v, brush->planes[i].normal);
810                 VectorNormalize(brush->planes[i].normal);
811                 brush->planes[i].dist = furthestplanedist_float(brush->planes[i].normal, brush->points, brush->numpoints);
812         }
813         Collision_ValidateBrush(brush);
814         return brush;
815 }
816
817 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)
818 {
819         colbrushf_t *boxbrush, *thisbrush_start, *thisbrush_end;
820         matrix4x4_t identitymatrix;
821         vec3_t startmins, startmaxs, endmins, endmaxs;
822
823         // create brushes for the collision
824         VectorAdd(start, mins, startmins);
825         VectorAdd(start, maxs, startmaxs);
826         VectorAdd(end, mins, endmins);
827         VectorAdd(end, maxs, endmaxs);
828         Matrix4x4_CreateIdentity(&identitymatrix);
829         boxbrush = Collision_BrushForBox(&identitymatrix, cmins, cmaxs);
830         thisbrush_start = Collision_BrushForBox(&identitymatrix, startmins, startmaxs);
831         thisbrush_end = Collision_BrushForBox(&identitymatrix, endmins, endmaxs);
832
833         memset(trace, 0, sizeof(trace_t));
834         trace->hitsupercontentsmask = hitsupercontentsmask;
835         trace->fraction = 1;
836         trace->allsolid = true;
837         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, boxbrush, boxbrush);
838 }
839
840 // LordHavoc: currently unused and not yet tested
841 // note: this can be used for tracing a moving sphere vs a stationary sphere,
842 // by simply adding the moving sphere's radius to the sphereradius parameter,
843 // all the results are correct (impactpoint, impactnormal, and fraction)
844 float Collision_ClipTrace_Line_Sphere(double *linestart, double *lineend, double *sphereorigin, double sphereradius, double *impactpoint, double *impactnormal)
845 {
846         double dir[3], scale, v[3], deviationdist, impactdist, linelength;
847         // make sure the impactpoint and impactnormal are valid even if there is
848         // no collision
849         impactpoint[0] = lineend[0];
850         impactpoint[1] = lineend[1];
851         impactpoint[2] = lineend[2];
852         impactnormal[0] = 0;
853         impactnormal[1] = 0;
854         impactnormal[2] = 0;
855         // calculate line direction
856         dir[0] = lineend[0] - linestart[0];
857         dir[1] = lineend[1] - linestart[1];
858         dir[2] = lineend[2] - linestart[2];
859         // normalize direction
860         linelength = sqrt(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]);
861         if (linelength)
862         {
863                 scale = 1.0 / linelength;
864                 dir[0] *= scale;
865                 dir[1] *= scale;
866                 dir[2] *= scale;
867         }
868         // this dotproduct calculates the distance along the line at which the
869         // sphere origin is (nearest point to the sphere origin on the line)
870         impactdist = dir[0] * (sphereorigin[0] - linestart[0]) + dir[1] * (sphereorigin[1] - linestart[1]) + dir[2] * (sphereorigin[2] - linestart[2]);
871         // calculate point on line at that distance, and subtract the
872         // sphereorigin from it, so we have a vector to measure for the distance
873         // of the line from the sphereorigin (deviation, how off-center it is)
874         v[0] = linestart[0] + impactdist * dir[0] - sphereorigin[0];
875         v[1] = linestart[1] + impactdist * dir[1] - sphereorigin[1];
876         v[2] = linestart[2] + impactdist * dir[2] - sphereorigin[2];
877         deviationdist = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
878         // if outside the radius, it's a miss for sure
879         // (we do this comparison using squared radius to avoid a sqrt)
880         if (deviationdist > sphereradius*sphereradius)
881                 return 1; // miss (off to the side)
882         // nudge back to find the correct impact distance
883         impactdist += (sqrt(deviationdist) - sphereradius);
884         if (impactdist >= linelength)
885                 return 1; // miss (not close enough)
886         if (impactdist < 0)
887                 return 1; // miss (linestart is past or inside sphere)
888         // calculate new impactpoint
889         impactpoint[0] = linestart[0] + impactdist * dir[0];
890         impactpoint[1] = linestart[1] + impactdist * dir[1];
891         impactpoint[2] = linestart[2] + impactdist * dir[2];
892         // calculate impactnormal (surface normal at point of impact)
893         impactnormal[0] = impactpoint[0] - sphereorigin[0];
894         impactnormal[1] = impactpoint[1] - sphereorigin[1];
895         impactnormal[2] = impactpoint[2] - sphereorigin[2];
896         // normalize impactnormal
897         scale = impactnormal[0] * impactnormal[0] + impactnormal[1] * impactnormal[1] + impactnormal[2] * impactnormal[2];
898         if (scale)
899         {
900                 scale = 1.0 / sqrt(scale);
901                 impactnormal[0] *= scale;
902                 impactnormal[1] *= scale;
903                 impactnormal[2] *= scale;
904         }
905         // return fraction of movement distance
906         return impactdist / linelength;
907 }
908