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