trying to improve terrain collision brush issues in q3bsp
[divverent/darkplaces.git] / collision.c
1
2 #include "quakedef.h"
3 #include "polygon.h"
4
5 #define COLLISION_SNAPSCALE (64.0f)
6 #define COLLISION_SNAP (1.0f / COLLISION_SNAPSCALE)
7 #define COLLISION_SNAP2 (2.0f / COLLISION_SNAPSCALE)
8 #define COLLISION_PLANE_DIST_EPSILON (1.0f / 32.0f)
9
10 cvar_t collision_impactnudge = {0, "collision_impactnudge", "0.03125", "how much to back off from the impact"};
11 cvar_t collision_startnudge = {0, "collision_startnudge", "0", "how much to bias collision trace start"};
12 cvar_t collision_endnudge = {0, "collision_endnudge", "0", "how much to bias collision trace end"};
13 cvar_t collision_enternudge = {0, "collision_enternudge", "0", "how much to bias collision entry fraction"};
14 cvar_t collision_leavenudge = {0, "collision_leavenudge", "0", "how much to bias collision exit fraction"};
15
16 void Collision_Init (void)
17 {
18         Cvar_RegisterVariable(&collision_impactnudge);
19         Cvar_RegisterVariable(&collision_startnudge);
20         Cvar_RegisterVariable(&collision_endnudge);
21         Cvar_RegisterVariable(&collision_enternudge);
22         Cvar_RegisterVariable(&collision_leavenudge);
23 }
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 void Collision_PrintBrushAsQHull(colbrushf_t *brush, const char *name)
39 {
40         int i;
41         Con_Printf("3 %s\n%i\n", name, brush->numpoints);
42         for (i = 0;i < brush->numpoints;i++)
43                 Con_Printf("%f %f %f\n", brush->points[i].v[0], brush->points[i].v[1], brush->points[i].v[2]);
44         // FIXME: optimize!
45         Con_Printf("4\n%i\n", brush->numplanes);
46         for (i = 0;i < brush->numplanes;i++)
47                 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);
48 }
49
50 void Collision_ValidateBrush(colbrushf_t *brush)
51 {
52         int j, k, pointsoffplanes, pointonplanes, pointswithinsufficientplanes, printbrush;
53         float d;
54         printbrush = false;
55         if (!brush->numpoints)
56         {
57                 Con_Print("Collision_ValidateBrush: brush with no points!\n");
58                 printbrush = true;
59         }
60 #if 0
61         // it's ok for a brush to have one point and no planes...
62         if (brush->numplanes == 0 && brush->numpoints != 1)
63         {
64                 Con_Print("Collision_ValidateBrush: brush with no planes and more than one point!\n");
65                 printbrush = true;
66         }
67 #endif
68         if (brush->numplanes)
69         {
70                 pointsoffplanes = 0;
71                 pointswithinsufficientplanes = 0;
72                 for (k = 0;k < brush->numplanes;k++)
73                         if (DotProduct(brush->planes[k].normal, brush->planes[k].normal) < 0.0001f)
74                                 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);
75                 for (j = 0;j < brush->numpoints;j++)
76                 {
77                         pointonplanes = 0;
78                         for (k = 0;k < brush->numplanes;k++)
79                         {
80                                 d = DotProduct(brush->points[j].v, brush->planes[k].normal) - brush->planes[k].dist;
81                                 if (d > COLLISION_PLANE_DIST_EPSILON)
82                                 {
83                                         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);
84                                         printbrush = true;
85                                 }
86                                 if (fabs(d) > COLLISION_PLANE_DIST_EPSILON)
87                                         pointsoffplanes++;
88                                 else
89                                         pointonplanes++;
90                         }
91                         if (pointonplanes < 3)
92                                 pointswithinsufficientplanes++;
93                 }
94                 if (pointswithinsufficientplanes)
95                 {
96                         Con_Print("Collision_ValidateBrush: some points have insufficient planes, every point must be on at least 3 planes to form a corner.\n");
97                         printbrush = true;
98                 }
99                 if (pointsoffplanes == 0) // all points are on all planes
100                 {
101                         Con_Print("Collision_ValidateBrush: all points lie on all planes (degenerate, no brush volume!)\n");
102                         printbrush = true;
103                 }
104         }
105         if (printbrush)
106                 Collision_PrintBrushAsQHull(brush, "unnamed");
107 }
108
109 float nearestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
110 {
111         float dist, bestdist;
112         bestdist = DotProduct(points->v, normal);
113         points++;
114         while(--numpoints)
115         {
116                 dist = DotProduct(points->v, normal);
117                 bestdist = min(bestdist, dist);
118                 points++;
119         }
120         return bestdist;
121 }
122
123 float furthestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
124 {
125         float dist, bestdist;
126         bestdist = DotProduct(points->v, normal);
127         points++;
128         while(--numpoints)
129         {
130                 dist = DotProduct(points->v, normal);
131                 bestdist = max(bestdist, dist);
132                 points++;
133         }
134         return bestdist;
135 }
136
137
138 colbrushf_t *Collision_NewBrushFromPlanes(mempool_t *mempool, int numoriginalplanes, const colplanef_t *originalplanes, int supercontents)
139 {
140         // TODO: planesbuf could be replaced by a remapping table
141         int j, k, m, w;
142         int numpointsbuf = 0, maxpointsbuf = 256, numplanesbuf = 0, maxplanesbuf = 256, numelementsbuf = 0, maxelementsbuf = 256;
143         double maxdist;
144         colbrushf_t *brush;
145         colpointf_t pointsbuf[256];
146         colplanef_t planesbuf[256];
147         int elementsbuf[1024];
148         int polypointbuf[256];
149         int pmaxpoints = 64;
150         int pnumpoints;
151         double p[2][3*64];
152 #if 0
153         // enable these if debugging to avoid seeing garbage in unused data
154         memset(pointsbuf, 0, sizeof(pointsbuf));
155         memset(planesbuf, 0, sizeof(planesbuf));
156         memset(elementsbuf, 0, sizeof(elementsbuf));
157         memset(polypointbuf, 0, sizeof(polypointbuf));
158         memset(p, 0, sizeof(p));
159 #endif
160         // figure out how large a bounding box we need to properly compute this brush
161         maxdist = 0;
162         for (j = 0;j < numoriginalplanes;j++)
163                 maxdist = max(maxdist, originalplanes[j].dist);
164         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
165         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
166         // construct a collision brush (points, planes, and renderable mesh) from
167         // a set of planes, this also optimizes out any unnecessary planes (ones
168         // whose polygon is clipped away by the other planes)
169         for (j = 0;j < numoriginalplanes;j++)
170         {
171                 // add the plane uniquely (no duplicates)
172                 for (k = 0;k < numplanesbuf;k++)
173                         if (VectorCompare(planesbuf[k].normal, originalplanes[j].normal) && planesbuf[k].dist == originalplanes[j].dist)
174                                 break;
175                 // if the plane is a duplicate, skip it
176                 if (k < numplanesbuf)
177                         continue;
178                 // check if there are too many and skip the brush
179                 if (numplanesbuf >= maxplanesbuf)
180                 {
181                         Con_Print("Collision_NewBrushFromPlanes: failed to build collision brush: too many planes for buffer\n");
182                         return NULL;
183                 }
184
185                 // create a large polygon from the plane
186                 w = 0;
187                 PolygonD_QuadForPlane(p[w], originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist, maxdist);
188                 pnumpoints = 4;
189                 // clip it by all other planes
190                 for (k = 0;k < numoriginalplanes && pnumpoints && pnumpoints <= pmaxpoints;k++)
191                 {
192                         if (k != j)
193                         {
194                                 // we want to keep the inside of the brush plane so we flip
195                                 // the cutting plane
196                                 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);
197                                 w = !w;
198                         }
199                 }
200                 // if nothing is left, skip it
201                 if (pnumpoints < 3)
202                 {
203                         //Con_Printf("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);
204                         continue;
205                 }
206
207                 for (k = 0;k < pnumpoints;k++)
208                 {
209                         int l, m;
210                         m = 0;
211                         for (l = 0;l < numoriginalplanes;l++)
212                                 if (fabs(DotProduct(&p[w][k*3], originalplanes[l].normal) - originalplanes[l].dist) < COLLISION_PLANE_DIST_EPSILON)
213                                         m++;
214                         if (m < 3)
215                                 break;
216                 }
217                 if (k < pnumpoints)
218                 {
219                         Con_Printf("Collision_NewBrushFromPlanes: warning: polygon point does not lie on at least 3 planes\n");
220                         //return NULL;
221                 }
222
223                 // check if there are too many polygon vertices for buffer
224                 if (pnumpoints > pmaxpoints)
225                 {
226                         Con_Print("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
227                         return NULL;
228                 }
229
230                 // check if there are too many triangle elements for buffer
231                 if (numelementsbuf + (pnumpoints - 2) * 3 > maxelementsbuf)
232                 {
233                         Con_Print("Collision_NewBrushFromPlanes: failed to build collision brush: too many triangle elements for buffer\n");
234                         return NULL;
235                 }
236
237                 for (k = 0;k < pnumpoints;k++)
238                 {
239                         // check if there is already a matching point (no duplicates)
240                         for (m = 0;m < numpointsbuf;m++)
241                                 if (VectorDistance2(&p[w][k*3], pointsbuf[m].v) < COLLISION_SNAP2)
242                                         break;
243
244                         // if there is no match, add a new one
245                         if (m == numpointsbuf)
246                         {
247                                 // check if there are too many and skip the brush
248                                 if (numpointsbuf >= maxpointsbuf)
249                                 {
250                                         Con_Print("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
251                                         return NULL;
252                                 }
253                                 // add the new one
254                                 VectorCopy(&p[w][k*3], pointsbuf[numpointsbuf].v);
255                                 numpointsbuf++;
256                         }
257
258                         // store the index into a buffer
259                         polypointbuf[k] = m;
260                 }
261
262                 // add the triangles for the polygon
263                 // (this particular code makes a triangle fan)
264                 for (k = 0;k < pnumpoints - 2;k++)
265                 {
266                         elementsbuf[numelementsbuf++] = polypointbuf[0];
267                         elementsbuf[numelementsbuf++] = polypointbuf[k + 1];
268                         elementsbuf[numelementsbuf++] = polypointbuf[k + 2];
269                 }
270
271                 // add the new plane
272                 VectorCopy(originalplanes[j].normal, planesbuf[numplanesbuf].normal);
273                 planesbuf[numplanesbuf].dist = originalplanes[j].dist;
274                 planesbuf[numplanesbuf].q3surfaceflags = originalplanes[j].q3surfaceflags;
275                 planesbuf[numplanesbuf].texture = originalplanes[j].texture;
276                 numplanesbuf++;
277         }
278
279         // validate plane distances
280         for (j = 0;j < numplanesbuf;j++)
281         {
282                 float d = furthestplanedist_float(planesbuf[j].normal, pointsbuf, numpointsbuf);
283                 if (fabs(planesbuf[j].dist - d) > COLLISION_PLANE_DIST_EPSILON)
284                         Con_Printf("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);
285         }
286
287         // if nothing is left, there's nothing to allocate
288         if (numelementsbuf < 12 || numplanesbuf < 4 || numpointsbuf < 4)
289         {
290                 Con_Printf("Collision_NewBrushFromPlanes: failed to build collision brush: %i triangles, %i planes (input was %i planes), %i vertices\n", numelementsbuf / 3, numplanesbuf, numoriginalplanes, numpointsbuf);
291                 return NULL;
292         }
293
294         // allocate the brush and copy to it
295         brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colpointf_t) * numpointsbuf + sizeof(colplanef_t) * numplanesbuf + sizeof(int) * numelementsbuf);
296         brush->supercontents = supercontents;
297         brush->numplanes = numplanesbuf;
298         brush->numpoints = numpointsbuf;
299         brush->numtriangles = numelementsbuf / 3;
300         brush->planes = (colplanef_t *)(brush + 1);
301         brush->points = (colpointf_t *)(brush->planes + brush->numplanes);
302         brush->elements = (int *)(brush->points + brush->numpoints);
303         for (j = 0;j < brush->numpoints;j++)
304         {
305                 brush->points[j].v[0] = pointsbuf[j].v[0];
306                 brush->points[j].v[1] = pointsbuf[j].v[1];
307                 brush->points[j].v[2] = pointsbuf[j].v[2];
308         }
309         for (j = 0;j < brush->numplanes;j++)
310         {
311                 brush->planes[j].normal[0] = planesbuf[j].normal[0];
312                 brush->planes[j].normal[1] = planesbuf[j].normal[1];
313                 brush->planes[j].normal[2] = planesbuf[j].normal[2];
314                 brush->planes[j].dist = planesbuf[j].dist;
315                 brush->planes[j].q3surfaceflags = planesbuf[j].q3surfaceflags;
316                 brush->planes[j].texture = planesbuf[j].texture;
317         }
318         for (j = 0;j < brush->numtriangles * 3;j++)
319                 brush->elements[j] = elementsbuf[j];
320         VectorCopy(brush->points[0].v, brush->mins);
321         VectorCopy(brush->points[0].v, brush->maxs);
322         for (j = 1;j < brush->numpoints;j++)
323         {
324                 brush->mins[0] = min(brush->mins[0], brush->points[j].v[0]);
325                 brush->mins[1] = min(brush->mins[1], brush->points[j].v[1]);
326                 brush->mins[2] = min(brush->mins[2], brush->points[j].v[2]);
327                 brush->maxs[0] = max(brush->maxs[0], brush->points[j].v[0]);
328                 brush->maxs[1] = max(brush->maxs[1], brush->points[j].v[1]);
329                 brush->maxs[2] = max(brush->maxs[2], brush->points[j].v[2]);
330         }
331         brush->mins[0] -= 1;
332         brush->mins[1] -= 1;
333         brush->mins[2] -= 1;
334         brush->maxs[0] += 1;
335         brush->maxs[1] += 1;
336         brush->maxs[2] += 1;
337         Collision_ValidateBrush(brush);
338         return brush;
339 }
340
341
342
343 void Collision_CalcPlanesForPolygonBrushFloat(colbrushf_t *brush)
344 {
345         int i;
346         float edge0[3], edge1[3], edge2[3], normal[3], dist, bestdist;
347         colpointf_t *p, *p2;
348
349         // FIXME: these probably don't actually need to be normalized if the collision code does not care
350         if (brush->numpoints == 3)
351         {
352                 // optimized triangle case
353                 TriangleNormal(brush->points[0].v, brush->points[1].v, brush->points[2].v, brush->planes[0].normal);
354                 if (DotProduct(brush->planes[0].normal, brush->planes[0].normal) < 0.0001f)
355                 {
356                         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
357                         brush->numplanes = 0;
358                         return;
359                 }
360                 else
361                 {
362                         brush->numplanes = 5;
363                         VectorNormalize(brush->planes[0].normal);
364                         brush->planes[0].dist = DotProduct(brush->points->v, brush->planes[0].normal);
365                         VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
366                         brush->planes[1].dist = -brush->planes[0].dist;
367                         VectorSubtract(brush->points[2].v, brush->points[0].v, edge0);
368                         VectorSubtract(brush->points[0].v, brush->points[1].v, edge1);
369                         VectorSubtract(brush->points[1].v, brush->points[2].v, edge2);
370 #if 1
371                         {
372                                 float projectionnormal[3], projectionedge0[3], projectionedge1[3], projectionedge2[3];
373                                 int i, best;
374                                 float dist, bestdist;
375                                 bestdist = fabs(brush->planes[0].normal[0]);
376                                 best = 0;
377                                 for (i = 1;i < 3;i++)
378                                 {
379                                         dist = fabs(brush->planes[0].normal[i]);
380                                         if (bestdist < dist)
381                                         {
382                                                 bestdist = dist;
383                                                 best = i;
384                                         }
385                                 }
386                                 VectorClear(projectionnormal);
387                                 if (brush->planes[0].normal[best] < 0)
388                                         projectionnormal[best] = -1;
389                                 else
390                                         projectionnormal[best] = 1;
391                                 VectorCopy(edge0, projectionedge0);
392                                 VectorCopy(edge1, projectionedge1);
393                                 VectorCopy(edge2, projectionedge2);
394                                 projectionedge0[best] = 0;
395                                 projectionedge1[best] = 0;
396                                 projectionedge2[best] = 0;
397                                 CrossProduct(projectionedge0, projectionnormal, brush->planes[2].normal);
398                                 CrossProduct(projectionedge1, projectionnormal, brush->planes[3].normal);
399                                 CrossProduct(projectionedge2, projectionnormal, brush->planes[4].normal);
400                         }
401 #else
402                         CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
403                         CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
404                         CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
405 #endif
406                         VectorNormalize(brush->planes[2].normal);
407                         VectorNormalize(brush->planes[3].normal);
408                         VectorNormalize(brush->planes[4].normal);
409                         brush->planes[2].dist = DotProduct(brush->points[2].v, brush->planes[2].normal);
410                         brush->planes[3].dist = DotProduct(brush->points[0].v, brush->planes[3].normal);
411                         brush->planes[4].dist = DotProduct(brush->points[1].v, brush->planes[4].normal);
412
413                         if (developer.integer >= 100)
414                         {
415                                 // validation code
416 #if 0
417                                 float temp[3];
418
419                                 VectorSubtract(brush->points[0].v, brush->points[1].v, edge0);
420                                 VectorSubtract(brush->points[2].v, brush->points[1].v, edge1);
421                                 CrossProduct(edge0, edge1, normal);
422                                 VectorNormalize(normal);
423                                 VectorSubtract(normal, brush->planes[0].normal, temp);
424                                 if (VectorLength(temp) > 0.01f)
425                                         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]);
426                                 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)
427                                         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);
428 #if 0
429                                 if (fabs(DotProduct(brush->planes[2].normal, brush->planes[0].normal)) > 0.01f)
430                                         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);
431                                 if (fabs(DotProduct(brush->planes[3].normal, brush->planes[0].normal)) > 0.01f)
432                                         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);
433                                 if (fabs(DotProduct(brush->planes[4].normal, brush->planes[0].normal)) > 0.01f)
434                                         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);
435                                 if (fabs(DotProduct(brush->planes[2].normal, edge0)) > 0.01f)
436                                         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]);
437                                 if (fabs(DotProduct(brush->planes[3].normal, edge1)) > 0.01f)
438                                         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]);
439                                 if (fabs(DotProduct(brush->planes[4].normal, edge2)) > 0.01f)
440                                         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]);
441 #endif
442 #endif
443                                 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)
444                                         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);
445                                 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)
446                                         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);
447                                 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)
448                                         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);
449                                 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)
450                                         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);
451                                 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)
452                                         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);
453                         }
454                 }
455         }
456         else
457         {
458                 // choose best surface normal for polygon's plane
459                 bestdist = 0;
460                 for (i = 0, p = brush->points + 1;i < brush->numpoints - 2;i++, p++)
461                 {
462                         VectorSubtract(p[-1].v, p[0].v, edge0);
463                         VectorSubtract(p[1].v, p[0].v, edge1);
464                         CrossProduct(edge0, edge1, normal);
465                         //TriangleNormal(p[-1].v, p[0].v, p[1].v, normal);
466                         dist = DotProduct(normal, normal);
467                         if (i == 0 || bestdist < dist)
468                         {
469                                 bestdist = dist;
470                                 VectorCopy(normal, brush->planes->normal);
471                         }
472                 }
473                 if (bestdist < 0.0001f)
474                 {
475                         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
476                         brush->numplanes = 0;
477                         return;
478                 }
479                 else
480                 {
481                         brush->numplanes = brush->numpoints + 2;
482                         VectorNormalize(brush->planes->normal);
483                         brush->planes->dist = DotProduct(brush->points->v, brush->planes->normal);
484
485                         // negate plane to create other side
486                         VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
487                         brush->planes[1].dist = -brush->planes[0].dist;
488                         for (i = 0, p = brush->points + (brush->numpoints - 1), p2 = brush->points;i < brush->numpoints;i++, p = p2, p2++)
489                         {
490                                 VectorSubtract(p->v, p2->v, edge0);
491                                 CrossProduct(edge0, brush->planes->normal, brush->planes[i + 2].normal);
492                                 VectorNormalize(brush->planes[i + 2].normal);
493                                 brush->planes[i + 2].dist = DotProduct(p->v, brush->planes[i + 2].normal);
494                         }
495                 }
496         }
497
498         if (developer.integer >= 100)
499         {
500                 // validity check - will be disabled later
501                 Collision_ValidateBrush(brush);
502                 for (i = 0;i < brush->numplanes;i++)
503                 {
504                         int j;
505                         for (j = 0, p = brush->points;j < brush->numpoints;j++, p++)
506                                 if (DotProduct(p->v, brush->planes[i].normal) > brush->planes[i].dist + COLLISION_PLANE_DIST_EPSILON)
507                                         Con_Printf("Error in brush plane generation, plane %i\n", i);
508                 }
509         }
510 }
511
512 colbrushf_t *Collision_AllocBrushFromPermanentPolygonFloat(mempool_t *mempool, int numpoints, float *points, int supercontents)
513 {
514         colbrushf_t *brush;
515         brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colplanef_t) * (numpoints + 2));
516         brush->supercontents = supercontents;
517         brush->numpoints = numpoints;
518         brush->numplanes = numpoints + 2;
519         brush->planes = (colplanef_t *)(brush + 1);
520         brush->points = (colpointf_t *)points;
521         Sys_Error("Collision_AllocBrushFromPermanentPolygonFloat: FIXME: this code needs to be updated to generate a mesh...");
522         return brush;
523 }
524
525 // NOTE: start and end of each brush pair must have same numplanes/numpoints
526 void Collision_TraceBrushBrushFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, const colbrushf_t *thatbrush_start, const colbrushf_t *thatbrush_end)
527 {
528         int nplane, nplane2, fstartsolid = true, fendsolid = true, brushsolid, hitq3surfaceflags = 0;
529         float enterfrac = -1, leavefrac = 1, d1, d2, f, imove, newimpactnormal[3], enterfrac2 = -1;
530         const colplanef_t *startplane, *endplane;
531         texture_t *hittexture = NULL;
532
533         VectorClear(newimpactnormal);
534
535         for (nplane = 0;nplane < thatbrush_start->numplanes + thisbrush_start->numplanes;nplane++)
536         {
537                 nplane2 = nplane;
538                 if (nplane2 >= thatbrush_start->numplanes)
539                 {
540                         nplane2 -= thatbrush_start->numplanes;
541                         startplane = thisbrush_start->planes + nplane2;
542                         endplane = thisbrush_end->planes + nplane2;
543                         if (developer.integer >= 100)
544                         {
545                                 // any brush with degenerate planes is not worth handling
546                                 if (DotProduct(startplane->normal, startplane->normal) < 0.9f || DotProduct(endplane->normal, endplane->normal) < 0.9f)
547                                 {
548                                         Con_Print("Collision_TraceBrushBrushFloat: degenerate thisbrush plane!\n");
549                                         return;
550                                 }
551                                 f = furthestplanedist_float(startplane->normal, thisbrush_start->points, thisbrush_start->numpoints);
552                                 if (fabs(f - startplane->dist) > COLLISION_PLANE_DIST_EPSILON)
553                                         Con_Printf("startplane->dist %f != calculated %f (thisbrush_start)\n", startplane->dist, f);
554                         }
555                         d1 = nearestplanedist_float(startplane->normal, thisbrush_start->points, thisbrush_start->numpoints) - furthestplanedist_float(startplane->normal, thatbrush_start->points, thatbrush_start->numpoints) - collision_startnudge.value;
556                         d2 = nearestplanedist_float(endplane->normal, thisbrush_end->points, thisbrush_end->numpoints) - furthestplanedist_float(endplane->normal, thatbrush_end->points, thatbrush_end->numpoints) - collision_endnudge.value;
557                 }
558                 else
559                 {
560                         startplane = thatbrush_start->planes + nplane2;
561                         endplane = thatbrush_end->planes + nplane2;
562                         if (developer.integer >= 100)
563                         {
564                                 // any brush with degenerate planes is not worth handling
565                                 if (DotProduct(startplane->normal, startplane->normal) < 0.9f || DotProduct(endplane->normal, endplane->normal) < 0.9f)
566                                 {
567                                         Con_Print("Collision_TraceBrushBrushFloat: degenerate thatbrush plane!\n");
568                                         return;
569                                 }
570                                 f = furthestplanedist_float(startplane->normal, thatbrush_start->points, thatbrush_start->numpoints);
571                                 if (fabs(f - startplane->dist) > COLLISION_PLANE_DIST_EPSILON)
572                                         Con_Printf("startplane->dist %f != calculated %f (thatbrush_start)\n", startplane->dist, f);
573                         }
574                         d1 = nearestplanedist_float(startplane->normal, thisbrush_start->points, thisbrush_start->numpoints) - startplane->dist - collision_startnudge.value;
575                         d2 = nearestplanedist_float(endplane->normal, thisbrush_end->points, thisbrush_end->numpoints) - endplane->dist - collision_endnudge.value;
576                 }
577                 //Con_Printf("%c%i: d1 = %f, d2 = %f, d1 / (d1 - d2) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, d1, d2, d1 / (d1 - d2));
578
579                 if(d1 > d2)
580                 {
581                         // moving into brush
582                         if(d2 > 0)
583                                 return;
584                         if(d1 > 0)
585                         {
586                                 // enter
587                                 fstartsolid = false;
588                                 imove = 1 / (d1 - d2);
589                                 f = (d1 - collision_enternudge.value) * imove;
590                                 if (enterfrac < f)
591                                 {
592                                         enterfrac = f;
593                                         enterfrac2 = f - collision_impactnudge.value * imove;
594                                         VectorLerp(startplane->normal, enterfrac, endplane->normal, newimpactnormal);
595                                         hitq3surfaceflags = startplane->q3surfaceflags;
596                                         hittexture = startplane->texture;
597                                 }
598                         }
599                 }
600                 else
601                 {
602                         // moving out of brush
603                         if(d1 > 0)
604                                 return;
605                         if(d2 > 0)
606                         {
607                                 // leave
608                                 fendsolid = false;
609                                 f = (d1 + collision_leavenudge.value) / (d1 - d2);
610                                 if (leavefrac > f)
611                                         leavefrac = f;
612                         }
613                 }
614         }
615
616         brushsolid = trace->hitsupercontentsmask & thatbrush_start->supercontents;
617         if (fstartsolid)
618         {
619                 trace->startsupercontents |= thatbrush_start->supercontents;
620                 if (brushsolid)
621                 {
622                         trace->startsolid = true;
623                         if (fendsolid)
624                                 trace->allsolid = true;
625                 }
626         }
627
628         // LordHavoc: we need an epsilon nudge here because for a point trace the
629         // penetrating line segment is normally zero length if this brush was
630         // generated from a polygon (infinitely thin), and could even be slightly
631         // positive or negative due to rounding errors in that case.
632         if (brushsolid && enterfrac > -1 && enterfrac < trace->realfraction && enterfrac - (1.0f / 1024.0f) <= leavefrac)
633         {
634 #if 0
635                 // broken
636                 if (thatbrush_start->ispolygon)
637                 {
638                         d1 = nearestplanedist_float(thatbrush_start->planes[0].normal, thisbrush_start->points, thisbrush_start->numpoints) - thatbrush_start->planes[0].dist - collision_startnudge.value;
639                         d2 = nearestplanedist_float(thatbrush_end->planes[0].normal, thisbrush_end->points, thisbrush_end->numpoints) - thatbrush_end->planes[0].dist - collision_endnudge.value;
640                         move = d1 - d2;
641                         if (move <= 0 || d2 > collision_enternudge.value || d1 < 0)
642                                 return;
643                         // enter
644                         imove = 1 / move;
645                         enterfrac = (d1 - collision_enternudge.value) * imove;
646                         if (enterfrac < trace->realfraction)
647                         {
648                                 enterfrac2 = enterfrac - collision_impactnudge.value * imove;
649                                 trace->hitsupercontents = thatbrush_start->supercontents;
650                                 trace->hitq3surfaceflags = thatbrush_start->planes[0].q3surfaceflags;
651                                 trace->hittexture = thatbrush_start->planes[0].texture;
652                                 trace->realfraction = bound(0, enterfrac, 1);
653                                 trace->fraction = bound(0, enterfrac2, 1);
654                                 VectorLerp(thatbrush_start->planes[0].normal, enterfrac, thatbrush_end->planes[0].normal, trace->plane.normal);
655                         }
656                 }
657                 else
658 #endif
659                 {
660                         trace->hitsupercontents = thatbrush_start->supercontents;
661                         trace->hitq3surfaceflags = hitq3surfaceflags;
662                         trace->hittexture = hittexture;
663                         trace->realfraction = bound(0, enterfrac, 1);
664                         trace->fraction = bound(0, enterfrac2, 1);
665                         VectorCopy(newimpactnormal, trace->plane.normal);
666                 }
667         }
668 }
669
670 // NOTE: start and end brush pair must have same numplanes/numpoints
671 void Collision_TraceLineBrushFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const colbrushf_t *thatbrush_start, const colbrushf_t *thatbrush_end)
672 {
673         int nplane, fstartsolid = true, fendsolid = true, brushsolid, hitq3surfaceflags = 0;
674         float enterfrac = -1, leavefrac = 1, d1, d2, f, imove, newimpactnormal[3], enterfrac2 = -1;
675         const colplanef_t *startplane, *endplane;
676         texture_t *hittexture = NULL;
677
678         VectorClear(newimpactnormal);
679
680         for (nplane = 0;nplane < thatbrush_start->numplanes;nplane++)
681         {
682                 startplane = thatbrush_start->planes + nplane;
683                 endplane = thatbrush_end->planes + nplane;
684                 d1 = DotProduct(startplane->normal, linestart) - startplane->dist - collision_startnudge.value;
685                 d2 = DotProduct(endplane->normal, lineend) - endplane->dist - collision_endnudge.value;
686                 if (developer.integer >= 100)
687                 {
688                         // any brush with degenerate planes is not worth handling
689                         if (DotProduct(startplane->normal, startplane->normal) < 0.9f || DotProduct(endplane->normal, endplane->normal) < 0.9f)
690                         {
691                                 Con_Print("Collision_TraceLineBrushFloat: degenerate plane!\n");
692                                 return;
693                         }
694                         if (thatbrush_start->numpoints)
695                         {
696                                 f = furthestplanedist_float(startplane->normal, thatbrush_start->points, thatbrush_start->numpoints);
697                                 if (fabs(f - startplane->dist) > COLLISION_PLANE_DIST_EPSILON)
698                                         Con_Printf("startplane->dist %f != calculated %f\n", startplane->dist, f);
699                         }
700                 }
701
702                 if (d1 > d2)
703                 {
704                         // moving into brush
705                         if (d2 > 0)
706                                 return;
707                         if (d1 > 0)
708                         {
709                                 // enter
710                                 fstartsolid = false;
711                                 imove = 1 / (d1 - d2);
712                                 f = (d1 - collision_enternudge.value) * imove;
713                                 if (enterfrac < f)
714                                 {
715                                         enterfrac = f;
716                                         enterfrac2 = f - collision_impactnudge.value * imove;
717                                         VectorLerp(startplane->normal, enterfrac, endplane->normal, newimpactnormal);
718                                         hitq3surfaceflags = startplane->q3surfaceflags;
719                                         hittexture = startplane->texture;
720                                 }
721                         }
722                 }
723                 else
724                 {
725                         // moving out of brush
726                         if (d1 > 0)
727                                 return;
728                         if (d2 > 0)
729                         {
730                                 // leave
731                                 fendsolid = false;
732                                 f = (d1 + collision_leavenudge.value) / (d1 - d2);
733                                 if (leavefrac > f)
734                                         leavefrac = f;
735                         }
736                 }
737         }
738
739         brushsolid = trace->hitsupercontentsmask & thatbrush_start->supercontents;
740         if (fstartsolid)
741         {
742                 trace->startsupercontents |= thatbrush_start->supercontents;
743                 if (brushsolid)
744                 {
745                         trace->startsolid = true;
746                         if (fendsolid)
747                                 trace->allsolid = true;
748                 }
749         }
750
751         // LordHavoc: we need an epsilon nudge here because for a point trace the
752         // penetrating line segment is normally zero length if this brush was
753         // generated from a polygon (infinitely thin), and could even be slightly
754         // positive or negative due to rounding errors in that case.
755         if (brushsolid && enterfrac > -1 && enterfrac < trace->realfraction && enterfrac <= leavefrac)
756         {
757 #if 0
758                 // broken
759                 if (thatbrush_start->ispolygon)
760                 {
761                         d1 = DotProduct(thatbrush_start->planes[0].normal, linestart) - thatbrush_start->planes[0].dist - collision_startnudge.value;
762                         d2 = DotProduct(thatbrush_end->planes[0].normal, lineend) - thatbrush_end->planes[0].dist - collision_endnudge.value;
763                         move = d1 - d2;
764                         if (move <= 0 || d2 > collision_enternudge.value || d1 < 0)
765                                 return;
766                         // enter
767                         imove = 1 / move;
768                         enterfrac = (d1 - collision_enternudge.value) * imove;
769                         if (enterfrac < trace->realfraction)
770                         {
771                                 enterfrac2 = enterfrac - collision_impactnudge.value * imove;
772                                 trace->hitsupercontents = thatbrush_start->supercontents;
773                                 trace->hitq3surfaceflags = hitq3surfaceflags;
774                                 trace->hittexture = hittexture;
775                                 trace->realfraction = bound(0, enterfrac, 1);
776                                 trace->fraction = bound(0, enterfrac2, 1);
777                                 VectorLerp(thatbrush_start->planes[0].normal, enterfrac, thatbrush_end->planes[0].normal, trace->plane.normal);
778                         }
779                 }
780                 else
781 #endif
782                 {
783                         trace->hitsupercontents = thatbrush_start->supercontents;
784                         trace->hitq3surfaceflags = hitq3surfaceflags;
785                         trace->hittexture = hittexture;
786                         trace->realfraction = bound(0, enterfrac, 1);
787                         trace->fraction = bound(0, enterfrac2, 1);
788                         VectorCopy(newimpactnormal, trace->plane.normal);
789                 }
790         }
791 }
792
793 void Collision_TracePointBrushFloat(trace_t *trace, const vec3_t point, const colbrushf_t *thatbrush)
794 {
795         int nplane;
796         const colplanef_t *plane;
797
798         for (nplane = 0, plane = thatbrush->planes;nplane < thatbrush->numplanes;nplane++, plane++)
799                 if (DotProduct(plane->normal, point) > plane->dist)
800                         return;
801
802         trace->startsupercontents |= thatbrush->supercontents;
803         if (trace->hitsupercontentsmask & thatbrush->supercontents)
804         {
805                 trace->startsolid = true;
806                 trace->allsolid = true;
807         }
808 }
809
810 static colpointf_t polyf_points[256];
811 static colplanef_t polyf_planes[256 + 2];
812 static colbrushf_t polyf_brush;
813
814 void Collision_SnapCopyPoints(int numpoints, const colpointf_t *in, colpointf_t *out, float fractionprecision, float invfractionprecision)
815 {
816         while (numpoints--)
817         {
818                 out->v[0] = floor(in->v[0] * fractionprecision + 0.5f) * invfractionprecision;
819                 out->v[1] = floor(in->v[1] * fractionprecision + 0.5f) * invfractionprecision;
820                 out->v[2] = floor(in->v[2] * fractionprecision + 0.5f) * invfractionprecision;
821         }
822 }
823
824 void Collision_TraceBrushPolygonFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int numpoints, const float *points, int supercontents)
825 {
826         if (numpoints > 256)
827         {
828                 Con_Print("Polygon with more than 256 points not supported yet (fixme!)\n");
829                 return;
830         }
831         polyf_brush.numpoints = numpoints;
832         polyf_brush.numplanes = numpoints + 2;
833         //polyf_brush.points = (colpointf_t *)points;
834         polyf_brush.planes = polyf_planes;
835         polyf_brush.supercontents = supercontents;
836         polyf_brush.points = polyf_points;
837         Collision_SnapCopyPoints(numpoints, (colpointf_t *)points, polyf_points, COLLISION_SNAPSCALE, COLLISION_SNAP);
838         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
839         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
840         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &polyf_brush, &polyf_brush);
841 }
842
843 void Collision_TraceBrushTriangleMeshFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int numtriangles, const int *element3i, const float *vertex3f, int supercontents, int q3surfaceflags, texture_t *texture, const vec3_t segmentmins, const vec3_t segmentmaxs)
844 {
845         int i;
846         float facemins[3], facemaxs[3];
847         polyf_brush.numpoints = 3;
848         polyf_brush.numplanes = 5;
849         polyf_brush.points = polyf_points;
850         polyf_brush.planes = polyf_planes;
851         polyf_brush.supercontents = supercontents;
852         for (i = 0;i < polyf_brush.numplanes;i++)
853         {
854                 polyf_brush.planes[i].q3surfaceflags = q3surfaceflags;
855                 polyf_brush.planes[i].texture = texture;
856         }
857         for (i = 0;i < numtriangles;i++, element3i += 3)
858         {
859                 VectorCopy(vertex3f + element3i[0] * 3, polyf_points[0].v);
860                 VectorCopy(vertex3f + element3i[1] * 3, polyf_points[1].v);
861                 VectorCopy(vertex3f + element3i[2] * 3, polyf_points[2].v);
862                 Collision_SnapCopyPoints(3, polyf_points, polyf_points, COLLISION_SNAPSCALE, COLLISION_SNAP);
863                 facemins[0] = min(polyf_points[0].v[0], min(polyf_points[1].v[0], polyf_points[2].v[0]));
864                 facemins[1] = min(polyf_points[0].v[1], min(polyf_points[1].v[1], polyf_points[2].v[1]));
865                 facemins[2] = min(polyf_points[0].v[2], min(polyf_points[1].v[2], polyf_points[2].v[2]));
866                 facemaxs[0] = max(polyf_points[0].v[0], max(polyf_points[1].v[0], polyf_points[2].v[0]));
867                 facemaxs[1] = max(polyf_points[0].v[1], max(polyf_points[1].v[1], polyf_points[2].v[1]));
868                 facemaxs[2] = max(polyf_points[0].v[2], max(polyf_points[1].v[2], polyf_points[2].v[2]));
869                 if (BoxesOverlap(segmentmins, segmentmaxs, facemins, facemaxs))
870                 {
871                         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
872                         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
873                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &polyf_brush, &polyf_brush);
874                 }
875         }
876 }
877
878 void Collision_TraceLinePolygonFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, int numpoints, const float *points, int supercontents)
879 {
880         if (numpoints > 256)
881         {
882                 Con_Print("Polygon with more than 256 points not supported yet (fixme!)\n");
883                 return;
884         }
885         polyf_brush.numpoints = numpoints;
886         polyf_brush.numplanes = numpoints + 2;
887         //polyf_brush.points = (colpointf_t *)points;
888         polyf_brush.points = polyf_points;
889         Collision_SnapCopyPoints(numpoints, (colpointf_t *)points, polyf_points, COLLISION_SNAPSCALE, COLLISION_SNAP);
890         polyf_brush.planes = polyf_planes;
891         polyf_brush.supercontents = supercontents;
892         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
893         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
894         Collision_TraceLineBrushFloat(trace, linestart, lineend, &polyf_brush, &polyf_brush);
895 }
896
897 void Collision_TraceLineTriangleMeshFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, int numtriangles, const int *element3i, const float *vertex3f, int supercontents, int q3surfaceflags, texture_t *texture, const vec3_t segmentmins, const vec3_t segmentmaxs)
898 {
899         int i;
900 #if 1
901         // FIXME: snap vertices?
902         for (i = 0;i < numtriangles;i++, element3i += 3)
903                 Collision_TraceLineTriangleFloat(trace, linestart, lineend, vertex3f + element3i[0] * 3, vertex3f + element3i[1] * 3, vertex3f + element3i[2] * 3, supercontents, q3surfaceflags, texture);
904 #else
905         polyf_brush.numpoints = 3;
906         polyf_brush.numplanes = 5;
907         polyf_brush.points = polyf_points;
908         polyf_brush.planes = polyf_planes;
909         polyf_brush.supercontents = supercontents;
910         for (i = 0;i < polyf_brush.numplanes;i++)
911         {
912                 polyf_brush.planes[i].supercontents = supercontents;
913                 polyf_brush.planes[i].q3surfaceflags = q3surfaceflags;
914                 polyf_brush.planes[i].texture = texture;
915         }
916         for (i = 0;i < numtriangles;i++, element3i += 3)
917         {
918                 float facemins[3], facemaxs[3];
919                 VectorCopy(vertex3f + element3i[0] * 3, polyf_points[0].v);
920                 VectorCopy(vertex3f + element3i[1] * 3, polyf_points[1].v);
921                 VectorCopy(vertex3f + element3i[2] * 3, polyf_points[2].v);
922                 Collision_SnapCopyPoints(numpoints, polyf_points, polyf_points, COLLISION_SNAPSCALE, COLLISION_SNAP);
923                 facemins[0] = min(polyf_points[0].v[0], min(polyf_points[1].v[0], polyf_points[2].v[0]));
924                 facemins[1] = min(polyf_points[0].v[1], min(polyf_points[1].v[1], polyf_points[2].v[1]));
925                 facemins[2] = min(polyf_points[0].v[2], min(polyf_points[1].v[2], polyf_points[2].v[2]));
926                 facemaxs[0] = max(polyf_points[0].v[0], max(polyf_points[1].v[0], polyf_points[2].v[0]));
927                 facemaxs[1] = max(polyf_points[0].v[1], max(polyf_points[1].v[1], polyf_points[2].v[1]));
928                 facemaxs[2] = max(polyf_points[0].v[2], max(polyf_points[1].v[2], polyf_points[2].v[2]));
929                 if (BoxesOverlap(segmentmins, segmentmaxs, facemins, facemaxs))
930                 {
931                         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brush);
932                         //Collision_PrintBrushAsQHull(&polyf_brush, "polyf_brush");
933                         Collision_TraceLineBrushFloat(trace, linestart, lineend, &polyf_brush, &polyf_brush);
934                 }
935         }
936 #endif
937 }
938
939
940 static colpointf_t polyf_pointsstart[256], polyf_pointsend[256];
941 static colplanef_t polyf_planesstart[256 + 2], polyf_planesend[256 + 2];
942 static colbrushf_t polyf_brushstart, polyf_brushend;
943
944 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)
945 {
946         int i;
947         if (numpoints > 256)
948         {
949                 Con_Print("Polygon with more than 256 points not supported yet (fixme!)\n");
950                 return;
951         }
952         polyf_brushstart.numpoints = numpoints;
953         polyf_brushstart.numplanes = numpoints + 2;
954         polyf_brushstart.points = polyf_pointsstart;//(colpointf_t *)points;
955         polyf_brushstart.planes = polyf_planesstart;
956         polyf_brushstart.supercontents = supercontents;
957         for (i = 0;i < numpoints;i++)
958                 Matrix4x4_Transform(polygonmatrixstart, points + i * 3, polyf_brushstart.points[i].v);
959         polyf_brushend.numpoints = numpoints;
960         polyf_brushend.numplanes = numpoints + 2;
961         polyf_brushend.points = polyf_pointsend;//(colpointf_t *)points;
962         polyf_brushend.planes = polyf_planesend;
963         polyf_brushend.supercontents = supercontents;
964         for (i = 0;i < numpoints;i++)
965                 Matrix4x4_Transform(polygonmatrixend, points + i * 3, polyf_brushend.points[i].v);
966         for (i = 0;i < polyf_brushstart.numplanes;i++)
967         {
968                 polyf_brushstart.planes[i].q3surfaceflags = q3surfaceflags;
969                 polyf_brushstart.planes[i].texture = texture;
970         }
971         Collision_SnapCopyPoints(numpoints, polyf_pointsstart, polyf_pointsstart, COLLISION_SNAPSCALE, COLLISION_SNAP);
972         Collision_SnapCopyPoints(numpoints, polyf_pointsend, polyf_pointsend, COLLISION_SNAPSCALE, COLLISION_SNAP);
973         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brushstart);
974         Collision_CalcPlanesForPolygonBrushFloat(&polyf_brushend);
975
976         //Collision_PrintBrushAsQHull(&polyf_brushstart, "polyf_brushstart");
977         //Collision_PrintBrushAsQHull(&polyf_brushend, "polyf_brushend");
978
979         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &polyf_brushstart, &polyf_brushend);
980 }
981
982
983
984 #define MAX_BRUSHFORBOX 16
985 static int brushforbox_index = 0;
986 static colpointf_t brushforbox_point[MAX_BRUSHFORBOX*8];
987 static colplanef_t brushforbox_plane[MAX_BRUSHFORBOX*6];
988 static colbrushf_t brushforbox_brush[MAX_BRUSHFORBOX];
989 static colbrushf_t brushforpoint_brush[MAX_BRUSHFORBOX];
990
991 void Collision_InitBrushForBox(void)
992 {
993         int i;
994         for (i = 0;i < MAX_BRUSHFORBOX;i++)
995         {
996                 brushforbox_brush[i].numpoints = 8;
997                 brushforbox_brush[i].numplanes = 6;
998                 brushforbox_brush[i].points = brushforbox_point + i * 8;
999                 brushforbox_brush[i].planes = brushforbox_plane + i * 6;
1000                 brushforpoint_brush[i].numpoints = 1;
1001                 brushforpoint_brush[i].numplanes = 0;
1002                 brushforpoint_brush[i].points = brushforbox_point + i * 8;
1003                 brushforpoint_brush[i].planes = brushforbox_plane + i * 6;
1004         }
1005 }
1006
1007 colbrushf_t *Collision_BrushForBox(const matrix4x4_t *matrix, const vec3_t mins, const vec3_t maxs, int supercontents, int q3surfaceflags, texture_t *texture)
1008 {
1009         int i, j;
1010         vec3_t v;
1011         colbrushf_t *brush;
1012         if (brushforbox_brush[0].numpoints == 0)
1013                 Collision_InitBrushForBox();
1014         // FIXME: these probably don't actually need to be normalized if the collision code does not care
1015         if (VectorCompare(mins, maxs))
1016         {
1017                 // point brush
1018                 brush = brushforpoint_brush + ((brushforbox_index++) % MAX_BRUSHFORBOX);
1019                 VectorCopy(mins, brush->points->v);
1020         }
1021         else
1022         {
1023                 brush = brushforbox_brush + ((brushforbox_index++) % MAX_BRUSHFORBOX);
1024                 // FIXME: optimize
1025                 for (i = 0;i < 8;i++)
1026                 {
1027                         v[0] = i & 1 ? maxs[0] : mins[0];
1028                         v[1] = i & 2 ? maxs[1] : mins[1];
1029                         v[2] = i & 4 ? maxs[2] : mins[2];
1030                         Matrix4x4_Transform(matrix, v, brush->points[i].v);
1031                 }
1032                 // FIXME: optimize!
1033                 for (i = 0;i < 6;i++)
1034                 {
1035                         VectorClear(v);
1036                         v[i >> 1] = i & 1 ? 1 : -1;
1037                         Matrix4x4_Transform3x3(matrix, v, brush->planes[i].normal);
1038                         VectorNormalize(brush->planes[i].normal);
1039                 }
1040         }
1041         brush->supercontents = supercontents;
1042         for (j = 0;j < brush->numplanes;j++)
1043         {
1044                 brush->planes[j].q3surfaceflags = q3surfaceflags;
1045                 brush->planes[j].texture = texture;
1046                 brush->planes[j].dist = furthestplanedist_float(brush->planes[j].normal, brush->points, brush->numpoints);
1047         }
1048         VectorCopy(brush->points[0].v, brush->mins);
1049         VectorCopy(brush->points[0].v, brush->maxs);
1050         for (j = 1;j < brush->numpoints;j++)
1051         {
1052                 brush->mins[0] = min(brush->mins[0], brush->points[j].v[0]);
1053                 brush->mins[1] = min(brush->mins[1], brush->points[j].v[1]);
1054                 brush->mins[2] = min(brush->mins[2], brush->points[j].v[2]);
1055                 brush->maxs[0] = max(brush->maxs[0], brush->points[j].v[0]);
1056                 brush->maxs[1] = max(brush->maxs[1], brush->points[j].v[1]);
1057                 brush->maxs[2] = max(brush->maxs[2], brush->points[j].v[2]);
1058         }
1059         brush->mins[0] -= 1;
1060         brush->mins[1] -= 1;
1061         brush->mins[2] -= 1;
1062         brush->maxs[0] += 1;
1063         brush->maxs[1] += 1;
1064         brush->maxs[2] += 1;
1065         Collision_ValidateBrush(brush);
1066         return brush;
1067 }
1068
1069 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)
1070 {
1071         colbrushf_t *boxbrush, *thisbrush_start, *thisbrush_end;
1072         vec3_t startmins, startmaxs, endmins, endmaxs;
1073
1074         // create brushes for the collision
1075         VectorAdd(start, mins, startmins);
1076         VectorAdd(start, maxs, startmaxs);
1077         VectorAdd(end, mins, endmins);
1078         VectorAdd(end, maxs, endmaxs);
1079         boxbrush = Collision_BrushForBox(&identitymatrix, cmins, cmaxs, supercontents, q3surfaceflags, texture);
1080         thisbrush_start = Collision_BrushForBox(&identitymatrix, startmins, startmaxs, 0, 0, NULL);
1081         thisbrush_end = Collision_BrushForBox(&identitymatrix, endmins, endmaxs, 0, 0, NULL);
1082
1083         memset(trace, 0, sizeof(trace_t));
1084         trace->hitsupercontentsmask = hitsupercontentsmask;
1085         trace->fraction = 1;
1086         trace->realfraction = 1;
1087         trace->allsolid = true;
1088         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, boxbrush, boxbrush);
1089 }
1090
1091 //pseudocode for detecting line/sphere overlap without calculating an impact point
1092 //linesphereorigin = sphereorigin - linestart;linediff = lineend - linestart;linespherefrac = DotProduct(linesphereorigin, linediff) / DotProduct(linediff, linediff);return VectorLength2(linesphereorigin - bound(0, linespherefrac, 1) * linediff) >= sphereradius*sphereradius;
1093
1094 // LordHavoc: currently unused, but tested
1095 // note: this can be used for tracing a moving sphere vs a stationary sphere,
1096 // by simply adding the moving sphere's radius to the sphereradius parameter,
1097 // all the results are correct (impactpoint, impactnormal, and fraction)
1098 float Collision_ClipTrace_Line_Sphere(double *linestart, double *lineend, double *sphereorigin, double sphereradius, double *impactpoint, double *impactnormal)
1099 {
1100         double dir[3], scale, v[3], deviationdist, impactdist, linelength;
1101         // make sure the impactpoint and impactnormal are valid even if there is
1102         // no collision
1103         VectorCopy(lineend, impactpoint);
1104         VectorClear(impactnormal);
1105         // calculate line direction
1106         VectorSubtract(lineend, linestart, dir);
1107         // normalize direction
1108         linelength = VectorLength(dir);
1109         if (linelength)
1110         {
1111                 scale = 1.0 / linelength;
1112                 VectorScale(dir, scale, dir);
1113         }
1114         // this dotproduct calculates the distance along the line at which the
1115         // sphere origin is (nearest point to the sphere origin on the line)
1116         impactdist = DotProduct(sphereorigin, dir) - DotProduct(linestart, dir);
1117         // calculate point on line at that distance, and subtract the
1118         // sphereorigin from it, so we have a vector to measure for the distance
1119         // of the line from the sphereorigin (deviation, how off-center it is)
1120         VectorMA(linestart, impactdist, dir, v);
1121         VectorSubtract(v, sphereorigin, v);
1122         deviationdist = VectorLength2(v);
1123         // if outside the radius, it's a miss for sure
1124         // (we do this comparison using squared radius to avoid a sqrt)
1125         if (deviationdist > sphereradius*sphereradius)
1126                 return 1; // miss (off to the side)
1127         // nudge back to find the correct impact distance
1128         impactdist += deviationdist - sphereradius;
1129         if (impactdist >= linelength)
1130                 return 1; // miss (not close enough)
1131         if (impactdist < 0)
1132                 return 1; // miss (linestart is past or inside sphere)
1133         // calculate new impactpoint
1134         VectorMA(linestart, impactdist, dir, impactpoint);
1135         // calculate impactnormal (surface normal at point of impact)
1136         VectorSubtract(impactpoint, sphereorigin, impactnormal);
1137         // normalize impactnormal
1138         VectorNormalize(impactnormal);
1139         // return fraction of movement distance
1140         return impactdist / linelength;
1141 }
1142
1143 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)
1144 {
1145 #if 1
1146         // more optimized
1147         float d1, d2, d, f, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, faceplanenormallength2, edge01[3], edge21[3], edge02[3];
1148
1149         // this function executes:
1150         // 32 ops when line starts behind triangle
1151         // 38 ops when line ends infront of triangle
1152         // 43 ops when line fraction is already closer than this triangle
1153         // 72 ops when line is outside edge 01
1154         // 92 ops when line is outside edge 21
1155         // 115 ops when line is outside edge 02
1156         // 123 ops when line impacts triangle and updates trace results
1157
1158         // this code is designed for clockwise triangles, conversion to
1159         // counterclockwise would require swapping some things around...
1160         // it is easier to simply swap the point0 and point2 parameters to this
1161         // function when calling it than it is to rewire the internals.
1162
1163         // calculate the faceplanenormal of the triangle, this represents the front side
1164         // 15 ops
1165         VectorSubtract(point0, point1, edge01);
1166         VectorSubtract(point2, point1, edge21);
1167         CrossProduct(edge01, edge21, faceplanenormal);
1168         // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
1169         // 6 ops
1170         faceplanenormallength2 = DotProduct(faceplanenormal, faceplanenormal);
1171         if (faceplanenormallength2 < 0.0001f)
1172                 return;
1173         // calculate the distance
1174         // 5 ops
1175         faceplanedist = DotProduct(point0, faceplanenormal);
1176
1177         // if start point is on the back side there is no collision
1178         // (we don't care about traces going through the triangle the wrong way)
1179
1180         // calculate the start distance
1181         // 6 ops
1182         d1 = DotProduct(faceplanenormal, linestart);
1183         if (d1 <= faceplanedist)
1184                 return;
1185
1186         // calculate the end distance
1187         // 6 ops
1188         d2 = DotProduct(faceplanenormal, lineend);
1189         // if both are in front, there is no collision
1190         if (d2 >= faceplanedist)
1191                 return;
1192
1193         // from here on we know d1 is >= 0 and d2 is < 0
1194         // this means the line starts infront and ends behind, passing through it
1195
1196         // calculate the recipricol of the distance delta,
1197         // so we can use it multiple times cheaply (instead of division)
1198         // 2 ops
1199         d = 1.0f / (d1 - d2);
1200         // calculate the impact fraction by taking the start distance (> 0)
1201         // and subtracting the face plane distance (this is the distance of the
1202         // triangle along that same normal)
1203         // then multiply by the recipricol distance delta
1204         // 2 ops
1205         f = (d1 - faceplanedist) * d;
1206         // skip out if this impact is further away than previous ones
1207         // 1 ops
1208         if (f > trace->realfraction)
1209                 return;
1210         // calculate the perfect impact point for classification of insidedness
1211         // 9 ops
1212         impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1213         impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1214         impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1215
1216         // calculate the edge normal and reject if impact is outside triangle
1217         // (an edge normal faces away from the triangle, to get the desired normal
1218         //  a crossproduct with the faceplanenormal is used, and because of the way
1219         // the insidedness comparison is written it does not need to be normalized)
1220
1221         // first use the two edges from the triangle plane math
1222         // the other edge only gets calculated if the point survives that long
1223
1224         // 20 ops
1225         CrossProduct(edge01, faceplanenormal, edgenormal);
1226         if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1227                 return;
1228
1229         // 20 ops
1230         CrossProduct(faceplanenormal, edge21, edgenormal);
1231         if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1232                 return;
1233
1234         // 23 ops
1235         VectorSubtract(point0, point2, edge02);
1236         CrossProduct(faceplanenormal, edge02, edgenormal);
1237         if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1238                 return;
1239
1240         // 8 ops (rare)
1241
1242         // store the new trace fraction
1243         trace->realfraction = f;
1244
1245         // calculate a nudged fraction to keep it out of the surface
1246         // (the main fraction remains perfect)
1247         trace->fraction = f - collision_impactnudge.value * d;
1248
1249         // store the new trace plane (because collisions only happen from
1250         // the front this is always simply the triangle normal, never flipped)
1251         d = 1.0 / sqrt(faceplanenormallength2);
1252         VectorScale(faceplanenormal, d, trace->plane.normal);
1253         trace->plane.dist = faceplanedist * d;
1254
1255         trace->hitsupercontents = supercontents;
1256         trace->hitq3surfaceflags = q3surfaceflags;
1257         trace->hittexture = texture;
1258 #else
1259         float d1, d2, d, f, fnudged, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, edge[3];
1260
1261         // this code is designed for clockwise triangles, conversion to
1262         // counterclockwise would require swapping some things around...
1263         // it is easier to simply swap the point0 and point2 parameters to this
1264         // function when calling it than it is to rewire the internals.
1265
1266         // calculate the unnormalized faceplanenormal of the triangle,
1267         // this represents the front side
1268         TriangleNormal(point0, point1, point2, faceplanenormal);
1269         // there's no point in processing a degenerate triangle
1270         // (GIGO - Garbage In, Garbage Out)
1271         if (DotProduct(faceplanenormal, faceplanenormal) < 0.0001f)
1272                 return;
1273         // calculate the unnormalized distance
1274         faceplanedist = DotProduct(point0, faceplanenormal);
1275
1276         // calculate the unnormalized start distance
1277         d1 = DotProduct(faceplanenormal, linestart) - faceplanedist;
1278         // if start point is on the back side there is no collision
1279         // (we don't care about traces going through the triangle the wrong way)
1280         if (d1 <= 0)
1281                 return;
1282
1283         // calculate the unnormalized end distance
1284         d2 = DotProduct(faceplanenormal, lineend) - faceplanedist;
1285         // if both are in front, there is no collision
1286         if (d2 >= 0)
1287                 return;
1288
1289         // from here on we know d1 is >= 0 and d2 is < 0
1290         // this means the line starts infront and ends behind, passing through it
1291
1292         // calculate the recipricol of the distance delta,
1293         // so we can use it multiple times cheaply (instead of division)
1294         d = 1.0f / (d1 - d2);
1295         // calculate the impact fraction by taking the start distance (> 0)
1296         // and subtracting the face plane distance (this is the distance of the
1297         // triangle along that same normal)
1298         // then multiply by the recipricol distance delta
1299         f = d1 * d;
1300         // skip out if this impact is further away than previous ones
1301         if (f > trace->realfraction)
1302                 return;
1303         // calculate the perfect impact point for classification of insidedness
1304         impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1305         impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1306         impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1307
1308         // calculate the edge normal and reject if impact is outside triangle
1309         // (an edge normal faces away from the triangle, to get the desired normal
1310         //  a crossproduct with the faceplanenormal is used, and because of the way
1311         // the insidedness comparison is written it does not need to be normalized)
1312
1313         VectorSubtract(point2, point0, edge);
1314         CrossProduct(edge, faceplanenormal, edgenormal);
1315         if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1316                 return;
1317
1318         VectorSubtract(point0, point1, edge);
1319         CrossProduct(edge, faceplanenormal, edgenormal);
1320         if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1321                 return;
1322
1323         VectorSubtract(point1, point2, edge);
1324         CrossProduct(edge, faceplanenormal, edgenormal);
1325         if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1326                 return;
1327
1328         // store the new trace fraction
1329         trace->realfraction = bound(0, f, 1);
1330
1331         // store the new trace plane (because collisions only happen from
1332         // the front this is always simply the triangle normal, never flipped)
1333         VectorNormalize(faceplanenormal);
1334         VectorCopy(faceplanenormal, trace->plane.normal);
1335         trace->plane.dist = DotProduct(point0, faceplanenormal);
1336
1337         // calculate the normalized start and end distances
1338         d1 = DotProduct(trace->plane.normal, linestart) - trace->plane.dist;
1339         d2 = DotProduct(trace->plane.normal, lineend) - trace->plane.dist;
1340
1341         // calculate a nudged fraction to keep it out of the surface
1342         // (the main fraction remains perfect)
1343         fnudged = (d1 - collision_impactnudge.value) / (d1 - d2);
1344         trace->fraction = bound(0, fnudged, 1);
1345
1346         // store the new trace endpos
1347         // not needed, it's calculated later when the trace is finished
1348         //trace->endpos[0] = linestart[0] + fnudged * (lineend[0] - linestart[0]);
1349         //trace->endpos[1] = linestart[1] + fnudged * (lineend[1] - linestart[1]);
1350         //trace->endpos[2] = linestart[2] + fnudged * (lineend[2] - linestart[2]);
1351         trace->hitsupercontents = supercontents;
1352         trace->hitq3surfaceflags = q3surfaceflags;
1353         trace->hittexture = texture;
1354 #endif
1355 }
1356
1357 typedef struct colbspnode_s
1358 {
1359         mplane_t plane;
1360         struct colbspnode_s *children[2];
1361         // the node is reallocated or split if max is reached
1362         int numcolbrushf;
1363         int maxcolbrushf;
1364         colbrushf_t **colbrushflist;
1365         //int numcolbrushd;
1366         //int maxcolbrushd;
1367         //colbrushd_t **colbrushdlist;
1368 }
1369 colbspnode_t;
1370
1371 typedef struct colbsp_s
1372 {
1373         mempool_t *mempool;
1374         colbspnode_t *nodes;
1375 }
1376 colbsp_t;
1377
1378 colbsp_t *Collision_CreateCollisionBSP(mempool_t *mempool)
1379 {
1380         colbsp_t *bsp;
1381         bsp = (colbsp_t *)Mem_Alloc(mempool, sizeof(colbsp_t));
1382         bsp->mempool = mempool;
1383         bsp->nodes = (colbspnode_t *)Mem_Alloc(bsp->mempool, sizeof(colbspnode_t));
1384         return bsp;
1385 }
1386
1387 void Collision_FreeCollisionBSPNode(colbspnode_t *node)
1388 {
1389         if (node->children[0])
1390                 Collision_FreeCollisionBSPNode(node->children[0]);
1391         if (node->children[1])
1392                 Collision_FreeCollisionBSPNode(node->children[1]);
1393         while (--node->numcolbrushf)
1394                 Mem_Free(node->colbrushflist[node->numcolbrushf]);
1395         //while (--node->numcolbrushd)
1396         //      Mem_Free(node->colbrushdlist[node->numcolbrushd]);
1397         Mem_Free(node);
1398 }
1399
1400 void Collision_FreeCollisionBSP(colbsp_t *bsp)
1401 {
1402         Collision_FreeCollisionBSPNode(bsp->nodes);
1403         Mem_Free(bsp);
1404 }
1405
1406 void Collision_BoundingBoxOfBrushTraceSegment(const colbrushf_t *start, const colbrushf_t *end, vec3_t mins, vec3_t maxs, float startfrac, float endfrac)
1407 {
1408         int i;
1409         colpointf_t *ps, *pe;
1410         float tempstart[3], tempend[3];
1411         VectorLerp(start->points[0].v, startfrac, end->points[0].v, mins);
1412         VectorCopy(mins, maxs);
1413         for (i = 0, ps = start->points, pe = end->points;i < start->numpoints;i++, ps++, pe++)
1414         {
1415                 VectorLerp(ps->v, startfrac, pe->v, tempstart);
1416                 VectorLerp(ps->v, endfrac, pe->v, tempend);
1417                 mins[0] = min(mins[0], min(tempstart[0], tempend[0]));
1418                 mins[1] = min(mins[1], min(tempstart[1], tempend[1]));
1419                 mins[2] = min(mins[2], min(tempstart[2], tempend[2]));
1420                 maxs[0] = min(maxs[0], min(tempstart[0], tempend[0]));
1421                 maxs[1] = min(maxs[1], min(tempstart[1], tempend[1]));
1422                 maxs[2] = min(maxs[2], min(tempstart[2], tempend[2]));
1423         }
1424         mins[0] -= 1;
1425         mins[1] -= 1;
1426         mins[2] -= 1;
1427         maxs[0] += 1;
1428         maxs[1] += 1;
1429         maxs[2] += 1;
1430 }
1431