]> git.xonotic.org Git - xonotic/darkplaces.git/blob - collision.c
56666afdf5532da0131f46c899a4cf3bcbfc2c01
[xonotic/darkplaces.git] / collision.c
1
2 #include "quakedef.h"
3 #include "polygon.h"
4
5 #define COLLISION_EDGEDIR_DOT_EPSILON (0.999f)
6 #define COLLISION_EDGECROSS_MINLENGTH2 (1.0f / 4194304.0f)
7 #define COLLISION_SNAPSCALE (32.0f)
8 #define COLLISION_SNAP (1.0f / COLLISION_SNAPSCALE)
9 #define COLLISION_SNAP2 (2.0f / COLLISION_SNAPSCALE)
10 #define COLLISION_PLANE_DIST_EPSILON (2.0f / COLLISION_SNAPSCALE)
11
12 cvar_t collision_impactnudge = {0, "collision_impactnudge", "0.03125", "how much to back off from the impact"};
13 cvar_t collision_startnudge = {0, "collision_startnudge", "0", "how much to bias collision trace start"};
14 cvar_t collision_endnudge = {0, "collision_endnudge", "0", "how much to bias collision trace end"};
15 cvar_t collision_enternudge = {0, "collision_enternudge", "0", "how much to bias collision entry fraction"};
16 cvar_t collision_leavenudge = {0, "collision_leavenudge", "0", "how much to bias collision exit fraction"};
17 cvar_t collision_prefernudgedfraction = {0, "collision_prefernudgedfraction", "1", "whether to sort collision events by nudged fraction (1) or real fraction (0)"};
18 #ifdef COLLISION_STUPID_TRACE_ENDPOS_IN_SOLID_WORKAROUND
19 cvar_t collision_endposnudge = {0, "collision_endposnudge", "0", "workaround to fix trace_endpos sometimes being returned where it would be inside solid by making that collision hit (recommended: values like 1)"};
20 #endif
21 cvar_t collision_debug_tracelineasbox = {0, "collision_debug_tracelineasbox", "0", "workaround for any bugs in Collision_TraceLineBrushFloat by using Collision_TraceBrushBrushFloat"};
22
23 void Collision_Init (void)
24 {
25         Cvar_RegisterVariable(&collision_impactnudge);
26         Cvar_RegisterVariable(&collision_startnudge);
27         Cvar_RegisterVariable(&collision_endnudge);
28         Cvar_RegisterVariable(&collision_enternudge);
29         Cvar_RegisterVariable(&collision_leavenudge);
30         Cvar_RegisterVariable(&collision_prefernudgedfraction);
31 #ifdef COLLISION_STUPID_TRACE_ENDPOS_IN_SOLID_WORKAROUND
32         Cvar_RegisterVariable(&collision_endposnudge);
33 #endif
34         Cvar_RegisterVariable(&collision_debug_tracelineasbox);
35 }
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 void Collision_PrintBrushAsQHull(colbrushf_t *brush, const char *name)
51 {
52         int i;
53         Con_Printf("3 %s\n%i\n", name, brush->numpoints);
54         for (i = 0;i < brush->numpoints;i++)
55                 Con_Printf("%f %f %f\n", brush->points[i].v[0], brush->points[i].v[1], brush->points[i].v[2]);
56         // FIXME: optimize!
57         Con_Printf("4\n%i\n", brush->numplanes);
58         for (i = 0;i < brush->numplanes;i++)
59                 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);
60 }
61
62 void Collision_ValidateBrush(colbrushf_t *brush)
63 {
64         int j, k, pointsoffplanes, pointonplanes, pointswithinsufficientplanes, printbrush;
65         float d;
66         printbrush = false;
67         if (!brush->numpoints)
68         {
69                 Con_Print("Collision_ValidateBrush: brush with no points!\n");
70                 printbrush = true;
71         }
72 #if 0
73         // it's ok for a brush to have one point and no planes...
74         if (brush->numplanes == 0 && brush->numpoints != 1)
75         {
76                 Con_Print("Collision_ValidateBrush: brush with no planes and more than one point!\n");
77                 printbrush = true;
78         }
79 #endif
80         if (brush->numplanes)
81         {
82                 pointsoffplanes = 0;
83                 pointswithinsufficientplanes = 0;
84                 for (k = 0;k < brush->numplanes;k++)
85                         if (DotProduct(brush->planes[k].normal, brush->planes[k].normal) < 0.0001f)
86                                 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);
87                 for (j = 0;j < brush->numpoints;j++)
88                 {
89                         pointonplanes = 0;
90                         for (k = 0;k < brush->numplanes;k++)
91                         {
92                                 d = DotProduct(brush->points[j].v, brush->planes[k].normal) - brush->planes[k].dist;
93                                 if (d > COLLISION_PLANE_DIST_EPSILON)
94                                 {
95                                         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);
96                                         printbrush = true;
97                                 }
98                                 if (fabs(d) > COLLISION_PLANE_DIST_EPSILON)
99                                         pointsoffplanes++;
100                                 else
101                                         pointonplanes++;
102                         }
103                         if (pointonplanes < 3)
104                                 pointswithinsufficientplanes++;
105                 }
106                 if (pointswithinsufficientplanes)
107                 {
108                         Con_Print("Collision_ValidateBrush: some points have insufficient planes, every point must be on at least 3 planes to form a corner.\n");
109                         printbrush = true;
110                 }
111                 if (pointsoffplanes == 0) // all points are on all planes
112                 {
113                         Con_Print("Collision_ValidateBrush: all points lie on all planes (degenerate, no brush volume!)\n");
114                         printbrush = true;
115                 }
116         }
117         if (printbrush)
118                 Collision_PrintBrushAsQHull(brush, "unnamed");
119 }
120
121 float nearestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
122 {
123         float dist, bestdist;
124         if (!numpoints)
125                 return 0;
126         bestdist = DotProduct(points->v, normal);
127         points++;
128         while(--numpoints)
129         {
130                 dist = DotProduct(points->v, normal);
131                 bestdist = min(bestdist, dist);
132                 points++;
133         }
134         return bestdist;
135 }
136
137 float furthestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
138 {
139         float dist, bestdist;
140         if (!numpoints)
141                 return 0;
142         bestdist = DotProduct(points->v, normal);
143         points++;
144         while(--numpoints)
145         {
146                 dist = DotProduct(points->v, normal);
147                 bestdist = max(bestdist, dist);
148                 points++;
149         }
150         return bestdist;
151 }
152
153 void Collision_CalcEdgeDirsForPolygonBrushFloat(colbrushf_t *brush)
154 {
155         int i, j;
156         for (i = 0, j = brush->numpoints - 1;i < brush->numpoints;j = i, i++)
157                 VectorSubtract(brush->points[i].v, brush->points[j].v, brush->edgedirs[j].v);
158 }
159
160 colbrushf_t *Collision_NewBrushFromPlanes(mempool_t *mempool, int numoriginalplanes, const colplanef_t *originalplanes, int supercontents, int q3surfaceflags, const texture_t *texture, int hasaabbplanes)
161 {
162         // TODO: planesbuf could be replaced by a remapping table
163         int j, k, l, m, w, xyzflags;
164         int numpointsbuf = 0, maxpointsbuf = 256, numedgedirsbuf = 0, maxedgedirsbuf = 256, numplanesbuf = 0, maxplanesbuf = 256, numelementsbuf = 0, maxelementsbuf = 256;
165         int isaabb = true;
166         double maxdist;
167         colbrushf_t *brush;
168         colpointf_t pointsbuf[256];
169         colpointf_t edgedirsbuf[256];
170         colplanef_t planesbuf[256];
171         int elementsbuf[1024];
172         int polypointbuf[256];
173         int pmaxpoints = 64;
174         int pnumpoints;
175         double p[2][3*64];
176 #if 0
177         // enable these if debugging to avoid seeing garbage in unused data-
178         memset(pointsbuf, 0, sizeof(pointsbuf));
179         memset(edgedirsbuf, 0, sizeof(edgedirsbuf));
180         memset(planesbuf, 0, sizeof(planesbuf));
181         memset(elementsbuf, 0, sizeof(elementsbuf));
182         memset(polypointbuf, 0, sizeof(polypointbuf));
183         memset(p, 0, sizeof(p));
184 #endif
185
186         // check if there are too many planes and skip the brush
187         if (numoriginalplanes >= maxplanesbuf)
188         {
189                 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many planes for buffer\n");
190                 return NULL;
191         }
192
193         // figure out how large a bounding box we need to properly compute this brush
194         maxdist = 0;
195         for (j = 0;j < numoriginalplanes;j++)
196                 maxdist = max(maxdist, fabs(originalplanes[j].dist));
197         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
198         maxdist = floor(maxdist * (4.0 / 1024.0) + 2) * 1024.0;
199         // construct a collision brush (points, planes, and renderable mesh) from
200         // a set of planes, this also optimizes out any unnecessary planes (ones
201         // whose polygon is clipped away by the other planes)
202         for (j = 0;j < numoriginalplanes;j++)
203         {
204                 // add the new plane
205                 VectorCopy(originalplanes[j].normal, planesbuf[numplanesbuf].normal);
206                 planesbuf[numplanesbuf].dist = originalplanes[j].dist;
207                 planesbuf[numplanesbuf].q3surfaceflags = originalplanes[j].q3surfaceflags;
208                 planesbuf[numplanesbuf].texture = originalplanes[j].texture;
209                 numplanesbuf++;
210
211                 // create a large polygon from the plane
212                 w = 0;
213                 PolygonD_QuadForPlane(p[w], originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist, maxdist);
214                 pnumpoints = 4;
215                 // clip it by all other planes
216                 for (k = 0;k < numoriginalplanes && pnumpoints >= 3 && pnumpoints <= pmaxpoints;k++)
217                 {
218                         // skip the plane this polygon
219                         // (nothing happens if it is processed, this is just an optimization)
220                         if (k != j)
221                         {
222                                 // we want to keep the inside of the brush plane so we flip
223                                 // the cutting plane
224                                 PolygonD_Divide(pnumpoints, p[w], -originalplanes[k].normal[0], -originalplanes[k].normal[1], -originalplanes[k].normal[2], -originalplanes[k].dist, COLLISION_PLANE_DIST_EPSILON, pmaxpoints, p[!w], &pnumpoints, 0, NULL, NULL, NULL);
225                                 w = !w;
226                         }
227                 }
228
229                 // if nothing is left, skip it
230                 if (pnumpoints < 3)
231                 {
232                         //Con_DPrintf("Collision_NewBrushFromPlanes: warning: polygon for plane %f %f %f %f clipped away\n", originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist);
233                         continue;
234                 }
235
236                 for (k = 0;k < pnumpoints;k++)
237                 {
238                         int l, m;
239                         m = 0;
240                         for (l = 0;l < numoriginalplanes;l++)
241                                 if (fabs(DotProduct(&p[w][k*3], originalplanes[l].normal) - originalplanes[l].dist) < COLLISION_PLANE_DIST_EPSILON)
242                                         m++;
243                         if (m < 3)
244                                 break;
245                 }
246                 if (k < pnumpoints)
247                 {
248                         Con_DPrintf("Collision_NewBrushFromPlanes: warning: polygon point does not lie on at least 3 planes\n");
249                         //return NULL;
250                 }
251
252                 // check if there are too many polygon vertices for buffer
253                 if (pnumpoints > pmaxpoints)
254                 {
255                         Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
256                         return NULL;
257                 }
258
259                 // check if there are too many triangle elements for buffer
260                 if (numelementsbuf + (pnumpoints - 2) * 3 > maxelementsbuf)
261                 {
262                         Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many triangle elements for buffer\n");
263                         return NULL;
264                 }
265
266                 // add the unique points for this polygon
267                 for (k = 0;k < pnumpoints;k++)
268                 {
269                         float v[3];
270                         // downgrade to float precision before comparing
271                         VectorCopy(&p[w][k*3], v);
272
273                         // check if there is already a matching point (no duplicates)
274                         for (m = 0;m < numpointsbuf;m++)
275                                 if (VectorDistance2(v, pointsbuf[m].v) < COLLISION_SNAP2)
276                                         break;
277
278                         // if there is no match, add a new one
279                         if (m == numpointsbuf)
280                         {
281                                 // check if there are too many and skip the brush
282                                 if (numpointsbuf >= maxpointsbuf)
283                                 {
284                                         Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
285                                         return NULL;
286                                 }
287                                 // add the new one
288                                 VectorCopy(&p[w][k*3], pointsbuf[numpointsbuf].v);
289                                 numpointsbuf++;
290                         }
291
292                         // store the index into a buffer
293                         polypointbuf[k] = m;
294                 }
295
296                 // add the triangles for the polygon
297                 // (this particular code makes a triangle fan)
298                 for (k = 0;k < pnumpoints - 2;k++)
299                 {
300                         elementsbuf[numelementsbuf++] = polypointbuf[0];
301                         elementsbuf[numelementsbuf++] = polypointbuf[k + 1];
302                         elementsbuf[numelementsbuf++] = polypointbuf[k + 2];
303                 }
304
305                 // add the unique edgedirs for this polygon
306                 for (k = 0, l = pnumpoints-1;k < pnumpoints;l = k, k++)
307                 {
308                         float dir[3];
309                         // downgrade to float precision before comparing
310                         VectorSubtract(&p[w][k*3], &p[w][l*3], dir);
311                         VectorNormalize(dir);
312
313                         // check if there is already a matching edgedir (no duplicates)
314                         for (m = 0;m < numedgedirsbuf;m++)
315                                 if (DotProduct(dir, edgedirsbuf[m].v) >= COLLISION_EDGEDIR_DOT_EPSILON)
316                                         break;
317                         // skip this if there is
318                         if (m < numedgedirsbuf)
319                                 continue;
320
321                         // try again with negated edgedir
322                         VectorNegate(dir, dir);
323                         // check if there is already a matching edgedir (no duplicates)
324                         for (m = 0;m < numedgedirsbuf;m++)
325                                 if (DotProduct(dir, edgedirsbuf[m].v) >= COLLISION_EDGEDIR_DOT_EPSILON)
326                                         break;
327                         // if there is no match, add a new one
328                         if (m == numedgedirsbuf)
329                         {
330                                 // check if there are too many and skip the brush
331                                 if (numedgedirsbuf >= maxedgedirsbuf)
332                                 {
333                                         Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many edgedirs for buffer\n");
334                                         return NULL;
335                                 }
336                                 // add the new one
337                                 VectorCopy(dir, edgedirsbuf[numedgedirsbuf].v);
338                                 numedgedirsbuf++;
339                         }
340                 }
341
342                 // if any normal is not purely axial, it's not an axis-aligned box
343                 if (isaabb && (originalplanes[j].normal[0] == 0) + (originalplanes[j].normal[1] == 0) + (originalplanes[j].normal[2] == 0) < 2)
344                         isaabb = false;
345         }
346
347         // if nothing is left, there's nothing to allocate
348         if (numplanesbuf < 4)
349         {
350                 Con_DPrintf("Collision_NewBrushFromPlanes: failed to build collision brush: %i triangles, %i planes (input was %i planes), %i vertices\n", numelementsbuf / 3, numplanesbuf, numoriginalplanes, numpointsbuf);
351                 return NULL;
352         }
353
354         // if no triangles or points could be constructed, then this routine failed but the brush is not discarded
355         if (numelementsbuf < 12 || numpointsbuf < 4)
356                 Con_DPrintf("Collision_NewBrushFromPlanes: unable to rebuild triangles/points for collision brush: %i triangles, %i planes (input was %i planes), %i vertices\n", numelementsbuf / 3, numplanesbuf, numoriginalplanes, numpointsbuf);
357
358         // validate plane distances
359         for (j = 0;j < numplanesbuf;j++)
360         {
361                 float d = furthestplanedist_float(planesbuf[j].normal, pointsbuf, numpointsbuf);
362                 if (fabs(planesbuf[j].dist - d) > COLLISION_PLANE_DIST_EPSILON)
363                         Con_DPrintf("plane %f %f %f %f mismatches dist %f\n", planesbuf[j].normal[0], planesbuf[j].normal[1], planesbuf[j].normal[2], planesbuf[j].dist, d);
364         }
365
366         // allocate the brush and copy to it
367         brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colpointf_t) * numpointsbuf + sizeof(colpointf_t) * numedgedirsbuf + sizeof(colplanef_t) * numplanesbuf + sizeof(int) * numelementsbuf);
368         brush->isaabb = isaabb;
369         brush->hasaabbplanes = hasaabbplanes;
370         brush->supercontents = supercontents;
371         brush->numplanes = numplanesbuf;
372         brush->numedgedirs = numedgedirsbuf;
373         brush->numpoints = numpointsbuf;
374         brush->numtriangles = numelementsbuf / 3;
375         brush->planes = (colplanef_t *)(brush + 1);
376         brush->points = (colpointf_t *)(brush->planes + brush->numplanes);
377         brush->edgedirs = (colpointf_t *)(brush->points + brush->numpoints);
378         brush->elements = (int *)(brush->points + brush->numpoints);
379         brush->q3surfaceflags = q3surfaceflags;
380         brush->texture = texture;
381         for (j = 0;j < brush->numpoints;j++)
382         {
383                 brush->points[j].v[0] = pointsbuf[j].v[0];
384                 brush->points[j].v[1] = pointsbuf[j].v[1];
385                 brush->points[j].v[2] = pointsbuf[j].v[2];
386         }
387         for (j = 0;j < brush->numedgedirs;j++)
388         {
389                 brush->edgedirs[j].v[0] = edgedirsbuf[j].v[0];
390                 brush->edgedirs[j].v[1] = edgedirsbuf[j].v[1];
391                 brush->edgedirs[j].v[2] = edgedirsbuf[j].v[2];
392         }
393         for (j = 0;j < brush->numplanes;j++)
394         {
395                 brush->planes[j].normal[0] = planesbuf[j].normal[0];
396                 brush->planes[j].normal[1] = planesbuf[j].normal[1];
397                 brush->planes[j].normal[2] = planesbuf[j].normal[2];
398                 brush->planes[j].dist = planesbuf[j].dist;
399                 brush->planes[j].q3surfaceflags = planesbuf[j].q3surfaceflags;
400                 brush->planes[j].texture = planesbuf[j].texture;
401         }
402         for (j = 0;j < brush->numtriangles * 3;j++)
403                 brush->elements[j] = elementsbuf[j];
404
405         xyzflags = 0;
406         VectorClear(brush->mins);
407         VectorClear(brush->maxs);
408         for (j = 0;j < min(6, numoriginalplanes);j++)
409         {
410                      if (originalplanes[j].normal[0] ==  1) {xyzflags |=  1;brush->maxs[0] =  originalplanes[j].dist;}
411                 else if (originalplanes[j].normal[0] == -1) {xyzflags |=  2;brush->mins[0] = -originalplanes[j].dist;}
412                 else if (originalplanes[j].normal[1] ==  1) {xyzflags |=  4;brush->maxs[1] =  originalplanes[j].dist;}
413                 else if (originalplanes[j].normal[1] == -1) {xyzflags |=  8;brush->mins[1] = -originalplanes[j].dist;}
414                 else if (originalplanes[j].normal[2] ==  1) {xyzflags |= 16;brush->maxs[2] =  originalplanes[j].dist;}
415                 else if (originalplanes[j].normal[2] == -1) {xyzflags |= 32;brush->mins[2] = -originalplanes[j].dist;}
416         }
417         // if not all xyzflags were set, then this is not a brush from q3map/q3map2, and needs reconstruction of the bounding box
418         // (this case works for any brush with valid points, but sometimes brushes are not reconstructed properly and hence the points are not valid, so this is reserved as a fallback case)
419         if (xyzflags != 63)
420         {
421                 VectorCopy(brush->points[0].v, brush->mins);
422                 VectorCopy(brush->points[0].v, brush->maxs);
423                 for (j = 1;j < brush->numpoints;j++)
424                 {
425                         brush->mins[0] = min(brush->mins[0], brush->points[j].v[0]);
426                         brush->mins[1] = min(brush->mins[1], brush->points[j].v[1]);
427                         brush->mins[2] = min(brush->mins[2], brush->points[j].v[2]);
428                         brush->maxs[0] = max(brush->maxs[0], brush->points[j].v[0]);
429                         brush->maxs[1] = max(brush->maxs[1], brush->points[j].v[1]);
430                         brush->maxs[2] = max(brush->maxs[2], brush->points[j].v[2]);
431                 }
432         }
433         brush->mins[0] -= 1;
434         brush->mins[1] -= 1;
435         brush->mins[2] -= 1;
436         brush->maxs[0] += 1;
437         brush->maxs[1] += 1;
438         brush->maxs[2] += 1;
439         Collision_ValidateBrush(brush);
440         return brush;
441 }
442
443
444
445 void Collision_CalcPlanesForPolygonBrushFloat(colbrushf_t *brush)
446 {
447         int i;
448         float edge0[3], edge1[3], edge2[3], normal[3], dist, bestdist;
449         colpointf_t *p, *p2;
450
451         // FIXME: these probably don't actually need to be normalized if the collision code does not care
452         if (brush->numpoints == 3)
453         {
454                 // optimized triangle case
455                 TriangleNormal(brush->points[0].v, brush->points[1].v, brush->points[2].v, brush->planes[0].normal);
456                 if (DotProduct(brush->planes[0].normal, brush->planes[0].normal) < 0.0001f)
457                 {
458                         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
459                         brush->numplanes = 0;
460                         return;
461                 }
462                 else
463                 {
464                         brush->numplanes = 5;
465                         brush->numedgedirs = 3;
466                         VectorNormalize(brush->planes[0].normal);
467                         brush->planes[0].dist = DotProduct(brush->points->v, brush->planes[0].normal);
468                         VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
469                         brush->planes[1].dist = -brush->planes[0].dist;
470                         VectorSubtract(brush->points[2].v, brush->points[0].v, edge0);
471                         VectorSubtract(brush->points[0].v, brush->points[1].v, edge1);
472                         VectorSubtract(brush->points[1].v, brush->points[2].v, edge2);
473                         VectorCopy(edge0, brush->edgedirs[0].v);
474                         VectorCopy(edge1, brush->edgedirs[1].v);
475                         VectorCopy(edge2, brush->edgedirs[2].v);
476 #if 1
477                         {
478                                 float projectionnormal[3], projectionedge0[3], projectionedge1[3], projectionedge2[3];
479                                 int i, best;
480                                 float dist, bestdist;
481                                 bestdist = fabs(brush->planes[0].normal[0]);
482                                 best = 0;
483                                 for (i = 1;i < 3;i++)
484                                 {
485                                         dist = fabs(brush->planes[0].normal[i]);
486                                         if (bestdist < dist)
487                                         {
488                                                 bestdist = dist;
489                                                 best = i;
490                                         }
491                                 }
492                                 VectorClear(projectionnormal);
493                                 if (brush->planes[0].normal[best] < 0)
494                                         projectionnormal[best] = -1;
495                                 else
496                                         projectionnormal[best] = 1;
497                                 VectorCopy(edge0, projectionedge0);
498                                 VectorCopy(edge1, projectionedge1);
499                                 VectorCopy(edge2, projectionedge2);
500                                 projectionedge0[best] = 0;
501                                 projectionedge1[best] = 0;
502                                 projectionedge2[best] = 0;
503                                 CrossProduct(projectionedge0, projectionnormal, brush->planes[2].normal);
504                                 CrossProduct(projectionedge1, projectionnormal, brush->planes[3].normal);
505                                 CrossProduct(projectionedge2, projectionnormal, brush->planes[4].normal);
506                         }
507 #else
508                         CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
509                         CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
510                         CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
511 #endif
512                         VectorNormalize(brush->planes[2].normal);
513                         VectorNormalize(brush->planes[3].normal);
514                         VectorNormalize(brush->planes[4].normal);
515                         brush->planes[2].dist = DotProduct(brush->points[2].v, brush->planes[2].normal);
516                         brush->planes[3].dist = DotProduct(brush->points[0].v, brush->planes[3].normal);
517                         brush->planes[4].dist = DotProduct(brush->points[1].v, brush->planes[4].normal);
518
519                         if (developer_extra.integer)
520                         {
521                                 // validation code
522 #if 0
523                                 float temp[3];
524
525                                 VectorSubtract(brush->points[0].v, brush->points[1].v, edge0);
526                                 VectorSubtract(brush->points[2].v, brush->points[1].v, edge1);
527                                 CrossProduct(edge0, edge1, normal);
528                                 VectorNormalize(normal);
529                                 VectorSubtract(normal, brush->planes[0].normal, temp);
530                                 if (VectorLength(temp) > 0.01f)
531                                         Con_DPrintf("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]);
532                                 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)
533                                         Con_DPrintf("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);
534 #if 0
535                                 if (fabs(DotProduct(brush->planes[2].normal, brush->planes[0].normal)) > 0.01f)
536                                         Con_DPrintf("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);
537                                 if (fabs(DotProduct(brush->planes[3].normal, brush->planes[0].normal)) > 0.01f)
538                                         Con_DPrintf("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);
539                                 if (fabs(DotProduct(brush->planes[4].normal, brush->planes[0].normal)) > 0.01f)
540                                         Con_DPrintf("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);
541                                 if (fabs(DotProduct(brush->planes[2].normal, edge0)) > 0.01f)
542                                         Con_DPrintf("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]);
543                                 if (fabs(DotProduct(brush->planes[3].normal, edge1)) > 0.01f)
544                                         Con_DPrintf("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]);
545                                 if (fabs(DotProduct(brush->planes[4].normal, edge2)) > 0.01f)
546                                         Con_DPrintf("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]);
547 #endif
548 #endif
549                                 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)
550                                         Con_DPrintf("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);
551                                 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)
552                                         Con_DPrintf("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);
553                                 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)
554                                         Con_DPrintf("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);
555                                 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)
556                                         Con_DPrintf("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);
557                                 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)
558                                         Con_DPrintf("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);
559                         }
560                 }
561         }
562         else
563         {
564                 // choose best surface normal for polygon's plane
565                 bestdist = 0;
566                 for (i = 0, p = brush->points + 1;i < brush->numpoints - 2;i++, p++)
567                 {
568                         VectorSubtract(p[-1].v, p[0].v, edge0);
569                         VectorSubtract(p[1].v, p[0].v, edge1);
570                         CrossProduct(edge0, edge1, normal);
571                         //TriangleNormal(p[-1].v, p[0].v, p[1].v, normal);
572                         dist = DotProduct(normal, normal);
573                         if (i == 0 || bestdist < dist)
574                         {
575                                 bestdist = dist;
576                                 VectorCopy(normal, brush->planes->normal);
577                         }
578                 }
579                 if (bestdist < 0.0001f)
580                 {
581                         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
582                         brush->numplanes = 0;
583                         return;
584                 }
585                 else
586                 {
587                         brush->numplanes = brush->numpoints + 2;
588                         VectorNormalize(brush->planes->normal);
589                         brush->planes->dist = DotProduct(brush->points->v, brush->planes->normal);
590
591                         // negate plane to create other side
592                         VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
593                         brush->planes[1].dist = -brush->planes[0].dist;
594                         for (i = 0, p = brush->points + (brush->numpoints - 1), p2 = brush->points;i < brush->numpoints;i++, p = p2, p2++)
595                         {
596                                 VectorSubtract(p->v, p2->v, edge0);
597                                 CrossProduct(edge0, brush->planes->normal, brush->planes[i + 2].normal);
598                                 VectorNormalize(brush->planes[i + 2].normal);
599                                 brush->planes[i + 2].dist = DotProduct(p->v, brush->planes[i + 2].normal);
600                         }
601                 }
602         }
603
604         if (developer_extra.integer)
605         {
606                 // validity check - will be disabled later
607                 Collision_ValidateBrush(brush);
608                 for (i = 0;i < brush->numplanes;i++)
609                 {
610                         int j;
611                         for (j = 0, p = brush->points;j < brush->numpoints;j++, p++)
612                                 if (DotProduct(p->v, brush->planes[i].normal) > brush->planes[i].dist + COLLISION_PLANE_DIST_EPSILON)
613                                         Con_DPrintf("Error in brush plane generation, plane %i\n", i);
614                 }
615         }
616 }
617
618 colbrushf_t *Collision_AllocBrushFromPermanentPolygonFloat(mempool_t *mempool, int numpoints, float *points, int supercontents, int q3surfaceflags, const texture_t *texture)
619 {
620         colbrushf_t *brush;
621         brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colplanef_t) * (numpoints + 2) + sizeof(colpointf_t) * numpoints);
622         brush->isaabb = false;
623         brush->hasaabbplanes = false;
624         brush->supercontents = supercontents;
625         brush->numpoints = numpoints;
626         brush->numedgedirs = numpoints;
627         brush->numplanes = numpoints + 2;
628         brush->planes = (colplanef_t *)(brush + 1);
629         brush->points = (colpointf_t *)points;
630         brush->edgedirs = (colpointf_t *)(brush->planes + brush->numplanes);
631         brush->q3surfaceflags = q3surfaceflags;
632         brush->texture = texture;
633         Sys_Error("Collision_AllocBrushFromPermanentPolygonFloat: FIXME: this code needs to be updated to generate a mesh...");
634         return brush;
635 }
636
637 // NOTE: start and end of each brush pair must have same numplanes/numpoints
638 void Collision_TraceBrushBrushFloat(trace_t *trace, const colbrushf_t *trace_start, const colbrushf_t *trace_end, const colbrushf_t *other_start, const colbrushf_t *other_end)
639 {
640         int nplane, nplane2, nedge1, nedge2, hitq3surfaceflags = 0;
641         int tracenumedgedirs = trace_start->numedgedirs;
642         //int othernumedgedirs = other_start->numedgedirs;
643         int tracenumpoints = trace_start->numpoints;
644         int othernumpoints = other_start->numpoints;
645         int numplanes1 = other_start->numplanes;
646         int numplanes2 = numplanes1 + trace_start->numplanes;
647         int numplanes3 = numplanes2 + trace_start->numedgedirs * other_start->numedgedirs * 2;
648         vec_t enterfrac = -1, leavefrac = 1, startdist, enddist, ie, f, imove, enterfrac2 = -1;
649         vec4_t startplane;
650         vec4_t endplane;
651         vec4_t newimpactplane;
652         const texture_t *hittexture = NULL;
653         vec_t startdepth = 1;
654         vec3_t startdepthnormal;
655
656         VectorClear(startdepthnormal);
657         Vector4Clear(newimpactplane);
658
659         // fast case for AABB vs compiled brushes (which begin with AABB planes and also have precomputed bevels for AABB collisions)
660         if (trace_start->isaabb && other_start->hasaabbplanes)
661                 numplanes3 = numplanes2 = numplanes1;
662
663         // Separating Axis Theorem:
664         // if a supporting vector (plane normal) can be found that separates two
665         // objects, they are not colliding.
666         //
667         // Minkowski Sum:
668         // reduce the size of one object to a point while enlarging the other to
669         // represent the space that point can not occupy.
670         //
671         // try every plane we can construct between the two brushes and measure
672         // the distance between them.
673         for (nplane = 0;nplane < numplanes3;nplane++)
674         {
675                 if (nplane < numplanes1)
676                 {
677                         nplane2 = nplane;
678                         VectorCopy(other_start->planes[nplane2].normal, startplane);
679                         VectorCopy(other_end->planes[nplane2].normal, endplane);
680                 }
681                 else if (nplane < numplanes2)
682                 {
683                         nplane2 = nplane - numplanes1;
684                         VectorCopy(trace_start->planes[nplane2].normal, startplane);
685                         VectorCopy(trace_end->planes[nplane2].normal, endplane);
686                 }
687                 else
688                 {
689                         // pick an edgedir from each brush and cross them
690                         nplane2 = nplane - numplanes2;
691                         nedge1 = nplane2 >> 1;
692                         nedge2 = nedge1 / tracenumedgedirs;
693                         nedge1 -= nedge2 * tracenumedgedirs;
694                         if (nplane2 & 1)
695                         {
696                                 CrossProduct(trace_start->edgedirs[nedge1].v, other_start->edgedirs[nedge2].v, startplane);
697                                 if (VectorLength2(startplane) < COLLISION_EDGECROSS_MINLENGTH2)
698                                         continue; // degenerate crossproduct
699                                 CrossProduct(trace_end->edgedirs[nedge1].v, other_end->edgedirs[nedge2].v, endplane);
700                                 if (VectorLength2(endplane) < COLLISION_EDGECROSS_MINLENGTH2)
701                                         continue; // degenerate crossproduct
702                         }
703                         else
704                         {
705                                 CrossProduct(other_start->edgedirs[nedge2].v, trace_start->edgedirs[nedge1].v, startplane);
706                                 if (VectorLength2(startplane) < COLLISION_EDGECROSS_MINLENGTH2)
707                                         continue; // degenerate crossproduct
708                                 CrossProduct(other_end->edgedirs[nedge2].v, trace_end->edgedirs[nedge1].v, endplane);
709                                 if (VectorLength2(endplane) < COLLISION_EDGECROSS_MINLENGTH2)
710                                         continue; // degenerate crossproduct
711                         }
712                         VectorNormalize(startplane);
713                         VectorNormalize(endplane);
714                 }
715                 startplane[3] = furthestplanedist_float(startplane, other_start->points, othernumpoints);
716                 endplane[3] = furthestplanedist_float(startplane, other_end->points, othernumpoints);
717                 startdist = nearestplanedist_float(startplane, trace_start->points, tracenumpoints) - startplane[3] - collision_startnudge.value;
718                 enddist = nearestplanedist_float(endplane, trace_end->points, tracenumpoints) - endplane[3] - collision_endnudge.value;
719                 //Con_Printf("%c%i: startdist = %f, enddist = %f, startdist / (startdist - enddist) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, startdist, enddist, startdist / (startdist - enddist));
720
721                 // aside from collisions, this is also used for error correction
722                 if (startdist < collision_impactnudge.value && nplane < numplanes1 && (startdepth < startdist || startdepth == 1))
723                 {
724                         startdepth = startdist;
725                         VectorCopy(startplane, startdepthnormal);
726                 }
727
728                 if (startdist >= -collision_impactnudge.value && enddist >= startdist)
729                         return;
730                 if (startdist <= 0 && enddist <= 0)
731                         continue;
732                 if (startdist > enddist)
733                 {
734                         // moving into brush
735                         if (enddist >= collision_enternudge.value)
736                                 return;
737                         if (startdist > 0)
738                         {
739                                 // enter
740                                 imove = 1 / (startdist - enddist);
741                                 f = (startdist - collision_enternudge.value) * imove;
742                                 if (f < 0)
743                                         f = 0;
744                                 // check if this will reduce the collision time range
745                                 if (enterfrac < f)
746                                 {
747                                         // reduced collision time range
748                                         enterfrac = f;
749                                         // if the collision time range is now empty, no collision
750                                         if (enterfrac > leavefrac)
751                                                 return;
752                                         // if the collision would be further away than the trace's
753                                         // existing collision data, we don't care about this
754                                         // collision
755                                         if (enterfrac > trace->realfraction)
756                                                 return;
757                                         // calculate the nudged fraction and impact normal we'll
758                                         // need if we accept this collision later
759                                         enterfrac2 = (startdist - collision_impactnudge.value) * imove;
760                                         ie = 1.0f - enterfrac;
761                                         newimpactplane[0] = startplane[0] * ie + endplane[0] * enterfrac;
762                                         newimpactplane[1] = startplane[1] * ie + endplane[1] * enterfrac;
763                                         newimpactplane[2] = startplane[2] * ie + endplane[2] * enterfrac;
764                                         newimpactplane[3] = startplane[3] * ie + endplane[3] * enterfrac;
765                                         if (nplane < numplanes1)
766                                         {
767                                                 // use the plane from other
768                                                 nplane2 = nplane;
769                                                 hitq3surfaceflags = other_start->planes[nplane2].q3surfaceflags;
770                                                 hittexture = other_start->planes[nplane2].texture;
771                                         }
772                                         else if (nplane < numplanes2)
773                                         {
774                                                 // use the plane from trace
775                                                 nplane2 = nplane - numplanes1;
776                                                 hitq3surfaceflags = trace_start->planes[nplane2].q3surfaceflags;
777                                                 hittexture = trace_start->planes[nplane2].texture;
778                                         }
779                                         else
780                                         {
781                                                 hitq3surfaceflags = other_start->q3surfaceflags;
782                                                 hittexture = other_start->texture;
783                                         }
784                                 }
785                         }
786                 }
787                 else
788                 {
789                         // moving out of brush
790                         if (startdist > 0)
791                                 return;
792                         if (enddist > 0)
793                         {
794                                 // leave
795                                 f = (startdist + collision_leavenudge.value) / (startdist - enddist);
796                                 if (f > 1)
797                                         f = 1;
798                                 // check if this will reduce the collision time range
799                                 if (leavefrac > f)
800                                 {
801                                         // reduced collision time range
802                                         leavefrac = f;
803                                         // if the collision time range is now empty, no collision
804                                         if (enterfrac > leavefrac)
805                                                 return;
806                                 }
807                         }
808                 }
809         }
810
811         // at this point we know the trace overlaps the brush because it was not
812         // rejected at any point in the loop above
813
814         // see if the trace started outside the brush or not
815         if (enterfrac > -1)
816         {
817                 // started outside, and overlaps, therefore there is a collision here
818                 // store out the impact information
819                 if (trace->hitsupercontentsmask & other_start->supercontents)
820                 {
821                         trace->hitsupercontents = other_start->supercontents;
822                         trace->hitq3surfaceflags = hitq3surfaceflags;
823                         trace->hittexture = hittexture;
824                         trace->realfraction = bound(0, enterfrac, 1);
825                         trace->fraction = bound(0, enterfrac2, 1);
826                         if (collision_prefernudgedfraction.integer)
827                                 trace->realfraction = trace->fraction;
828                         VectorCopy(newimpactplane, trace->plane.normal);
829                         trace->plane.dist = newimpactplane[3];
830                 }
831         }
832         else
833         {
834                 // started inside, update startsolid and friends
835                 trace->startsupercontents |= other_start->supercontents;
836                 if (trace->hitsupercontentsmask & other_start->supercontents)
837                 {
838                         trace->startsolid = true;
839                         if (leavefrac < 1)
840                                 trace->allsolid = true;
841                         VectorCopy(newimpactplane, trace->plane.normal);
842                         trace->plane.dist = newimpactplane[3];
843                         if (trace->startdepth > startdepth)
844                         {
845                                 trace->startdepth = startdepth;
846                                 VectorCopy(startdepthnormal, trace->startdepthnormal);
847                         }
848                 }
849         }
850 }
851
852 // NOTE: start and end of each brush pair must have same numplanes/numpoints
853 void Collision_TraceLineBrushFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const colbrushf_t *other_start, const colbrushf_t *other_end)
854 {
855         int nplane, hitq3surfaceflags = 0;
856         int numplanes = other_start->numplanes;
857         vec_t enterfrac = -1, leavefrac = 1, startdist, enddist, ie, f, imove, enterfrac2 = -1;
858         vec4_t startplane;
859         vec4_t endplane;
860         vec4_t newimpactplane;
861         const texture_t *hittexture = NULL;
862         vec_t startdepth = 1;
863         vec3_t startdepthnormal;
864
865         if (collision_debug_tracelineasbox.integer)
866         {
867                 colboxbrushf_t thisbrush_start, thisbrush_end;
868                 Collision_BrushForBox(&thisbrush_start, linestart, linestart, 0, 0, NULL);
869                 Collision_BrushForBox(&thisbrush_end, lineend, lineend, 0, 0, NULL);
870                 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, other_start, other_end);
871                 return;
872         }
873
874         VectorClear(startdepthnormal);
875         Vector4Clear(newimpactplane);
876
877         // Separating Axis Theorem:
878         // if a supporting vector (plane normal) can be found that separates two
879         // objects, they are not colliding.
880         //
881         // Minkowski Sum:
882         // reduce the size of one object to a point while enlarging the other to
883         // represent the space that point can not occupy.
884         //
885         // try every plane we can construct between the two brushes and measure
886         // the distance between them.
887         for (nplane = 0;nplane < numplanes;nplane++)
888         {
889                 VectorCopy(other_start->planes[nplane].normal, startplane);
890                 startplane[3] = other_start->planes[nplane].dist;
891                 VectorCopy(other_end->planes[nplane].normal, endplane);
892                 endplane[3] = other_end->planes[nplane].dist;
893                 startdist = DotProduct(linestart, startplane) - startplane[3] - collision_startnudge.value;
894                 enddist = DotProduct(lineend, endplane) - endplane[3] - collision_endnudge.value;
895                 //Con_Printf("%c%i: startdist = %f, enddist = %f, startdist / (startdist - enddist) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, startdist, enddist, startdist / (startdist - enddist));
896
897                 // aside from collisions, this is also used for error correction
898                 if (startdist < collision_impactnudge.value && (startdepth < startdist || startdepth == 1))
899                 {
900                         startdepth = startdist;
901                         VectorCopy(startplane, startdepthnormal);
902                 }
903
904                 if (startdist >= -collision_impactnudge.value && enddist >= startdist)
905                         return;
906                 if (startdist <= 0 && enddist <= 0)
907                         continue;
908                 if (startdist > enddist)
909                 {
910                         // moving into brush
911                         if (enddist >= collision_enternudge.value)
912                                 return;
913                         if (startdist > 0)
914                         {
915                                 // enter
916                                 imove = 1 / (startdist - enddist);
917                                 f = (startdist - collision_enternudge.value) * imove;
918                                 if (f < 0)
919                                         f = 0;
920                                 // check if this will reduce the collision time range
921                                 if (enterfrac < f)
922                                 {
923                                         // reduced collision time range
924                                         enterfrac = f;
925                                         // if the collision time range is now empty, no collision
926                                         if (enterfrac > leavefrac)
927                                                 return;
928                                         // if the collision would be further away than the trace's
929                                         // existing collision data, we don't care about this
930                                         // collision
931                                         if (enterfrac > trace->realfraction)
932                                                 return;
933                                         // calculate the nudged fraction and impact normal we'll
934                                         // need if we accept this collision later
935                                         enterfrac2 = (startdist - collision_impactnudge.value) * imove;
936                                         ie = 1.0f - enterfrac;
937                                         newimpactplane[0] = startplane[0] * ie + endplane[0] * enterfrac;
938                                         newimpactplane[1] = startplane[1] * ie + endplane[1] * enterfrac;
939                                         newimpactplane[2] = startplane[2] * ie + endplane[2] * enterfrac;
940                                         newimpactplane[3] = startplane[3] * ie + endplane[3] * enterfrac;
941                                         hitq3surfaceflags = other_start->planes[nplane].q3surfaceflags;
942                                         hittexture = other_start->planes[nplane].texture;
943                                 }
944                         }
945                 }
946                 else
947                 {
948                         // moving out of brush
949                         if (startdist > 0)
950                                 return;
951                         if (enddist > 0)
952                         {
953                                 // leave
954                                 f = (startdist + collision_leavenudge.value) / (startdist - enddist);
955                                 if (f > 1)
956                                         f = 1;
957                                 // check if this will reduce the collision time range
958                                 if (leavefrac > f)
959                                 {
960                                         // reduced collision time range
961                                         leavefrac = f;
962                                         // if the collision time range is now empty, no collision
963                                         if (enterfrac > leavefrac)
964                                                 return;
965                                 }
966                         }
967                 }
968         }
969
970         // at this point we know the trace overlaps the brush because it was not
971         // rejected at any point in the loop above
972
973         // see if the trace started outside the brush or not
974         if (enterfrac > -1)
975         {
976                 // started outside, and overlaps, therefore there is a collision here
977                 // store out the impact information
978                 if (trace->hitsupercontentsmask & other_start->supercontents)
979                 {
980                         trace->hitsupercontents = other_start->supercontents;
981                         trace->hitq3surfaceflags = hitq3surfaceflags;
982                         trace->hittexture = hittexture;
983                         trace->realfraction = bound(0, enterfrac, 1);
984                         trace->fraction = bound(0, enterfrac2, 1);
985                         if (collision_prefernudgedfraction.integer)
986                                 trace->realfraction = trace->fraction;
987                         VectorCopy(newimpactplane, trace->plane.normal);
988                         trace->plane.dist = newimpactplane[3];
989                 }
990         }
991         else
992         {
993                 // started inside, update startsolid and friends
994                 trace->startsupercontents |= other_start->supercontents;
995                 if (trace->hitsupercontentsmask & other_start->supercontents)
996                 {
997                         trace->startsolid = true;
998                         if (leavefrac < 1)
999                                 trace->allsolid = true;
1000                         VectorCopy(newimpactplane, trace->plane.normal);
1001                         trace->plane.dist = newimpactplane[3];
1002                         if (trace->startdepth > startdepth)
1003                         {
1004                                 trace->startdepth = startdepth;
1005                                 VectorCopy(startdepthnormal, trace->startdepthnormal);
1006                         }
1007                 }
1008         }
1009 }
1010
1011 qboolean Collision_PointInsideBrushFloat(const vec3_t point, const colbrushf_t *brush)
1012 {
1013         int nplane;
1014         const colplanef_t *plane;
1015
1016         if (!BoxesOverlap(point, point, brush->mins, brush->maxs))
1017                 return false;
1018         for (nplane = 0, plane = brush->planes;nplane < brush->numplanes;nplane++, plane++)
1019                 if (DotProduct(plane->normal, point) > plane->dist)
1020                         return false;
1021         return true;
1022 }
1023
1024 void Collision_TracePointBrushFloat(trace_t *trace, const vec3_t point, const colbrushf_t *thatbrush)
1025 {
1026         if (!Collision_PointInsideBrushFloat(point, thatbrush))
1027                 return;
1028
1029         trace->startsupercontents |= thatbrush->supercontents;
1030         if (trace->hitsupercontentsmask & thatbrush->supercontents)
1031         {
1032                 trace->startsolid = true;
1033                 trace->allsolid = true;
1034         }
1035 }
1036
1037 void Collision_SnapCopyPoints(int numpoints, const colpointf_t *in, colpointf_t *out, float fractionprecision, float invfractionprecision)
1038 {
1039         int i;
1040         for (i = 0;i < numpoints;i++)
1041         {
1042                 out[i].v[0] = floor(in[i].v[0] * fractionprecision + 0.5f) * invfractionprecision;
1043                 out[i].v[1] = floor(in[i].v[1] * fractionprecision + 0.5f) * invfractionprecision;
1044                 out[i].v[2] = floor(in[i].v[2] * fractionprecision + 0.5f) * invfractionprecision;
1045         }
1046 }
1047
1048 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 stride, float *bbox6f, int supercontents, int q3surfaceflags, const texture_t *texture, const vec3_t segmentmins, const vec3_t segmentmaxs)
1049 {
1050         int i;
1051         colpointf_t points[3];
1052         colpointf_t edgedirs[3];
1053         colplanef_t planes[5];
1054         colbrushf_t brush;
1055         memset(&brush, 0, sizeof(brush));
1056         brush.isaabb = false;
1057         brush.hasaabbplanes = false;
1058         brush.numpoints = 3;
1059         brush.numedgedirs = 3;
1060         brush.numplanes = 5;
1061         brush.points = points;
1062         brush.edgedirs = edgedirs;
1063         brush.planes = planes;
1064         brush.supercontents = supercontents;
1065         brush.q3surfaceflags = q3surfaceflags;
1066         brush.texture = texture;
1067         for (i = 0;i < brush.numplanes;i++)
1068         {
1069                 brush.planes[i].q3surfaceflags = q3surfaceflags;
1070                 brush.planes[i].texture = texture;
1071         }
1072         if(stride > 0)
1073         {
1074                 int k, cnt, tri;
1075                 cnt = (numtriangles + stride - 1) / stride;
1076                 for(i = 0; i < cnt; ++i)
1077                 {
1078                         if(BoxesOverlap(bbox6f + i * 6, bbox6f + i * 6 + 3, segmentmins, segmentmaxs))
1079                         {
1080                                 for(k = 0; k < stride; ++k)
1081                                 {
1082                                         tri = i * stride + k;
1083                                         if(tri >= numtriangles)
1084                                                 break;
1085                                         VectorCopy(vertex3f + element3i[tri * 3 + 0] * 3, points[0].v);
1086                                         VectorCopy(vertex3f + element3i[tri * 3 + 1] * 3, points[1].v);
1087                                         VectorCopy(vertex3f + element3i[tri * 3 + 2] * 3, points[2].v);
1088                                         Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1089                                         Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1090                                         Collision_CalcPlanesForPolygonBrushFloat(&brush);
1091                                         //Collision_PrintBrushAsQHull(&brush, "brush");
1092                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1093                                 }
1094                         }
1095                 }
1096         }
1097         else if(stride == 0)
1098         {
1099                 for (i = 0;i < numtriangles;i++, element3i += 3)
1100                 {
1101                         if (TriangleOverlapsBox(vertex3f + element3i[0]*3, vertex3f + element3i[1]*3, vertex3f + element3i[2]*3, segmentmins, segmentmaxs))
1102                         {
1103                                 VectorCopy(vertex3f + element3i[0] * 3, points[0].v);
1104                                 VectorCopy(vertex3f + element3i[1] * 3, points[1].v);
1105                                 VectorCopy(vertex3f + element3i[2] * 3, points[2].v);
1106                                 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1107                                 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1108                                 Collision_CalcPlanesForPolygonBrushFloat(&brush);
1109                                 //Collision_PrintBrushAsQHull(&brush, "brush");
1110                                 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1111                         }
1112                 }
1113         }
1114         else
1115         {
1116                 for (i = 0;i < numtriangles;i++, element3i += 3)
1117                 {
1118                         VectorCopy(vertex3f + element3i[0] * 3, points[0].v);
1119                         VectorCopy(vertex3f + element3i[1] * 3, points[1].v);
1120                         VectorCopy(vertex3f + element3i[2] * 3, points[2].v);
1121                         Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1122                         Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1123                         Collision_CalcPlanesForPolygonBrushFloat(&brush);
1124                         //Collision_PrintBrushAsQHull(&brush, "brush");
1125                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1126                 }
1127         }
1128 }
1129
1130 void Collision_TraceLineTriangleMeshFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, int numtriangles, const int *element3i, const float *vertex3f, int stride, float *bbox6f, int supercontents, int q3surfaceflags, const texture_t *texture, const vec3_t segmentmins, const vec3_t segmentmaxs)
1131 {
1132         int i;
1133         // FIXME: snap vertices?
1134         if(stride > 0)
1135         {
1136                 int k, cnt, tri;
1137                 cnt = (numtriangles + stride - 1) / stride;
1138                 for(i = 0; i < cnt; ++i)
1139                 {
1140                         if(BoxesOverlap(bbox6f + i * 6, bbox6f + i * 6 + 3, segmentmins, segmentmaxs))
1141                         {
1142                                 for(k = 0; k < stride; ++k)
1143                                 {
1144                                         tri = i * stride + k;
1145                                         if(tri >= numtriangles)
1146                                                 break;
1147                                         Collision_TraceLineTriangleFloat(trace, linestart, lineend, vertex3f + element3i[tri * 3 + 0] * 3, vertex3f + element3i[tri * 3 + 1] * 3, vertex3f + element3i[tri * 3 + 2] * 3, supercontents, q3surfaceflags, texture);
1148                                 }
1149                         }
1150                 }
1151         }
1152         else
1153         {
1154                 for (i = 0;i < numtriangles;i++, element3i += 3)
1155                         Collision_TraceLineTriangleFloat(trace, linestart, lineend, vertex3f + element3i[0] * 3, vertex3f + element3i[1] * 3, vertex3f + element3i[2] * 3, supercontents, q3surfaceflags, texture);
1156         }
1157 }
1158
1159 void Collision_TraceBrushTriangleFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, const float *v0, const float *v1, const float *v2, int supercontents, int q3surfaceflags, const texture_t *texture)
1160 {
1161         int i;
1162         colpointf_t points[3];
1163         colpointf_t edgedirs[3];
1164         colplanef_t planes[5];
1165         colbrushf_t brush;
1166         memset(&brush, 0, sizeof(brush));
1167         brush.isaabb = false;
1168         brush.hasaabbplanes = false;
1169         brush.numpoints = 3;
1170         brush.numedgedirs = 3;
1171         brush.numplanes = 5;
1172         brush.points = points;
1173         brush.edgedirs = edgedirs;
1174         brush.planes = planes;
1175         brush.supercontents = supercontents;
1176         brush.q3surfaceflags = q3surfaceflags;
1177         brush.texture = texture;
1178         for (i = 0;i < brush.numplanes;i++)
1179         {
1180                 brush.planes[i].q3surfaceflags = q3surfaceflags;
1181                 brush.planes[i].texture = texture;
1182         }
1183         VectorCopy(v0, points[0].v);
1184         VectorCopy(v1, points[1].v);
1185         VectorCopy(v2, points[2].v);
1186         Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1187         Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1188         Collision_CalcPlanesForPolygonBrushFloat(&brush);
1189         //Collision_PrintBrushAsQHull(&brush, "brush");
1190         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1191 }
1192
1193 void Collision_BrushForBox(colboxbrushf_t *boxbrush, const vec3_t mins, const vec3_t maxs, int supercontents, int q3surfaceflags, const texture_t *texture)
1194 {
1195         int i;
1196         memset(boxbrush, 0, sizeof(*boxbrush));
1197         boxbrush->brush.isaabb = true;
1198         boxbrush->brush.hasaabbplanes = true;
1199         boxbrush->brush.points = boxbrush->points;
1200         boxbrush->brush.edgedirs = boxbrush->edgedirs;
1201         boxbrush->brush.planes = boxbrush->planes;
1202         boxbrush->brush.supercontents = supercontents;
1203         boxbrush->brush.q3surfaceflags = q3surfaceflags;
1204         boxbrush->brush.texture = texture;
1205         if (VectorCompare(mins, maxs))
1206         {
1207                 // point brush
1208                 boxbrush->brush.numpoints = 1;
1209                 boxbrush->brush.numedgedirs = 0;
1210                 boxbrush->brush.numplanes = 0;
1211                 VectorCopy(mins, boxbrush->brush.points[0].v);
1212         }
1213         else
1214         {
1215                 boxbrush->brush.numpoints = 8;
1216                 boxbrush->brush.numedgedirs = 3;
1217                 boxbrush->brush.numplanes = 6;
1218                 // there are 8 points on a box
1219                 // there are 3 edgedirs on a box (both signs are tested in collision)
1220                 // there are 6 planes on a box
1221                 VectorSet(boxbrush->brush.points[0].v, mins[0], mins[1], mins[2]);
1222                 VectorSet(boxbrush->brush.points[1].v, maxs[0], mins[1], mins[2]);
1223                 VectorSet(boxbrush->brush.points[2].v, mins[0], maxs[1], mins[2]);
1224                 VectorSet(boxbrush->brush.points[3].v, maxs[0], maxs[1], mins[2]);
1225                 VectorSet(boxbrush->brush.points[4].v, mins[0], mins[1], maxs[2]);
1226                 VectorSet(boxbrush->brush.points[5].v, maxs[0], mins[1], maxs[2]);
1227                 VectorSet(boxbrush->brush.points[6].v, mins[0], maxs[1], maxs[2]);
1228                 VectorSet(boxbrush->brush.points[7].v, maxs[0], maxs[1], maxs[2]);
1229                 VectorSet(boxbrush->brush.edgedirs[0].v, 1, 0, 0);
1230                 VectorSet(boxbrush->brush.edgedirs[1].v, 0, 1, 0);
1231                 VectorSet(boxbrush->brush.edgedirs[2].v, 0, 0, 1);
1232                 VectorSet(boxbrush->brush.planes[0].normal, -1,  0,  0);boxbrush->brush.planes[0].dist = -mins[0];
1233                 VectorSet(boxbrush->brush.planes[1].normal,  1,  0,  0);boxbrush->brush.planes[1].dist =  maxs[0];
1234                 VectorSet(boxbrush->brush.planes[2].normal,  0, -1,  0);boxbrush->brush.planes[2].dist = -mins[1];
1235                 VectorSet(boxbrush->brush.planes[3].normal,  0,  1,  0);boxbrush->brush.planes[3].dist =  maxs[1];
1236                 VectorSet(boxbrush->brush.planes[4].normal,  0,  0, -1);boxbrush->brush.planes[4].dist = -mins[2];
1237                 VectorSet(boxbrush->brush.planes[5].normal,  0,  0,  1);boxbrush->brush.planes[5].dist =  maxs[2];
1238                 for (i = 0;i < 6;i++)
1239                 {
1240                         boxbrush->brush.planes[i].q3surfaceflags = q3surfaceflags;
1241                         boxbrush->brush.planes[i].texture = texture;
1242                 }
1243         }
1244         boxbrush->brush.supercontents = supercontents;
1245         boxbrush->brush.q3surfaceflags = q3surfaceflags;
1246         boxbrush->brush.texture = texture;
1247         VectorSet(boxbrush->brush.mins, mins[0] - 1, mins[1] - 1, mins[2] - 1);
1248         VectorSet(boxbrush->brush.maxs, maxs[0] + 1, maxs[1] + 1, maxs[2] + 1);
1249         Collision_ValidateBrush(&boxbrush->brush);
1250 }
1251
1252 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, int supercontents, int q3surfaceflags, texture_t *texture)
1253 {
1254         colboxbrushf_t boxbrush, thisbrush_start, thisbrush_end;
1255         vec3_t startmins, startmaxs, endmins, endmaxs;
1256
1257         // create brushes for the collision
1258         VectorAdd(start, mins, startmins);
1259         VectorAdd(start, maxs, startmaxs);
1260         VectorAdd(end, mins, endmins);
1261         VectorAdd(end, maxs, endmaxs);
1262         Collision_BrushForBox(&boxbrush, cmins, cmaxs, supercontents, q3surfaceflags, texture);
1263         Collision_BrushForBox(&thisbrush_start, startmins, startmaxs, 0, 0, NULL);
1264         Collision_BrushForBox(&thisbrush_end, endmins, endmaxs, 0, 0, NULL);
1265
1266         memset(trace, 0, sizeof(trace_t));
1267         trace->hitsupercontentsmask = hitsupercontentsmask;
1268         trace->fraction = 1;
1269         trace->realfraction = 1;
1270         trace->allsolid = true;
1271         Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, &boxbrush.brush, &boxbrush.brush);
1272 }
1273
1274 //pseudocode for detecting line/sphere overlap without calculating an impact point
1275 //linesphereorigin = sphereorigin - linestart;linediff = lineend - linestart;linespherefrac = DotProduct(linesphereorigin, linediff) / DotProduct(linediff, linediff);return VectorLength2(linesphereorigin - bound(0, linespherefrac, 1) * linediff) >= sphereradius*sphereradius;
1276
1277 // LordHavoc: currently unused, but tested
1278 // note: this can be used for tracing a moving sphere vs a stationary sphere,
1279 // by simply adding the moving sphere's radius to the sphereradius parameter,
1280 // all the results are correct (impactpoint, impactnormal, and fraction)
1281 float Collision_ClipTrace_Line_Sphere(double *linestart, double *lineend, double *sphereorigin, double sphereradius, double *impactpoint, double *impactnormal)
1282 {
1283         double dir[3], scale, v[3], deviationdist, impactdist, linelength;
1284         // make sure the impactpoint and impactnormal are valid even if there is
1285         // no collision
1286         VectorCopy(lineend, impactpoint);
1287         VectorClear(impactnormal);
1288         // calculate line direction
1289         VectorSubtract(lineend, linestart, dir);
1290         // normalize direction
1291         linelength = VectorLength(dir);
1292         if (linelength)
1293         {
1294                 scale = 1.0 / linelength;
1295                 VectorScale(dir, scale, dir);
1296         }
1297         // this dotproduct calculates the distance along the line at which the
1298         // sphere origin is (nearest point to the sphere origin on the line)
1299         impactdist = DotProduct(sphereorigin, dir) - DotProduct(linestart, dir);
1300         // calculate point on line at that distance, and subtract the
1301         // sphereorigin from it, so we have a vector to measure for the distance
1302         // of the line from the sphereorigin (deviation, how off-center it is)
1303         VectorMA(linestart, impactdist, dir, v);
1304         VectorSubtract(v, sphereorigin, v);
1305         deviationdist = VectorLength2(v);
1306         // if outside the radius, it's a miss for sure
1307         // (we do this comparison using squared radius to avoid a sqrt)
1308         if (deviationdist > sphereradius*sphereradius)
1309                 return 1; // miss (off to the side)
1310         // nudge back to find the correct impact distance
1311         impactdist -= sphereradius - deviationdist/sphereradius;
1312         if (impactdist >= linelength)
1313                 return 1; // miss (not close enough)
1314         if (impactdist < 0)
1315                 return 1; // miss (linestart is past or inside sphere)
1316         // calculate new impactpoint
1317         VectorMA(linestart, impactdist, dir, impactpoint);
1318         // calculate impactnormal (surface normal at point of impact)
1319         VectorSubtract(impactpoint, sphereorigin, impactnormal);
1320         // normalize impactnormal
1321         VectorNormalize(impactnormal);
1322         // return fraction of movement distance
1323         return impactdist / linelength;
1324 }
1325
1326 void Collision_TraceLineTriangleFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const float *point0, const float *point1, const float *point2, int supercontents, int q3surfaceflags, const texture_t *texture)
1327 {
1328 #if 1
1329         // more optimized
1330         float d1, d2, d, f, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, faceplanenormallength2, edge01[3], edge21[3], edge02[3];
1331
1332         // this function executes:
1333         // 32 ops when line starts behind triangle
1334         // 38 ops when line ends infront of triangle
1335         // 43 ops when line fraction is already closer than this triangle
1336         // 72 ops when line is outside edge 01
1337         // 92 ops when line is outside edge 21
1338         // 115 ops when line is outside edge 02
1339         // 123 ops when line impacts triangle and updates trace results
1340
1341         // this code is designed for clockwise triangles, conversion to
1342         // counterclockwise would require swapping some things around...
1343         // it is easier to simply swap the point0 and point2 parameters to this
1344         // function when calling it than it is to rewire the internals.
1345
1346         // calculate the faceplanenormal of the triangle, this represents the front side
1347         // 15 ops
1348         VectorSubtract(point0, point1, edge01);
1349         VectorSubtract(point2, point1, edge21);
1350         CrossProduct(edge01, edge21, faceplanenormal);
1351         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
1352         // 6 ops
1353         faceplanenormallength2 = DotProduct(faceplanenormal, faceplanenormal);
1354         if (faceplanenormallength2 < 0.0001f)
1355                 return;
1356         // calculate the distance
1357         // 5 ops
1358         faceplanedist = DotProduct(point0, faceplanenormal);
1359
1360         // if start point is on the back side there is no collision
1361         // (we don't care about traces going through the triangle the wrong way)
1362
1363         // calculate the start distance
1364         // 6 ops
1365         d1 = DotProduct(faceplanenormal, linestart);
1366         if (d1 <= faceplanedist)
1367                 return;
1368
1369         // calculate the end distance
1370         // 6 ops
1371         d2 = DotProduct(faceplanenormal, lineend);
1372         // if both are in front, there is no collision
1373         if (d2 >= faceplanedist)
1374                 return;
1375
1376         // from here on we know d1 is >= 0 and d2 is < 0
1377         // this means the line starts infront and ends behind, passing through it
1378
1379         // calculate the recipricol of the distance delta,
1380         // so we can use it multiple times cheaply (instead of division)
1381         // 2 ops
1382         d = 1.0f / (d1 - d2);
1383         // calculate the impact fraction by taking the start distance (> 0)
1384         // and subtracting the face plane distance (this is the distance of the
1385         // triangle along that same normal)
1386         // then multiply by the recipricol distance delta
1387         // 2 ops
1388         f = (d1 - faceplanedist) * d;
1389         // skip out if this impact is further away than previous ones
1390         // 1 ops
1391         if (f > trace->realfraction)
1392                 return;
1393         // calculate the perfect impact point for classification of insidedness
1394         // 9 ops
1395         impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1396         impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1397         impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1398
1399         // calculate the edge normal and reject if impact is outside triangle
1400         // (an edge normal faces away from the triangle, to get the desired normal
1401         //  a crossproduct with the faceplanenormal is used, and because of the way
1402         // the insidedness comparison is written it does not need to be normalized)
1403
1404         // first use the two edges from the triangle plane math
1405         // the other edge only gets calculated if the point survives that long
1406
1407         // 20 ops
1408         CrossProduct(edge01, faceplanenormal, edgenormal);
1409         if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1410                 return;
1411
1412         // 20 ops
1413         CrossProduct(faceplanenormal, edge21, edgenormal);
1414         if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1415                 return;
1416
1417         // 23 ops
1418         VectorSubtract(point0, point2, edge02);
1419         CrossProduct(faceplanenormal, edge02, edgenormal);
1420         if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1421                 return;
1422
1423         // 8 ops (rare)
1424
1425         // store the new trace fraction
1426         trace->realfraction = f;
1427
1428         // calculate a nudged fraction to keep it out of the surface
1429         // (the main fraction remains perfect)
1430         trace->fraction = f - collision_impactnudge.value * d;
1431
1432         if (collision_prefernudgedfraction.integer)
1433                 trace->realfraction = trace->fraction;
1434
1435         // store the new trace plane (because collisions only happen from
1436         // the front this is always simply the triangle normal, never flipped)
1437         d = 1.0 / sqrt(faceplanenormallength2);
1438         VectorScale(faceplanenormal, d, trace->plane.normal);
1439         trace->plane.dist = faceplanedist * d;
1440
1441         trace->hitsupercontents = supercontents;
1442         trace->hitq3surfaceflags = q3surfaceflags;
1443         trace->hittexture = texture;
1444 #else
1445         float d1, d2, d, f, fnudged, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, edge[3];
1446
1447         // this code is designed for clockwise triangles, conversion to
1448         // counterclockwise would require swapping some things around...
1449         // it is easier to simply swap the point0 and point2 parameters to this
1450         // function when calling it than it is to rewire the internals.
1451
1452         // calculate the unnormalized faceplanenormal of the triangle,
1453         // this represents the front side
1454         TriangleNormal(point0, point1, point2, faceplanenormal);
1455         // there's no point in processing a degenerate triangle
1456         // (GIGO - Garbage In, Garbage Out)
1457         if (DotProduct(faceplanenormal, faceplanenormal) < 0.0001f)
1458                 return;
1459         // calculate the unnormalized distance
1460         faceplanedist = DotProduct(point0, faceplanenormal);
1461
1462         // calculate the unnormalized start distance
1463         d1 = DotProduct(faceplanenormal, linestart) - faceplanedist;
1464         // if start point is on the back side there is no collision
1465         // (we don't care about traces going through the triangle the wrong way)
1466         if (d1 <= 0)
1467                 return;
1468
1469         // calculate the unnormalized end distance
1470         d2 = DotProduct(faceplanenormal, lineend) - faceplanedist;
1471         // if both are in front, there is no collision
1472         if (d2 >= 0)
1473                 return;
1474
1475         // from here on we know d1 is >= 0 and d2 is < 0
1476         // this means the line starts infront and ends behind, passing through it
1477
1478         // calculate the recipricol of the distance delta,
1479         // so we can use it multiple times cheaply (instead of division)
1480         d = 1.0f / (d1 - d2);
1481         // calculate the impact fraction by taking the start distance (> 0)
1482         // and subtracting the face plane distance (this is the distance of the
1483         // triangle along that same normal)
1484         // then multiply by the recipricol distance delta
1485         f = d1 * d;
1486         // skip out if this impact is further away than previous ones
1487         if (f > trace->realfraction)
1488                 return;
1489         // calculate the perfect impact point for classification of insidedness
1490         impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1491         impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1492         impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1493
1494         // calculate the edge normal and reject if impact is outside triangle
1495         // (an edge normal faces away from the triangle, to get the desired normal
1496         //  a crossproduct with the faceplanenormal is used, and because of the way
1497         // the insidedness comparison is written it does not need to be normalized)
1498
1499         VectorSubtract(point2, point0, edge);
1500         CrossProduct(edge, faceplanenormal, edgenormal);
1501         if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1502                 return;
1503
1504         VectorSubtract(point0, point1, edge);
1505         CrossProduct(edge, faceplanenormal, edgenormal);
1506         if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1507                 return;
1508
1509         VectorSubtract(point1, point2, edge);
1510         CrossProduct(edge, faceplanenormal, edgenormal);
1511         if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1512                 return;
1513
1514         // store the new trace fraction
1515         trace->realfraction = bound(0, f, 1);
1516
1517         // store the new trace plane (because collisions only happen from
1518         // the front this is always simply the triangle normal, never flipped)
1519         VectorNormalize(faceplanenormal);
1520         VectorCopy(faceplanenormal, trace->plane.normal);
1521         trace->plane.dist = DotProduct(point0, faceplanenormal);
1522
1523         // calculate the normalized start and end distances
1524         d1 = DotProduct(trace->plane.normal, linestart) - trace->plane.dist;
1525         d2 = DotProduct(trace->plane.normal, lineend) - trace->plane.dist;
1526
1527         // calculate a nudged fraction to keep it out of the surface
1528         // (the main fraction remains perfect)
1529         fnudged = (d1 - collision_impactnudge.value) / (d1 - d2);
1530         trace->fraction = bound(0, fnudged, 1);
1531
1532         // store the new trace endpos
1533         // not needed, it's calculated later when the trace is finished
1534         //trace->endpos[0] = linestart[0] + fnudged * (lineend[0] - linestart[0]);
1535         //trace->endpos[1] = linestart[1] + fnudged * (lineend[1] - linestart[1]);
1536         //trace->endpos[2] = linestart[2] + fnudged * (lineend[2] - linestart[2]);
1537         trace->hitsupercontents = supercontents;
1538         trace->hitq3surfaceflags = q3surfaceflags;
1539         trace->hittexture = texture;
1540 #endif
1541 }
1542
1543 typedef struct colbspnode_s
1544 {
1545         mplane_t plane;
1546         struct colbspnode_s *children[2];
1547         // the node is reallocated or split if max is reached
1548         int numcolbrushf;
1549         int maxcolbrushf;
1550         colbrushf_t **colbrushflist;
1551         //int numcolbrushd;
1552         //int maxcolbrushd;
1553         //colbrushd_t **colbrushdlist;
1554 }
1555 colbspnode_t;
1556
1557 typedef struct colbsp_s
1558 {
1559         mempool_t *mempool;
1560         colbspnode_t *nodes;
1561 }
1562 colbsp_t;
1563
1564 colbsp_t *Collision_CreateCollisionBSP(mempool_t *mempool)
1565 {
1566         colbsp_t *bsp;
1567         bsp = (colbsp_t *)Mem_Alloc(mempool, sizeof(colbsp_t));
1568         bsp->mempool = mempool;
1569         bsp->nodes = (colbspnode_t *)Mem_Alloc(bsp->mempool, sizeof(colbspnode_t));
1570         return bsp;
1571 }
1572
1573 void Collision_FreeCollisionBSPNode(colbspnode_t *node)
1574 {
1575         if (node->children[0])
1576                 Collision_FreeCollisionBSPNode(node->children[0]);
1577         if (node->children[1])
1578                 Collision_FreeCollisionBSPNode(node->children[1]);
1579         while (--node->numcolbrushf)
1580                 Mem_Free(node->colbrushflist[node->numcolbrushf]);
1581         //while (--node->numcolbrushd)
1582         //      Mem_Free(node->colbrushdlist[node->numcolbrushd]);
1583         Mem_Free(node);
1584 }
1585
1586 void Collision_FreeCollisionBSP(colbsp_t *bsp)
1587 {
1588         Collision_FreeCollisionBSPNode(bsp->nodes);
1589         Mem_Free(bsp);
1590 }
1591
1592 void Collision_BoundingBoxOfBrushTraceSegment(const colbrushf_t *start, const colbrushf_t *end, vec3_t mins, vec3_t maxs, float startfrac, float endfrac)
1593 {
1594         int i;
1595         colpointf_t *ps, *pe;
1596         float tempstart[3], tempend[3];
1597         VectorLerp(start->points[0].v, startfrac, end->points[0].v, mins);
1598         VectorCopy(mins, maxs);
1599         for (i = 0, ps = start->points, pe = end->points;i < start->numpoints;i++, ps++, pe++)
1600         {
1601                 VectorLerp(ps->v, startfrac, pe->v, tempstart);
1602                 VectorLerp(ps->v, endfrac, pe->v, tempend);
1603                 mins[0] = min(mins[0], min(tempstart[0], tempend[0]));
1604                 mins[1] = min(mins[1], min(tempstart[1], tempend[1]));
1605                 mins[2] = min(mins[2], min(tempstart[2], tempend[2]));
1606                 maxs[0] = min(maxs[0], min(tempstart[0], tempend[0]));
1607                 maxs[1] = min(maxs[1], min(tempstart[1], tempend[1]));
1608                 maxs[2] = min(maxs[2], min(tempstart[2], tempend[2]));
1609         }
1610         mins[0] -= 1;
1611         mins[1] -= 1;
1612         mins[2] -= 1;
1613         maxs[0] += 1;
1614         maxs[1] += 1;
1615         maxs[2] += 1;
1616 }
1617
1618 //===========================================
1619
1620 void Collision_ClipToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask)
1621 {
1622         float starttransformed[3], endtransformed[3];
1623
1624         memset(trace, 0, sizeof(*trace));
1625         trace->fraction = trace->realfraction = 1;
1626
1627         Matrix4x4_Transform(inversematrix, start, starttransformed);
1628         Matrix4x4_Transform(inversematrix, end, endtransformed);
1629 #if COLLISIONPARANOID >= 3
1630         Con_Printf("trans(%f %f %f -> %f %f %f, %f %f %f -> %f %f %f)", start[0], start[1], start[2], starttransformed[0], starttransformed[1], starttransformed[2], end[0], end[1], end[2], endtransformed[0], endtransformed[1], endtransformed[2]);
1631 #endif
1632
1633         if (model && model->TraceBox)
1634                 model->TraceBox(model, frameblend, skeleton, trace, starttransformed, mins, maxs, endtransformed, hitsupercontentsmask);
1635         else
1636                 Collision_ClipTrace_Box(trace, bodymins, bodymaxs, starttransformed, mins, maxs, endtransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1637         trace->fraction = bound(0, trace->fraction, 1);
1638         trace->realfraction = bound(0, trace->realfraction, 1);
1639
1640         VectorLerp(start, trace->fraction, end, trace->endpos);
1641         // transform plane
1642         // NOTE: this relies on plane.dist being directly after plane.normal
1643         Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1644 }
1645
1646 void Collision_ClipToWorld(trace_t *trace, dp_model_t *model, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontents)
1647 {
1648         memset(trace, 0, sizeof(*trace));
1649         trace->fraction = trace->realfraction = 1;
1650         if (model && model->TraceBox)
1651                 model->TraceBox(model, NULL, NULL, trace, start, mins, maxs, end, hitsupercontents);
1652         trace->fraction = bound(0, trace->fraction, 1);
1653         trace->realfraction = bound(0, trace->realfraction, 1);
1654         VectorLerp(start, trace->fraction, end, trace->endpos);
1655 }
1656
1657 void Collision_ClipLineToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
1658 {
1659         float starttransformed[3], endtransformed[3];
1660
1661         memset(trace, 0, sizeof(*trace));
1662         trace->fraction = trace->realfraction = 1;
1663
1664         Matrix4x4_Transform(inversematrix, start, starttransformed);
1665         Matrix4x4_Transform(inversematrix, end, endtransformed);
1666 #if COLLISIONPARANOID >= 3
1667         Con_Printf("trans(%f %f %f -> %f %f %f, %f %f %f -> %f %f %f)", start[0], start[1], start[2], starttransformed[0], starttransformed[1], starttransformed[2], end[0], end[1], end[2], endtransformed[0], endtransformed[1], endtransformed[2]);
1668 #endif
1669
1670         if (model && model->TraceLine)
1671                 model->TraceLine(model, frameblend, skeleton, trace, starttransformed, endtransformed, hitsupercontentsmask);
1672         else
1673                 Collision_ClipTrace_Box(trace, bodymins, bodymaxs, starttransformed, vec3_origin, vec3_origin, endtransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1674         trace->fraction = bound(0, trace->fraction, 1);
1675         trace->realfraction = bound(0, trace->realfraction, 1);
1676
1677         VectorLerp(start, trace->fraction, end, trace->endpos);
1678         // transform plane
1679         // NOTE: this relies on plane.dist being directly after plane.normal
1680         Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1681 }
1682
1683 void Collision_ClipLineToWorld(trace_t *trace, dp_model_t *model, const vec3_t start, const vec3_t end, int hitsupercontents)
1684 {
1685         memset(trace, 0, sizeof(*trace));
1686         trace->fraction = trace->realfraction = 1;
1687         if (model && model->TraceLine)
1688                 model->TraceLine(model, NULL, NULL, trace, start, end, hitsupercontents);
1689         trace->fraction = bound(0, trace->fraction, 1);
1690         trace->realfraction = bound(0, trace->realfraction, 1);
1691         VectorLerp(start, trace->fraction, end, trace->endpos);
1692 }
1693
1694 void Collision_ClipPointToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, int hitsupercontentsmask)
1695 {
1696         float starttransformed[3];
1697
1698         memset(trace, 0, sizeof(*trace));
1699         trace->fraction = trace->realfraction = 1;
1700
1701         Matrix4x4_Transform(inversematrix, start, starttransformed);
1702 #if COLLISIONPARANOID >= 3
1703         Con_Printf("trans(%f %f %f -> %f %f %f)", start[0], start[1], start[2], starttransformed[0], starttransformed[1], starttransformed[2]);
1704 #endif
1705
1706         if (model && model->TracePoint)
1707                 model->TracePoint(model, NULL, NULL, trace, starttransformed, hitsupercontentsmask);
1708         else
1709                 Collision_ClipTrace_Point(trace, bodymins, bodymaxs, starttransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1710
1711         VectorCopy(start, trace->endpos);
1712         // transform plane
1713         // NOTE: this relies on plane.dist being directly after plane.normal
1714         Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1715 }
1716
1717 void Collision_ClipPointToWorld(trace_t *trace, dp_model_t *model, const vec3_t start, int hitsupercontents)
1718 {
1719         memset(trace, 0, sizeof(*trace));
1720         trace->fraction = trace->realfraction = 1;
1721         if (model && model->TracePoint)
1722                 model->TracePoint(model, NULL, NULL, trace, start, hitsupercontents);
1723         VectorCopy(start, trace->endpos);
1724 }
1725
1726 void Collision_CombineTraces(trace_t *cliptrace, const trace_t *trace, void *touch, qboolean isbmodel)
1727 {
1728         // take the 'best' answers from the new trace and combine with existing data
1729         if (trace->allsolid)
1730                 cliptrace->allsolid = true;
1731         if (trace->startsolid)
1732         {
1733                 if (isbmodel)
1734                         cliptrace->bmodelstartsolid = true;
1735                 cliptrace->startsolid = true;
1736                 if (cliptrace->realfraction == 1)
1737                         cliptrace->ent = touch;
1738                 if (cliptrace->startdepth > trace->startdepth)
1739                 {
1740                         cliptrace->startdepth = trace->startdepth;
1741                         VectorCopy(trace->startdepthnormal, cliptrace->startdepthnormal);
1742                 }
1743         }
1744         // don't set this except on the world, because it can easily confuse
1745         // monsters underwater if there's a bmodel involved in the trace
1746         // (inopen && inwater is how they check water visibility)
1747         //if (trace->inopen)
1748         //      cliptrace->inopen = true;
1749         if (trace->inwater)
1750                 cliptrace->inwater = true;
1751         if ((trace->realfraction <= cliptrace->realfraction) && (VectorLength2(trace->plane.normal) > 0))
1752         {
1753                 cliptrace->fraction = trace->fraction;
1754                 cliptrace->realfraction = trace->realfraction;
1755                 VectorCopy(trace->endpos, cliptrace->endpos);
1756                 cliptrace->plane = trace->plane;
1757                 cliptrace->ent = touch;
1758                 cliptrace->hitsupercontents = trace->hitsupercontents;
1759                 cliptrace->hitq3surfaceflags = trace->hitq3surfaceflags;
1760                 cliptrace->hittexture = trace->hittexture;
1761         }
1762         cliptrace->startsupercontents |= trace->startsupercontents;
1763 }
1764
1765 void Collision_ShortenTrace(trace_t *trace, float shorten_factor, const vec3_t end)
1766 {
1767         // now undo our moving end 1 qu farther...
1768         trace->fraction = bound(trace->fraction, trace->fraction / shorten_factor - 1e-6, 1); // we subtract 1e-6 to guard for roundoff errors
1769         trace->realfraction = bound(trace->realfraction, trace->realfraction / shorten_factor - 1e-6, 1); // we subtract 1e-6 to guard for roundoff errors
1770         if(trace->fraction >= 1) // trace would NOT hit if not expanded!
1771         {
1772                 trace->fraction = 1;
1773                 trace->realfraction = 1;
1774                 VectorCopy(end, trace->endpos);
1775                 memset(&trace->plane, 0, sizeof(trace->plane));
1776                 trace->ent = NULL;
1777                 trace->hitsupercontentsmask = 0;
1778                 trace->hitsupercontents = 0;
1779                 trace->hitq3surfaceflags = 0;
1780                 trace->hittexture = NULL;
1781         }
1782 }