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