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