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