5 #define COLLISION_EDGEDIR_DOT_EPSILON (0.999f)
6 #define COLLISION_EDGECROSS_MINLENGTH2 (1.0f / 4194304.0f)
7 #define COLLISION_SNAPSCALE (32.0f)
8 #define COLLISION_SNAP (1.0f / COLLISION_SNAPSCALE)
9 #define COLLISION_SNAP2 (2.0f / COLLISION_SNAPSCALE)
10 #define COLLISION_PLANE_DIST_EPSILON (2.0f / COLLISION_SNAPSCALE)
12 cvar_t collision_impactnudge = {0, "collision_impactnudge", "0.03125", "how much to back off from the impact"};
13 cvar_t collision_startnudge = {0, "collision_startnudge", "0", "how much to bias collision trace start"};
14 cvar_t collision_endnudge = {0, "collision_endnudge", "0", "how much to bias collision trace end"};
15 cvar_t collision_enternudge = {0, "collision_enternudge", "0", "how much to bias collision entry fraction"};
16 cvar_t collision_leavenudge = {0, "collision_leavenudge", "0", "how much to bias collision exit fraction"};
17 cvar_t collision_prefernudgedfraction = {0, "collision_prefernudgedfraction", "1", "whether to sort collision events by nudged fraction (1) or real fraction (0)"};
18 cvar_t collision_extendmovelength = {0, "collision_extendmovelength", "16", "internal bias on trace length to ensure detection of collisions within the collision_impactnudge/collision_enternudge/collision_leavenudge distance so that short moves do not degrade across frames (this does not alter the final trace length)"};
19 cvar_t collision_extendtraceboxlength = {0, "collision_extendtraceboxlength", "1", "internal bias for tracebox() qc builtin to account for collision_impactnudge/collision_enternudge/collision_leavenudge (this does not alter the final trace length)"};
20 cvar_t collision_extendtracelinelength = {0, "collision_extendtracelinelength", "1", "internal bias for traceline() qc builtin to account for collision_impactnudge/collision_enternudge/collision_leavenudge (this does not alter the final trace length)"};
21 cvar_t collision_debug_tracelineasbox = {0, "collision_debug_tracelineasbox", "0", "workaround for any bugs in Collision_TraceLineBrushFloat by using Collision_TraceBrushBrushFloat"};
22 cvar_t collision_cache = {0, "collision_cache", "1", "store results of collision traces for next frame to reuse if possible (optimization)"};
23 //cvar_t collision_triangle_neighborsides = {0, "collision_triangle_neighborsides", "1", "override automatic side generation if triangle has neighbors with face planes that form a convex edge (perfect solution, but can not work for all edges)"};
24 cvar_t collision_triangle_bevelsides = {0, "collision_triangle_bevelsides", "0", "generate sloped edge planes on triangles - if 0, see axialedgeplanes"};
25 cvar_t collision_triangle_axialsides = {0, "collision_triangle_axialsides", "1", "generate axially-aligned edge planes on triangles - otherwise use perpendicular edge planes"};
27 mempool_t *collision_mempool;
29 void Collision_Init (void)
31 Cvar_RegisterVariable(&collision_impactnudge);
32 Cvar_RegisterVariable(&collision_startnudge);
33 Cvar_RegisterVariable(&collision_endnudge);
34 Cvar_RegisterVariable(&collision_enternudge);
35 Cvar_RegisterVariable(&collision_leavenudge);
36 Cvar_RegisterVariable(&collision_prefernudgedfraction);
37 Cvar_RegisterVariable(&collision_extendmovelength);
38 Cvar_RegisterVariable(&collision_extendtracelinelength);
39 Cvar_RegisterVariable(&collision_extendtraceboxlength);
40 Cvar_RegisterVariable(&collision_debug_tracelineasbox);
41 Cvar_RegisterVariable(&collision_cache);
42 // Cvar_RegisterVariable(&collision_triangle_neighborsides);
43 Cvar_RegisterVariable(&collision_triangle_bevelsides);
44 Cvar_RegisterVariable(&collision_triangle_axialsides);
45 collision_mempool = Mem_AllocPool("collision cache", 0, NULL);
46 Collision_Cache_Init(collision_mempool);
62 static void Collision_PrintBrushAsQHull(colbrushf_t *brush, const char *name)
65 Con_Printf("3 %s\n%i\n", name, brush->numpoints);
66 for (i = 0;i < brush->numpoints;i++)
67 Con_Printf("%f %f %f\n", brush->points[i].v[0], brush->points[i].v[1], brush->points[i].v[2]);
69 Con_Printf("4\n%i\n", brush->numplanes);
70 for (i = 0;i < brush->numplanes;i++)
71 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);
74 static void Collision_ValidateBrush(colbrushf_t *brush)
76 int j, k, pointsoffplanes, pointonplanes, pointswithinsufficientplanes, printbrush;
79 if (!brush->numpoints)
81 Con_Print("Collision_ValidateBrush: brush with no points!\n");
85 // it's ok for a brush to have one point and no planes...
86 if (brush->numplanes == 0 && brush->numpoints != 1)
88 Con_Print("Collision_ValidateBrush: brush with no planes and more than one point!\n");
95 pointswithinsufficientplanes = 0;
96 for (k = 0;k < brush->numplanes;k++)
97 if (DotProduct(brush->planes[k].normal, brush->planes[k].normal) < 0.0001f)
98 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);
99 for (j = 0;j < brush->numpoints;j++)
102 for (k = 0;k < brush->numplanes;k++)
104 d = DotProduct(brush->points[j].v, brush->planes[k].normal) - brush->planes[k].dist;
105 if (d > COLLISION_PLANE_DIST_EPSILON)
107 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);
110 if (fabs(d) > COLLISION_PLANE_DIST_EPSILON)
115 if (pointonplanes < 3)
116 pointswithinsufficientplanes++;
118 if (pointswithinsufficientplanes)
120 Con_Print("Collision_ValidateBrush: some points have insufficient planes, every point must be on at least 3 planes to form a corner.\n");
123 if (pointsoffplanes == 0) // all points are on all planes
125 Con_Print("Collision_ValidateBrush: all points lie on all planes (degenerate, no brush volume!)\n");
130 Collision_PrintBrushAsQHull(brush, "unnamed");
133 static float nearestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
135 float dist, bestdist;
138 bestdist = DotProduct(points->v, normal);
142 dist = DotProduct(points->v, normal);
143 bestdist = min(bestdist, dist);
149 static float furthestplanedist_float(const float *normal, const colpointf_t *points, int numpoints)
151 float dist, bestdist;
154 bestdist = DotProduct(points->v, normal);
158 dist = DotProduct(points->v, normal);
159 bestdist = max(bestdist, dist);
165 static void Collision_CalcEdgeDirsForPolygonBrushFloat(colbrushf_t *brush)
168 for (i = 0, j = brush->numpoints - 1;i < brush->numpoints;j = i, i++)
169 VectorSubtract(brush->points[i].v, brush->points[j].v, brush->edgedirs[j].v);
172 colbrushf_t *Collision_NewBrushFromPlanes(mempool_t *mempool, int numoriginalplanes, const colplanef_t *originalplanes, int supercontents, int q3surfaceflags, const texture_t *texture, int hasaabbplanes)
174 // TODO: planesbuf could be replaced by a remapping table
175 int j, k, l, m, w, xyzflags;
176 int numpointsbuf = 0, maxpointsbuf = 256, numedgedirsbuf = 0, maxedgedirsbuf = 256, numplanesbuf = 0, maxplanesbuf = 256, numelementsbuf = 0, maxelementsbuf = 256;
180 colpointf_t pointsbuf[256];
181 colpointf_t edgedirsbuf[256];
182 colplanef_t planesbuf[256];
183 int elementsbuf[1024];
184 int polypointbuf[256];
189 // enable these if debugging to avoid seeing garbage in unused data-
190 memset(pointsbuf, 0, sizeof(pointsbuf));
191 memset(edgedirsbuf, 0, sizeof(edgedirsbuf));
192 memset(planesbuf, 0, sizeof(planesbuf));
193 memset(elementsbuf, 0, sizeof(elementsbuf));
194 memset(polypointbuf, 0, sizeof(polypointbuf));
195 memset(p, 0, sizeof(p));
198 // check if there are too many planes and skip the brush
199 if (numoriginalplanes >= maxplanesbuf)
201 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many planes for buffer\n");
205 // figure out how large a bounding box we need to properly compute this brush
207 for (j = 0;j < numoriginalplanes;j++)
208 maxdist = max(maxdist, fabs(originalplanes[j].dist));
209 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
210 maxdist = floor(maxdist * (4.0 / 1024.0) + 2) * 1024.0;
211 // construct a collision brush (points, planes, and renderable mesh) from
212 // a set of planes, this also optimizes out any unnecessary planes (ones
213 // whose polygon is clipped away by the other planes)
214 for (j = 0;j < numoriginalplanes;j++)
217 VectorCopy(originalplanes[j].normal, planesbuf[numplanesbuf].normal);
218 planesbuf[numplanesbuf].dist = originalplanes[j].dist;
219 planesbuf[numplanesbuf].q3surfaceflags = originalplanes[j].q3surfaceflags;
220 planesbuf[numplanesbuf].texture = originalplanes[j].texture;
223 // create a large polygon from the plane
225 PolygonD_QuadForPlane(p[w], originalplanes[j].normal[0], originalplanes[j].normal[1], originalplanes[j].normal[2], originalplanes[j].dist, maxdist);
227 // clip it by all other planes
228 for (k = 0;k < numoriginalplanes && pnumpoints >= 3 && pnumpoints <= pmaxpoints;k++)
230 // skip the plane this polygon
231 // (nothing happens if it is processed, this is just an optimization)
234 // we want to keep the inside of the brush plane so we flip
236 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);
241 // if nothing is left, skip it
244 //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);
248 for (k = 0;k < pnumpoints;k++)
252 for (l = 0;l < numoriginalplanes;l++)
253 if (fabs(DotProduct(&p[w][k*3], originalplanes[l].normal) - originalplanes[l].dist) < COLLISION_PLANE_DIST_EPSILON)
260 Con_DPrintf("Collision_NewBrushFromPlanes: warning: polygon point does not lie on at least 3 planes\n");
264 // check if there are too many polygon vertices for buffer
265 if (pnumpoints > pmaxpoints)
267 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
271 // check if there are too many triangle elements for buffer
272 if (numelementsbuf + (pnumpoints - 2) * 3 > maxelementsbuf)
274 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many triangle elements for buffer\n");
278 // add the unique points for this polygon
279 for (k = 0;k < pnumpoints;k++)
282 // downgrade to float precision before comparing
283 VectorCopy(&p[w][k*3], v);
285 // check if there is already a matching point (no duplicates)
286 for (m = 0;m < numpointsbuf;m++)
287 if (VectorDistance2(v, pointsbuf[m].v) < COLLISION_SNAP2)
290 // if there is no match, add a new one
291 if (m == numpointsbuf)
293 // check if there are too many and skip the brush
294 if (numpointsbuf >= maxpointsbuf)
296 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many points for buffer\n");
300 VectorCopy(&p[w][k*3], pointsbuf[numpointsbuf].v);
304 // store the index into a buffer
308 // add the triangles for the polygon
309 // (this particular code makes a triangle fan)
310 for (k = 0;k < pnumpoints - 2;k++)
312 elementsbuf[numelementsbuf++] = polypointbuf[0];
313 elementsbuf[numelementsbuf++] = polypointbuf[k + 1];
314 elementsbuf[numelementsbuf++] = polypointbuf[k + 2];
317 // add the unique edgedirs for this polygon
318 for (k = 0, l = pnumpoints-1;k < pnumpoints;l = k, k++)
321 // downgrade to float precision before comparing
322 VectorSubtract(&p[w][k*3], &p[w][l*3], dir);
323 VectorNormalize(dir);
325 // check if there is already a matching edgedir (no duplicates)
326 for (m = 0;m < numedgedirsbuf;m++)
327 if (DotProduct(dir, edgedirsbuf[m].v) >= COLLISION_EDGEDIR_DOT_EPSILON)
329 // skip this if there is
330 if (m < numedgedirsbuf)
333 // try again with negated edgedir
334 VectorNegate(dir, dir);
335 // check if there is already a matching edgedir (no duplicates)
336 for (m = 0;m < numedgedirsbuf;m++)
337 if (DotProduct(dir, edgedirsbuf[m].v) >= COLLISION_EDGEDIR_DOT_EPSILON)
339 // if there is no match, add a new one
340 if (m == numedgedirsbuf)
342 // check if there are too many and skip the brush
343 if (numedgedirsbuf >= maxedgedirsbuf)
345 Con_DPrint("Collision_NewBrushFromPlanes: failed to build collision brush: too many edgedirs for buffer\n");
349 VectorCopy(dir, edgedirsbuf[numedgedirsbuf].v);
354 // if any normal is not purely axial, it's not an axis-aligned box
355 if (isaabb && (originalplanes[j].normal[0] == 0) + (originalplanes[j].normal[1] == 0) + (originalplanes[j].normal[2] == 0) < 2)
359 // if nothing is left, there's nothing to allocate
360 if (numplanesbuf < 4)
362 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);
366 // if no triangles or points could be constructed, then this routine failed but the brush is not discarded
367 if (numelementsbuf < 12 || numpointsbuf < 4)
368 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);
370 // validate plane distances
371 for (j = 0;j < numplanesbuf;j++)
373 float d = furthestplanedist_float(planesbuf[j].normal, pointsbuf, numpointsbuf);
374 if (fabs(planesbuf[j].dist - d) > COLLISION_PLANE_DIST_EPSILON)
375 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);
378 // allocate the brush and copy to it
379 brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colpointf_t) * numpointsbuf + sizeof(colpointf_t) * numedgedirsbuf + sizeof(colplanef_t) * numplanesbuf + sizeof(int) * numelementsbuf);
380 brush->isaabb = isaabb;
381 brush->hasaabbplanes = hasaabbplanes;
382 brush->supercontents = supercontents;
383 brush->numplanes = numplanesbuf;
384 brush->numedgedirs = numedgedirsbuf;
385 brush->numpoints = numpointsbuf;
386 brush->numtriangles = numelementsbuf / 3;
387 brush->planes = (colplanef_t *)(brush + 1);
388 brush->points = (colpointf_t *)(brush->planes + brush->numplanes);
389 brush->edgedirs = (colpointf_t *)(brush->points + brush->numpoints);
390 brush->elements = (int *)(brush->points + brush->numpoints);
391 brush->q3surfaceflags = q3surfaceflags;
392 brush->texture = texture;
393 for (j = 0;j < brush->numpoints;j++)
395 brush->points[j].v[0] = pointsbuf[j].v[0];
396 brush->points[j].v[1] = pointsbuf[j].v[1];
397 brush->points[j].v[2] = pointsbuf[j].v[2];
399 for (j = 0;j < brush->numedgedirs;j++)
401 brush->edgedirs[j].v[0] = edgedirsbuf[j].v[0];
402 brush->edgedirs[j].v[1] = edgedirsbuf[j].v[1];
403 brush->edgedirs[j].v[2] = edgedirsbuf[j].v[2];
405 for (j = 0;j < brush->numplanes;j++)
407 brush->planes[j].normal[0] = planesbuf[j].normal[0];
408 brush->planes[j].normal[1] = planesbuf[j].normal[1];
409 brush->planes[j].normal[2] = planesbuf[j].normal[2];
410 brush->planes[j].dist = planesbuf[j].dist;
411 brush->planes[j].q3surfaceflags = planesbuf[j].q3surfaceflags;
412 brush->planes[j].texture = planesbuf[j].texture;
414 for (j = 0;j < brush->numtriangles * 3;j++)
415 brush->elements[j] = elementsbuf[j];
418 VectorClear(brush->mins);
419 VectorClear(brush->maxs);
420 for (j = 0;j < min(6, numoriginalplanes);j++)
422 if (originalplanes[j].normal[0] == 1) {xyzflags |= 1;brush->maxs[0] = originalplanes[j].dist;}
423 else if (originalplanes[j].normal[0] == -1) {xyzflags |= 2;brush->mins[0] = -originalplanes[j].dist;}
424 else if (originalplanes[j].normal[1] == 1) {xyzflags |= 4;brush->maxs[1] = originalplanes[j].dist;}
425 else if (originalplanes[j].normal[1] == -1) {xyzflags |= 8;brush->mins[1] = -originalplanes[j].dist;}
426 else if (originalplanes[j].normal[2] == 1) {xyzflags |= 16;brush->maxs[2] = originalplanes[j].dist;}
427 else if (originalplanes[j].normal[2] == -1) {xyzflags |= 32;brush->mins[2] = -originalplanes[j].dist;}
429 // if not all xyzflags were set, then this is not a brush from q3map/q3map2, and needs reconstruction of the bounding box
430 // (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)
433 VectorCopy(brush->points[0].v, brush->mins);
434 VectorCopy(brush->points[0].v, brush->maxs);
435 for (j = 1;j < brush->numpoints;j++)
437 brush->mins[0] = min(brush->mins[0], brush->points[j].v[0]);
438 brush->mins[1] = min(brush->mins[1], brush->points[j].v[1]);
439 brush->mins[2] = min(brush->mins[2], brush->points[j].v[2]);
440 brush->maxs[0] = max(brush->maxs[0], brush->points[j].v[0]);
441 brush->maxs[1] = max(brush->maxs[1], brush->points[j].v[1]);
442 brush->maxs[2] = max(brush->maxs[2], brush->points[j].v[2]);
451 Collision_ValidateBrush(brush);
457 void Collision_CalcPlanesForTriangleBrushFloat(colbrushf_t *brush)
460 float edge0[3], edge1[3], edge2[3];
463 TriangleNormal(brush->points[0].v, brush->points[1].v, brush->points[2].v, brush->planes[0].normal);
464 if (DotProduct(brush->planes[0].normal, brush->planes[0].normal) < 0.0001f)
466 // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
467 // note that some of these exist in q3bsp bspline patches
468 brush->numplanes = 0;
472 // there are 5 planes (front, back, sides) and 3 edges
473 brush->numplanes = 5;
474 brush->numedgedirs = 3;
475 VectorNormalize(brush->planes[0].normal);
476 brush->planes[0].dist = DotProduct(brush->points->v, brush->planes[0].normal);
477 VectorNegate(brush->planes[0].normal, brush->planes[1].normal);
478 brush->planes[1].dist = -brush->planes[0].dist;
479 // edge directions are easy to calculate
480 VectorSubtract(brush->points[2].v, brush->points[0].v, edge0);
481 VectorSubtract(brush->points[0].v, brush->points[1].v, edge1);
482 VectorSubtract(brush->points[1].v, brush->points[2].v, edge2);
483 VectorCopy(edge0, brush->edgedirs[0].v);
484 VectorCopy(edge1, brush->edgedirs[1].v);
485 VectorCopy(edge2, brush->edgedirs[2].v);
486 // now select an algorithm to generate the side planes
487 if (collision_triangle_bevelsides.integer)
489 // use 45 degree slopes at the edges of the triangle to make a sinking trace error turn into "riding up" the slope rather than getting stuck
490 CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
491 CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
492 CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
493 VectorNormalize(brush->planes[2].normal);
494 VectorNormalize(brush->planes[3].normal);
495 VectorNormalize(brush->planes[4].normal);
496 VectorAdd(brush->planes[2].normal, brush->planes[0].normal, brush->planes[2].normal);
497 VectorAdd(brush->planes[3].normal, brush->planes[0].normal, brush->planes[3].normal);
498 VectorAdd(brush->planes[4].normal, brush->planes[0].normal, brush->planes[4].normal);
499 VectorNormalize(brush->planes[2].normal);
500 VectorNormalize(brush->planes[3].normal);
501 VectorNormalize(brush->planes[4].normal);
503 else if (collision_triangle_axialsides.integer)
505 float projectionnormal[3], projectionedge0[3], projectionedge1[3], projectionedge2[3];
507 float dist, bestdist;
508 bestdist = fabs(brush->planes[0].normal[0]);
510 for (i = 1;i < 3;i++)
512 dist = fabs(brush->planes[0].normal[i]);
519 VectorClear(projectionnormal);
520 if (brush->planes[0].normal[best] < 0)
521 projectionnormal[best] = -1;
523 projectionnormal[best] = 1;
524 VectorCopy(edge0, projectionedge0);
525 VectorCopy(edge1, projectionedge1);
526 VectorCopy(edge2, projectionedge2);
527 projectionedge0[best] = 0;
528 projectionedge1[best] = 0;
529 projectionedge2[best] = 0;
530 CrossProduct(projectionedge0, projectionnormal, brush->planes[2].normal);
531 CrossProduct(projectionedge1, projectionnormal, brush->planes[3].normal);
532 CrossProduct(projectionedge2, projectionnormal, brush->planes[4].normal);
533 VectorNormalize(brush->planes[2].normal);
534 VectorNormalize(brush->planes[3].normal);
535 VectorNormalize(brush->planes[4].normal);
539 CrossProduct(edge0, brush->planes->normal, brush->planes[2].normal);
540 CrossProduct(edge1, brush->planes->normal, brush->planes[3].normal);
541 CrossProduct(edge2, brush->planes->normal, brush->planes[4].normal);
542 VectorNormalize(brush->planes[2].normal);
543 VectorNormalize(brush->planes[3].normal);
544 VectorNormalize(brush->planes[4].normal);
546 brush->planes[2].dist = DotProduct(brush->points[2].v, brush->planes[2].normal);
547 brush->planes[3].dist = DotProduct(brush->points[0].v, brush->planes[3].normal);
548 brush->planes[4].dist = DotProduct(brush->points[1].v, brush->planes[4].normal);
550 if (developer_extra.integer)
552 // validity check - will be disabled later
553 Collision_ValidateBrush(brush);
554 for (i = 0;i < brush->numplanes;i++)
557 for (j = 0, p = brush->points;j < brush->numpoints;j++, p++)
558 if (DotProduct(p->v, brush->planes[i].normal) > brush->planes[i].dist + COLLISION_PLANE_DIST_EPSILON)
559 Con_DPrintf("Error in brush plane generation, plane %i\n", i);
564 colbrushf_t *Collision_AllocBrushFromPermanentPolygonFloat(mempool_t *mempool, int numpoints, float *points, int supercontents, int q3surfaceflags, const texture_t *texture)
567 brush = (colbrushf_t *)Mem_Alloc(mempool, sizeof(colbrushf_t) + sizeof(colplanef_t) * (numpoints + 2) + sizeof(colpointf_t) * numpoints);
568 brush->isaabb = false;
569 brush->hasaabbplanes = false;
570 brush->supercontents = supercontents;
571 brush->numpoints = numpoints;
572 brush->numedgedirs = numpoints;
573 brush->numplanes = numpoints + 2;
574 brush->planes = (colplanef_t *)(brush + 1);
575 brush->points = (colpointf_t *)points;
576 brush->edgedirs = (colpointf_t *)(brush->planes + brush->numplanes);
577 brush->q3surfaceflags = q3surfaceflags;
578 brush->texture = texture;
579 Sys_Error("Collision_AllocBrushFromPermanentPolygonFloat: FIXME: this code needs to be updated to generate a mesh...");
583 // NOTE: start and end of each brush pair must have same numplanes/numpoints
584 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)
586 int nplane, nplane2, nedge1, nedge2, hitq3surfaceflags = 0;
587 int tracenumedgedirs = trace_start->numedgedirs;
588 //int othernumedgedirs = other_start->numedgedirs;
589 int tracenumpoints = trace_start->numpoints;
590 int othernumpoints = other_start->numpoints;
591 int numplanes1 = other_start->numplanes;
592 int numplanes2 = numplanes1 + trace_start->numplanes;
593 int numplanes3 = numplanes2 + trace_start->numedgedirs * other_start->numedgedirs * 2;
594 vec_t enterfrac = -1, leavefrac = 1, startdist, enddist, ie, f, imove, enterfrac2 = -1;
597 vec4_t newimpactplane;
598 const texture_t *hittexture = NULL;
599 vec_t startdepth = 1;
600 vec3_t startdepthnormal;
602 VectorClear(startdepthnormal);
603 Vector4Clear(newimpactplane);
605 // fast case for AABB vs compiled brushes (which begin with AABB planes and also have precomputed bevels for AABB collisions)
606 if (trace_start->isaabb && other_start->hasaabbplanes)
607 numplanes3 = numplanes2 = numplanes1;
609 // Separating Axis Theorem:
610 // if a supporting vector (plane normal) can be found that separates two
611 // objects, they are not colliding.
614 // reduce the size of one object to a point while enlarging the other to
615 // represent the space that point can not occupy.
617 // try every plane we can construct between the two brushes and measure
618 // the distance between them.
619 for (nplane = 0;nplane < numplanes3;nplane++)
621 if (nplane < numplanes1)
624 VectorCopy(other_start->planes[nplane2].normal, startplane);
625 VectorCopy(other_end->planes[nplane2].normal, endplane);
627 else if (nplane < numplanes2)
629 nplane2 = nplane - numplanes1;
630 VectorCopy(trace_start->planes[nplane2].normal, startplane);
631 VectorCopy(trace_end->planes[nplane2].normal, endplane);
635 // pick an edgedir from each brush and cross them
636 nplane2 = nplane - numplanes2;
637 nedge1 = nplane2 >> 1;
638 nedge2 = nedge1 / tracenumedgedirs;
639 nedge1 -= nedge2 * tracenumedgedirs;
642 CrossProduct(trace_start->edgedirs[nedge1].v, other_start->edgedirs[nedge2].v, startplane);
643 CrossProduct(trace_end->edgedirs[nedge1].v, other_end->edgedirs[nedge2].v, endplane);
647 CrossProduct(other_start->edgedirs[nedge2].v, trace_start->edgedirs[nedge1].v, startplane);
648 CrossProduct(other_end->edgedirs[nedge2].v, trace_end->edgedirs[nedge1].v, endplane);
650 if (VectorLength2(startplane) < COLLISION_EDGECROSS_MINLENGTH2 || VectorLength2(endplane) < COLLISION_EDGECROSS_MINLENGTH2)
651 continue; // degenerate crossproducts
652 VectorNormalize(startplane);
653 VectorNormalize(endplane);
655 startplane[3] = furthestplanedist_float(startplane, other_start->points, othernumpoints);
656 endplane[3] = furthestplanedist_float(startplane, other_end->points, othernumpoints);
657 startdist = nearestplanedist_float(startplane, trace_start->points, tracenumpoints) - startplane[3] - collision_startnudge.value;
658 enddist = nearestplanedist_float(endplane, trace_end->points, tracenumpoints) - endplane[3] - collision_endnudge.value;
659 //Con_Printf("%c%i: startdist = %f, enddist = %f, startdist / (startdist - enddist) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, startdist, enddist, startdist / (startdist - enddist));
661 // aside from collisions, this is also used for error correction
662 if (startdist <= collision_impactnudge.value && nplane < numplanes1 && (startdepth < startdist || startdepth == 1))
664 startdepth = startdist;
665 VectorCopy(startplane, startdepthnormal);
668 if (startdist > enddist)
671 if (enddist >= collision_enternudge.value)
676 imove = 1 / (startdist - enddist);
677 f = (startdist - collision_enternudge.value) * imove;
680 // check if this will reduce the collision time range
683 // reduced collision time range
685 // if the collision time range is now empty, no collision
686 if (enterfrac > leavefrac)
688 // if the collision would be further away than the trace's
689 // existing collision data, we don't care about this
691 if (enterfrac > trace->realfraction)
693 // calculate the nudged fraction and impact normal we'll
694 // need if we accept this collision later
695 enterfrac2 = (startdist - collision_impactnudge.value) * imove;
696 ie = 1.0f - enterfrac;
697 newimpactplane[0] = startplane[0] * ie + endplane[0] * enterfrac;
698 newimpactplane[1] = startplane[1] * ie + endplane[1] * enterfrac;
699 newimpactplane[2] = startplane[2] * ie + endplane[2] * enterfrac;
700 newimpactplane[3] = startplane[3] * ie + endplane[3] * enterfrac;
701 if (nplane < numplanes1)
703 // use the plane from other
705 hitq3surfaceflags = other_start->planes[nplane2].q3surfaceflags;
706 hittexture = other_start->planes[nplane2].texture;
708 else if (nplane < numplanes2)
710 // use the plane from trace
711 nplane2 = nplane - numplanes1;
712 hitq3surfaceflags = trace_start->planes[nplane2].q3surfaceflags;
713 hittexture = trace_start->planes[nplane2].texture;
717 hitq3surfaceflags = other_start->q3surfaceflags;
718 hittexture = other_start->texture;
725 // moving out of brush
731 f = (startdist + collision_leavenudge.value) / (startdist - enddist);
734 // check if this will reduce the collision time range
737 // reduced collision time range
739 // if the collision time range is now empty, no collision
740 if (enterfrac > leavefrac)
747 // at this point we know the trace overlaps the brush because it was not
748 // rejected at any point in the loop above
750 // see if the trace started outside the brush or not
753 // started outside, and overlaps, therefore there is a collision here
754 // store out the impact information
755 if (trace->hitsupercontentsmask & other_start->supercontents)
757 trace->hitsupercontents = other_start->supercontents;
758 trace->hitq3surfaceflags = hitq3surfaceflags;
759 trace->hittexture = hittexture;
760 trace->realfraction = bound(0, enterfrac, 1);
761 trace->fraction = bound(0, enterfrac2, 1);
762 if (collision_prefernudgedfraction.integer)
763 trace->realfraction = trace->fraction;
764 VectorCopy(newimpactplane, trace->plane.normal);
765 trace->plane.dist = newimpactplane[3];
770 // started inside, update startsolid and friends
771 trace->startsupercontents |= other_start->supercontents;
772 if (trace->hitsupercontentsmask & other_start->supercontents)
774 trace->startsolid = true;
776 trace->allsolid = true;
777 VectorCopy(newimpactplane, trace->plane.normal);
778 trace->plane.dist = newimpactplane[3];
779 if (trace->startdepth > startdepth)
781 trace->startdepth = startdepth;
782 VectorCopy(startdepthnormal, trace->startdepthnormal);
788 // NOTE: start and end of each brush pair must have same numplanes/numpoints
789 void Collision_TraceLineBrushFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const colbrushf_t *other_start, const colbrushf_t *other_end)
791 int nplane, hitq3surfaceflags = 0;
792 int numplanes = other_start->numplanes;
793 vec_t enterfrac = -1, leavefrac = 1, startdist, enddist, ie, f, imove, enterfrac2 = -1;
796 vec4_t newimpactplane;
797 const texture_t *hittexture = NULL;
798 vec_t startdepth = 1;
799 vec3_t startdepthnormal;
801 if (collision_debug_tracelineasbox.integer)
803 colboxbrushf_t thisbrush_start, thisbrush_end;
804 Collision_BrushForBox(&thisbrush_start, linestart, linestart, 0, 0, NULL);
805 Collision_BrushForBox(&thisbrush_end, lineend, lineend, 0, 0, NULL);
806 Collision_TraceBrushBrushFloat(trace, &thisbrush_start.brush, &thisbrush_end.brush, other_start, other_end);
810 VectorClear(startdepthnormal);
811 Vector4Clear(newimpactplane);
813 // Separating Axis Theorem:
814 // if a supporting vector (plane normal) can be found that separates two
815 // objects, they are not colliding.
818 // reduce the size of one object to a point while enlarging the other to
819 // represent the space that point can not occupy.
821 // try every plane we can construct between the two brushes and measure
822 // the distance between them.
823 for (nplane = 0;nplane < numplanes;nplane++)
825 VectorCopy(other_start->planes[nplane].normal, startplane);
826 startplane[3] = other_start->planes[nplane].dist;
827 VectorCopy(other_end->planes[nplane].normal, endplane);
828 endplane[3] = other_end->planes[nplane].dist;
829 startdist = DotProduct(linestart, startplane) - startplane[3] - collision_startnudge.value;
830 enddist = DotProduct(lineend, endplane) - endplane[3] - collision_endnudge.value;
831 //Con_Printf("%c%i: startdist = %f, enddist = %f, startdist / (startdist - enddist) = %f\n", nplane2 != nplane ? 'b' : 'a', nplane2, startdist, enddist, startdist / (startdist - enddist));
833 // aside from collisions, this is also used for error correction
834 if (startdist < collision_impactnudge.value && (startdepth < startdist || startdepth == 1))
836 startdepth = startdist;
837 VectorCopy(startplane, startdepthnormal);
840 if (startdist > enddist)
843 if (enddist >= collision_enternudge.value)
848 imove = 1 / (startdist - enddist);
849 f = (startdist - collision_enternudge.value) * imove;
852 // check if this will reduce the collision time range
855 // reduced collision time range
857 // if the collision time range is now empty, no collision
858 if (enterfrac > leavefrac)
860 // if the collision would be further away than the trace's
861 // existing collision data, we don't care about this
863 if (enterfrac > trace->realfraction)
865 // calculate the nudged fraction and impact normal we'll
866 // need if we accept this collision later
867 enterfrac2 = (startdist - collision_impactnudge.value) * imove;
868 ie = 1.0f - enterfrac;
869 newimpactplane[0] = startplane[0] * ie + endplane[0] * enterfrac;
870 newimpactplane[1] = startplane[1] * ie + endplane[1] * enterfrac;
871 newimpactplane[2] = startplane[2] * ie + endplane[2] * enterfrac;
872 newimpactplane[3] = startplane[3] * ie + endplane[3] * enterfrac;
873 hitq3surfaceflags = other_start->planes[nplane].q3surfaceflags;
874 hittexture = other_start->planes[nplane].texture;
880 // moving out of brush
886 f = (startdist + collision_leavenudge.value) / (startdist - enddist);
889 // check if this will reduce the collision time range
892 // reduced collision time range
894 // if the collision time range is now empty, no collision
895 if (enterfrac > leavefrac)
902 // at this point we know the trace overlaps the brush because it was not
903 // rejected at any point in the loop above
905 // see if the trace started outside the brush or not
908 // started outside, and overlaps, therefore there is a collision here
909 // store out the impact information
910 if (trace->hitsupercontentsmask & other_start->supercontents)
912 trace->hitsupercontents = other_start->supercontents;
913 trace->hitq3surfaceflags = hitq3surfaceflags;
914 trace->hittexture = hittexture;
915 trace->realfraction = bound(0, enterfrac, 1);
916 trace->fraction = bound(0, enterfrac2, 1);
917 if (collision_prefernudgedfraction.integer)
918 trace->realfraction = trace->fraction;
919 VectorCopy(newimpactplane, trace->plane.normal);
920 trace->plane.dist = newimpactplane[3];
925 // started inside, update startsolid and friends
926 trace->startsupercontents |= other_start->supercontents;
927 if (trace->hitsupercontentsmask & other_start->supercontents)
929 trace->startsolid = true;
931 trace->allsolid = true;
932 VectorCopy(newimpactplane, trace->plane.normal);
933 trace->plane.dist = newimpactplane[3];
934 if (trace->startdepth > startdepth)
936 trace->startdepth = startdepth;
937 VectorCopy(startdepthnormal, trace->startdepthnormal);
943 qboolean Collision_PointInsideBrushFloat(const vec3_t point, const colbrushf_t *brush)
946 const colplanef_t *plane;
948 if (!BoxesOverlap(point, point, brush->mins, brush->maxs))
950 for (nplane = 0, plane = brush->planes;nplane < brush->numplanes;nplane++, plane++)
951 if (DotProduct(plane->normal, point) > plane->dist)
956 void Collision_TracePointBrushFloat(trace_t *trace, const vec3_t point, const colbrushf_t *thatbrush)
958 if (!Collision_PointInsideBrushFloat(point, thatbrush))
961 trace->startsupercontents |= thatbrush->supercontents;
962 if (trace->hitsupercontentsmask & thatbrush->supercontents)
964 trace->startsolid = true;
965 trace->allsolid = true;
969 static void Collision_SnapCopyPoints(int numpoints, const colpointf_t *in, colpointf_t *out, float fractionprecision, float invfractionprecision)
972 for (i = 0;i < numpoints;i++)
974 out[i].v[0] = floor(in[i].v[0] * fractionprecision + 0.5f) * invfractionprecision;
975 out[i].v[1] = floor(in[i].v[1] * fractionprecision + 0.5f) * invfractionprecision;
976 out[i].v[2] = floor(in[i].v[2] * fractionprecision + 0.5f) * invfractionprecision;
980 void Collision_TraceBrushTriangleMeshFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int numtriangles, const int *element3i, const float *vertex3f, int stride, float *bbox6f, int supercontents, int q3surfaceflags, const texture_t *texture, const vec3_t segmentmins, const vec3_t segmentmaxs)
983 colpointf_t points[3];
984 colpointf_t edgedirs[3];
985 colplanef_t planes[5];
987 memset(&brush, 0, sizeof(brush));
988 brush.isaabb = false;
989 brush.hasaabbplanes = false;
991 brush.numedgedirs = 3;
993 brush.points = points;
994 brush.edgedirs = edgedirs;
995 brush.planes = planes;
996 brush.supercontents = supercontents;
997 brush.q3surfaceflags = q3surfaceflags;
998 brush.texture = texture;
999 for (i = 0;i < brush.numplanes;i++)
1001 brush.planes[i].q3surfaceflags = q3surfaceflags;
1002 brush.planes[i].texture = texture;
1007 cnt = (numtriangles + stride - 1) / stride;
1008 for(i = 0; i < cnt; ++i)
1010 if(BoxesOverlap(bbox6f + i * 6, bbox6f + i * 6 + 3, segmentmins, segmentmaxs))
1012 for(k = 0; k < stride; ++k)
1014 tri = i * stride + k;
1015 if(tri >= numtriangles)
1017 VectorCopy(vertex3f + element3i[tri * 3 + 0] * 3, points[0].v);
1018 VectorCopy(vertex3f + element3i[tri * 3 + 1] * 3, points[1].v);
1019 VectorCopy(vertex3f + element3i[tri * 3 + 2] * 3, points[2].v);
1020 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1021 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1022 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1023 //Collision_PrintBrushAsQHull(&brush, "brush");
1024 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1029 else if(stride == 0)
1031 for (i = 0;i < numtriangles;i++, element3i += 3)
1033 if (TriangleBBoxOverlapsBox(vertex3f + element3i[0]*3, vertex3f + element3i[1]*3, vertex3f + element3i[2]*3, segmentmins, segmentmaxs))
1035 VectorCopy(vertex3f + element3i[0] * 3, points[0].v);
1036 VectorCopy(vertex3f + element3i[1] * 3, points[1].v);
1037 VectorCopy(vertex3f + element3i[2] * 3, points[2].v);
1038 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1039 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1040 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1041 //Collision_PrintBrushAsQHull(&brush, "brush");
1042 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1048 for (i = 0;i < numtriangles;i++, element3i += 3)
1050 VectorCopy(vertex3f + element3i[0] * 3, points[0].v);
1051 VectorCopy(vertex3f + element3i[1] * 3, points[1].v);
1052 VectorCopy(vertex3f + element3i[2] * 3, points[2].v);
1053 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1054 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1055 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1056 //Collision_PrintBrushAsQHull(&brush, "brush");
1057 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1062 void Collision_TraceLineTriangleMeshFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, int numtriangles, const int *element3i, const float *vertex3f, int stride, float *bbox6f, int supercontents, int q3surfaceflags, const texture_t *texture, const vec3_t segmentmins, const vec3_t segmentmaxs)
1065 // FIXME: snap vertices?
1069 cnt = (numtriangles + stride - 1) / stride;
1070 for(i = 0; i < cnt; ++i)
1072 if(BoxesOverlap(bbox6f + i * 6, bbox6f + i * 6 + 3, segmentmins, segmentmaxs))
1074 for(k = 0; k < stride; ++k)
1076 tri = i * stride + k;
1077 if(tri >= numtriangles)
1079 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);
1086 for (i = 0;i < numtriangles;i++, element3i += 3)
1087 Collision_TraceLineTriangleFloat(trace, linestart, lineend, vertex3f + element3i[0] * 3, vertex3f + element3i[1] * 3, vertex3f + element3i[2] * 3, supercontents, q3surfaceflags, texture);
1091 void Collision_TraceBrushTriangleFloat(trace_t *trace, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, const float *v0, const float *v1, const float *v2, int supercontents, int q3surfaceflags, const texture_t *texture)
1094 colpointf_t points[3];
1095 colpointf_t edgedirs[3];
1096 colplanef_t planes[5];
1098 memset(&brush, 0, sizeof(brush));
1099 brush.isaabb = false;
1100 brush.hasaabbplanes = false;
1101 brush.numpoints = 3;
1102 brush.numedgedirs = 3;
1103 brush.numplanes = 5;
1104 brush.points = points;
1105 brush.edgedirs = edgedirs;
1106 brush.planes = planes;
1107 brush.supercontents = supercontents;
1108 brush.q3surfaceflags = q3surfaceflags;
1109 brush.texture = texture;
1110 for (i = 0;i < brush.numplanes;i++)
1112 brush.planes[i].q3surfaceflags = q3surfaceflags;
1113 brush.planes[i].texture = texture;
1115 VectorCopy(v0, points[0].v);
1116 VectorCopy(v1, points[1].v);
1117 VectorCopy(v2, points[2].v);
1118 Collision_SnapCopyPoints(brush.numpoints, points, points, COLLISION_SNAPSCALE, COLLISION_SNAP);
1119 Collision_CalcEdgeDirsForPolygonBrushFloat(&brush);
1120 Collision_CalcPlanesForTriangleBrushFloat(&brush);
1121 //Collision_PrintBrushAsQHull(&brush, "brush");
1122 Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, &brush, &brush);
1125 void Collision_BrushForBox(colboxbrushf_t *boxbrush, const vec3_t mins, const vec3_t maxs, int supercontents, int q3surfaceflags, const texture_t *texture)
1128 memset(boxbrush, 0, sizeof(*boxbrush));
1129 boxbrush->brush.isaabb = true;
1130 boxbrush->brush.hasaabbplanes = true;
1131 boxbrush->brush.points = boxbrush->points;
1132 boxbrush->brush.edgedirs = boxbrush->edgedirs;
1133 boxbrush->brush.planes = boxbrush->planes;
1134 boxbrush->brush.supercontents = supercontents;
1135 boxbrush->brush.q3surfaceflags = q3surfaceflags;
1136 boxbrush->brush.texture = texture;
1137 if (VectorCompare(mins, maxs))
1140 boxbrush->brush.numpoints = 1;
1141 boxbrush->brush.numedgedirs = 0;
1142 boxbrush->brush.numplanes = 0;
1143 VectorCopy(mins, boxbrush->brush.points[0].v);
1147 boxbrush->brush.numpoints = 8;
1148 boxbrush->brush.numedgedirs = 3;
1149 boxbrush->brush.numplanes = 6;
1150 // there are 8 points on a box
1151 // there are 3 edgedirs on a box (both signs are tested in collision)
1152 // there are 6 planes on a box
1153 VectorSet(boxbrush->brush.points[0].v, mins[0], mins[1], mins[2]);
1154 VectorSet(boxbrush->brush.points[1].v, maxs[0], mins[1], mins[2]);
1155 VectorSet(boxbrush->brush.points[2].v, mins[0], maxs[1], mins[2]);
1156 VectorSet(boxbrush->brush.points[3].v, maxs[0], maxs[1], mins[2]);
1157 VectorSet(boxbrush->brush.points[4].v, mins[0], mins[1], maxs[2]);
1158 VectorSet(boxbrush->brush.points[5].v, maxs[0], mins[1], maxs[2]);
1159 VectorSet(boxbrush->brush.points[6].v, mins[0], maxs[1], maxs[2]);
1160 VectorSet(boxbrush->brush.points[7].v, maxs[0], maxs[1], maxs[2]);
1161 VectorSet(boxbrush->brush.edgedirs[0].v, 1, 0, 0);
1162 VectorSet(boxbrush->brush.edgedirs[1].v, 0, 1, 0);
1163 VectorSet(boxbrush->brush.edgedirs[2].v, 0, 0, 1);
1164 VectorSet(boxbrush->brush.planes[0].normal, -1, 0, 0);boxbrush->brush.planes[0].dist = -mins[0];
1165 VectorSet(boxbrush->brush.planes[1].normal, 1, 0, 0);boxbrush->brush.planes[1].dist = maxs[0];
1166 VectorSet(boxbrush->brush.planes[2].normal, 0, -1, 0);boxbrush->brush.planes[2].dist = -mins[1];
1167 VectorSet(boxbrush->brush.planes[3].normal, 0, 1, 0);boxbrush->brush.planes[3].dist = maxs[1];
1168 VectorSet(boxbrush->brush.planes[4].normal, 0, 0, -1);boxbrush->brush.planes[4].dist = -mins[2];
1169 VectorSet(boxbrush->brush.planes[5].normal, 0, 0, 1);boxbrush->brush.planes[5].dist = maxs[2];
1170 for (i = 0;i < 6;i++)
1172 boxbrush->brush.planes[i].q3surfaceflags = q3surfaceflags;
1173 boxbrush->brush.planes[i].texture = texture;
1176 boxbrush->brush.supercontents = supercontents;
1177 boxbrush->brush.q3surfaceflags = q3surfaceflags;
1178 boxbrush->brush.texture = texture;
1179 VectorSet(boxbrush->brush.mins, mins[0] - 1, mins[1] - 1, mins[2] - 1);
1180 VectorSet(boxbrush->brush.maxs, maxs[0] + 1, maxs[1] + 1, maxs[2] + 1);
1181 //Collision_ValidateBrush(&boxbrush->brush);
1184 //pseudocode for detecting line/sphere overlap without calculating an impact point
1185 //linesphereorigin = sphereorigin - linestart;linediff = lineend - linestart;linespherefrac = DotProduct(linesphereorigin, linediff) / DotProduct(linediff, linediff);return VectorLength2(linesphereorigin - bound(0, linespherefrac, 1) * linediff) >= sphereradius*sphereradius;
1187 // LordHavoc: currently unused, but tested
1188 // note: this can be used for tracing a moving sphere vs a stationary sphere,
1189 // by simply adding the moving sphere's radius to the sphereradius parameter,
1190 // all the results are correct (impactpoint, impactnormal, and fraction)
1191 float Collision_ClipTrace_Line_Sphere(double *linestart, double *lineend, double *sphereorigin, double sphereradius, double *impactpoint, double *impactnormal)
1193 double dir[3], scale, v[3], deviationdist2, impactdist, linelength;
1194 // make sure the impactpoint and impactnormal are valid even if there is
1196 VectorCopy(lineend, impactpoint);
1197 VectorClear(impactnormal);
1198 // calculate line direction
1199 VectorSubtract(lineend, linestart, dir);
1200 // normalize direction
1201 linelength = VectorLength(dir);
1204 scale = 1.0 / linelength;
1205 VectorScale(dir, scale, dir);
1207 // this dotproduct calculates the distance along the line at which the
1208 // sphere origin is (nearest point to the sphere origin on the line)
1209 impactdist = DotProduct(sphereorigin, dir) - DotProduct(linestart, dir);
1210 // calculate point on line at that distance, and subtract the
1211 // sphereorigin from it, so we have a vector to measure for the distance
1212 // of the line from the sphereorigin (deviation, how off-center it is)
1213 VectorMA(linestart, impactdist, dir, v);
1214 VectorSubtract(v, sphereorigin, v);
1215 deviationdist2 = sphereradius * sphereradius - VectorLength2(v);
1216 // if squared offset length is outside the squared sphere radius, miss
1217 if (deviationdist2 < 0)
1218 return 1; // miss (off to the side)
1219 // nudge back to find the correct impact distance
1220 impactdist -= sqrt(deviationdist2);
1221 if (impactdist >= linelength)
1222 return 1; // miss (not close enough)
1224 return 1; // miss (linestart is past or inside sphere)
1225 // calculate new impactpoint
1226 VectorMA(linestart, impactdist, dir, impactpoint);
1227 // calculate impactnormal (surface normal at point of impact)
1228 VectorSubtract(impactpoint, sphereorigin, impactnormal);
1229 // normalize impactnormal
1230 VectorNormalize(impactnormal);
1231 // return fraction of movement distance
1232 return impactdist / linelength;
1235 void Collision_TraceLineTriangleFloat(trace_t *trace, const vec3_t linestart, const vec3_t lineend, const float *point0, const float *point1, const float *point2, int supercontents, int q3surfaceflags, const texture_t *texture)
1239 float d1, d2, d, f, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, faceplanenormallength2, edge01[3], edge21[3], edge02[3];
1241 // this function executes:
1242 // 32 ops when line starts behind triangle
1243 // 38 ops when line ends infront of triangle
1244 // 43 ops when line fraction is already closer than this triangle
1245 // 72 ops when line is outside edge 01
1246 // 92 ops when line is outside edge 21
1247 // 115 ops when line is outside edge 02
1248 // 123 ops when line impacts triangle and updates trace results
1250 // this code is designed for clockwise triangles, conversion to
1251 // counterclockwise would require swapping some things around...
1252 // it is easier to simply swap the point0 and point2 parameters to this
1253 // function when calling it than it is to rewire the internals.
1255 // calculate the faceplanenormal of the triangle, this represents the front side
1257 VectorSubtract(point0, point1, edge01);
1258 VectorSubtract(point2, point1, edge21);
1259 CrossProduct(edge01, edge21, faceplanenormal);
1260 // there's no point in processing a degenerate triangle (GIGO - Garbage In, Garbage Out)
1262 faceplanenormallength2 = DotProduct(faceplanenormal, faceplanenormal);
1263 if (faceplanenormallength2 < 0.0001f)
1265 // calculate the distance
1267 faceplanedist = DotProduct(point0, faceplanenormal);
1269 // if start point is on the back side there is no collision
1270 // (we don't care about traces going through the triangle the wrong way)
1272 // calculate the start distance
1274 d1 = DotProduct(faceplanenormal, linestart);
1275 if (d1 <= faceplanedist)
1278 // calculate the end distance
1280 d2 = DotProduct(faceplanenormal, lineend);
1281 // if both are in front, there is no collision
1282 if (d2 >= faceplanedist)
1285 // from here on we know d1 is >= 0 and d2 is < 0
1286 // this means the line starts infront and ends behind, passing through it
1288 // calculate the recipricol of the distance delta,
1289 // so we can use it multiple times cheaply (instead of division)
1291 d = 1.0f / (d1 - d2);
1292 // calculate the impact fraction by taking the start distance (> 0)
1293 // and subtracting the face plane distance (this is the distance of the
1294 // triangle along that same normal)
1295 // then multiply by the recipricol distance delta
1297 f = (d1 - faceplanedist) * d;
1298 // skip out if this impact is further away than previous ones
1300 if (f > trace->realfraction)
1302 // 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]);
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)
1313 // first use the two edges from the triangle plane math
1314 // the other edge only gets calculated if the point survives that long
1317 CrossProduct(edge01, faceplanenormal, edgenormal);
1318 if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1322 CrossProduct(faceplanenormal, edge21, edgenormal);
1323 if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1327 VectorSubtract(point0, point2, edge02);
1328 CrossProduct(faceplanenormal, edge02, edgenormal);
1329 if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1334 // store the new trace fraction
1335 trace->realfraction = f;
1337 // calculate a nudged fraction to keep it out of the surface
1338 // (the main fraction remains perfect)
1339 trace->fraction = f - collision_impactnudge.value * d;
1341 if (collision_prefernudgedfraction.integer)
1342 trace->realfraction = trace->fraction;
1344 // store the new trace plane (because collisions only happen from
1345 // the front this is always simply the triangle normal, never flipped)
1346 d = 1.0 / sqrt(faceplanenormallength2);
1347 VectorScale(faceplanenormal, d, trace->plane.normal);
1348 trace->plane.dist = faceplanedist * d;
1350 trace->hitsupercontents = supercontents;
1351 trace->hitq3surfaceflags = q3surfaceflags;
1352 trace->hittexture = texture;
1354 float d1, d2, d, f, fnudged, impact[3], edgenormal[3], faceplanenormal[3], faceplanedist, edge[3];
1356 // this code is designed for clockwise triangles, conversion to
1357 // counterclockwise would require swapping some things around...
1358 // it is easier to simply swap the point0 and point2 parameters to this
1359 // function when calling it than it is to rewire the internals.
1361 // calculate the unnormalized faceplanenormal of the triangle,
1362 // this represents the front side
1363 TriangleNormal(point0, point1, point2, faceplanenormal);
1364 // there's no point in processing a degenerate triangle
1365 // (GIGO - Garbage In, Garbage Out)
1366 if (DotProduct(faceplanenormal, faceplanenormal) < 0.0001f)
1368 // calculate the unnormalized distance
1369 faceplanedist = DotProduct(point0, faceplanenormal);
1371 // calculate the unnormalized start distance
1372 d1 = DotProduct(faceplanenormal, linestart) - faceplanedist;
1373 // if start point is on the back side there is no collision
1374 // (we don't care about traces going through the triangle the wrong way)
1378 // calculate the unnormalized end distance
1379 d2 = DotProduct(faceplanenormal, lineend) - faceplanedist;
1380 // if both are in front, there is no collision
1384 // from here on we know d1 is >= 0 and d2 is < 0
1385 // this means the line starts infront and ends behind, passing through it
1387 // calculate the recipricol of the distance delta,
1388 // so we can use it multiple times cheaply (instead of division)
1389 d = 1.0f / (d1 - d2);
1390 // calculate the impact fraction by taking the start distance (> 0)
1391 // and subtracting the face plane distance (this is the distance of the
1392 // triangle along that same normal)
1393 // then multiply by the recipricol distance delta
1395 // skip out if this impact is further away than previous ones
1396 if (f > trace->realfraction)
1398 // calculate the perfect impact point for classification of insidedness
1399 impact[0] = linestart[0] + f * (lineend[0] - linestart[0]);
1400 impact[1] = linestart[1] + f * (lineend[1] - linestart[1]);
1401 impact[2] = linestart[2] + f * (lineend[2] - linestart[2]);
1403 // calculate the edge normal and reject if impact is outside triangle
1404 // (an edge normal faces away from the triangle, to get the desired normal
1405 // a crossproduct with the faceplanenormal is used, and because of the way
1406 // the insidedness comparison is written it does not need to be normalized)
1408 VectorSubtract(point2, point0, edge);
1409 CrossProduct(edge, faceplanenormal, edgenormal);
1410 if (DotProduct(impact, edgenormal) > DotProduct(point0, edgenormal))
1413 VectorSubtract(point0, point1, edge);
1414 CrossProduct(edge, faceplanenormal, edgenormal);
1415 if (DotProduct(impact, edgenormal) > DotProduct(point1, edgenormal))
1418 VectorSubtract(point1, point2, edge);
1419 CrossProduct(edge, faceplanenormal, edgenormal);
1420 if (DotProduct(impact, edgenormal) > DotProduct(point2, edgenormal))
1423 // store the new trace fraction
1424 trace->realfraction = bound(0, f, 1);
1426 // store the new trace plane (because collisions only happen from
1427 // the front this is always simply the triangle normal, never flipped)
1428 VectorNormalize(faceplanenormal);
1429 VectorCopy(faceplanenormal, trace->plane.normal);
1430 trace->plane.dist = DotProduct(point0, faceplanenormal);
1432 // calculate the normalized start and end distances
1433 d1 = DotProduct(trace->plane.normal, linestart) - trace->plane.dist;
1434 d2 = DotProduct(trace->plane.normal, lineend) - trace->plane.dist;
1436 // calculate a nudged fraction to keep it out of the surface
1437 // (the main fraction remains perfect)
1438 fnudged = (d1 - collision_impactnudge.value) / (d1 - d2);
1439 trace->fraction = bound(0, fnudged, 1);
1441 // store the new trace endpos
1442 // not needed, it's calculated later when the trace is finished
1443 //trace->endpos[0] = linestart[0] + fnudged * (lineend[0] - linestart[0]);
1444 //trace->endpos[1] = linestart[1] + fnudged * (lineend[1] - linestart[1]);
1445 //trace->endpos[2] = linestart[2] + fnudged * (lineend[2] - linestart[2]);
1446 trace->hitsupercontents = supercontents;
1447 trace->hitq3surfaceflags = q3surfaceflags;
1448 trace->hittexture = texture;
1452 void Collision_BoundingBoxOfBrushTraceSegment(const colbrushf_t *start, const colbrushf_t *end, vec3_t mins, vec3_t maxs, float startfrac, float endfrac)
1455 colpointf_t *ps, *pe;
1456 float tempstart[3], tempend[3];
1457 VectorLerp(start->points[0].v, startfrac, end->points[0].v, mins);
1458 VectorCopy(mins, maxs);
1459 for (i = 0, ps = start->points, pe = end->points;i < start->numpoints;i++, ps++, pe++)
1461 VectorLerp(ps->v, startfrac, pe->v, tempstart);
1462 VectorLerp(ps->v, endfrac, pe->v, tempend);
1463 mins[0] = min(mins[0], min(tempstart[0], tempend[0]));
1464 mins[1] = min(mins[1], min(tempstart[1], tempend[1]));
1465 mins[2] = min(mins[2], min(tempstart[2], tempend[2]));
1466 maxs[0] = min(maxs[0], min(tempstart[0], tempend[0]));
1467 maxs[1] = min(maxs[1], min(tempstart[1], tempend[1]));
1468 maxs[2] = min(maxs[2], min(tempstart[2], tempend[2]));
1478 //===========================================
1480 static void Collision_TranslateBrush(const vec3_t shift, colbrushf_t *brush)
1483 // now we can transform the data
1484 for(i = 0; i < brush->numplanes; ++i)
1486 brush->planes[i].dist += DotProduct(shift, brush->planes[i].normal);
1488 for(i = 0; i < brush->numpoints; ++i)
1490 VectorAdd(brush->points[i].v, shift, brush->points[i].v);
1492 VectorAdd(brush->mins, shift, brush->mins);
1493 VectorAdd(brush->maxs, shift, brush->maxs);
1496 static void Collision_TransformBrush(const matrix4x4_t *matrix, colbrushf_t *brush)
1500 // we're breaking any AABB properties here...
1501 brush->isaabb = false;
1502 brush->hasaabbplanes = false;
1503 // now we can transform the data
1504 for(i = 0; i < brush->numplanes; ++i)
1506 Matrix4x4_TransformPositivePlane(matrix, brush->planes[i].normal[0], brush->planes[i].normal[1], brush->planes[i].normal[2], brush->planes[i].dist, brush->planes[i].normal);
1508 for(i = 0; i < brush->numedgedirs; ++i)
1510 Matrix4x4_Transform(matrix, brush->edgedirs[i].v, v);
1511 VectorCopy(v, brush->edgedirs[i].v);
1513 for(i = 0; i < brush->numpoints; ++i)
1515 Matrix4x4_Transform(matrix, brush->points[i].v, v);
1516 VectorCopy(v, brush->points[i].v);
1518 VectorCopy(brush->points[0].v, brush->mins);
1519 VectorCopy(brush->points[0].v, brush->maxs);
1520 for(i = 1; i < brush->numpoints; ++i)
1522 if(brush->points[i].v[0] < brush->mins[0]) brush->mins[0] = brush->points[i].v[0];
1523 if(brush->points[i].v[1] < brush->mins[1]) brush->mins[1] = brush->points[i].v[1];
1524 if(brush->points[i].v[2] < brush->mins[2]) brush->mins[2] = brush->points[i].v[2];
1525 if(brush->points[i].v[0] > brush->maxs[0]) brush->maxs[0] = brush->points[i].v[0];
1526 if(brush->points[i].v[1] > brush->maxs[1]) brush->maxs[1] = brush->points[i].v[1];
1527 if(brush->points[i].v[2] > brush->maxs[2]) brush->maxs[2] = brush->points[i].v[2];
1531 typedef struct collision_cachedtrace_parameters_s
1536 int hitsupercontentsmask;
1539 collision_cachedtrace_parameters_t;
1541 typedef struct collision_cachedtrace_s
1544 collision_cachedtrace_parameters_t p;
1547 collision_cachedtrace_t;
1549 static mempool_t *collision_cachedtrace_mempool;
1550 static collision_cachedtrace_t *collision_cachedtrace_array;
1551 static int collision_cachedtrace_firstfree;
1552 static int collision_cachedtrace_lastused;
1553 static int collision_cachedtrace_max;
1554 static int collision_cachedtrace_sequence;
1555 static int collision_cachedtrace_hashsize;
1556 static int *collision_cachedtrace_hash;
1557 static unsigned int *collision_cachedtrace_arrayfullhashindex;
1558 static unsigned int *collision_cachedtrace_arrayhashindex;
1559 static unsigned int *collision_cachedtrace_arraynext;
1560 static unsigned char *collision_cachedtrace_arrayused;
1561 static qboolean collision_cachedtrace_rebuildhash;
1563 void Collision_Cache_Reset(qboolean resetlimits)
1565 if (collision_cachedtrace_hash)
1566 Mem_Free(collision_cachedtrace_hash);
1567 if (collision_cachedtrace_array)
1568 Mem_Free(collision_cachedtrace_array);
1569 if (collision_cachedtrace_arrayfullhashindex)
1570 Mem_Free(collision_cachedtrace_arrayfullhashindex);
1571 if (collision_cachedtrace_arrayhashindex)
1572 Mem_Free(collision_cachedtrace_arrayhashindex);
1573 if (collision_cachedtrace_arraynext)
1574 Mem_Free(collision_cachedtrace_arraynext);
1575 if (collision_cachedtrace_arrayused)
1576 Mem_Free(collision_cachedtrace_arrayused);
1577 if (resetlimits || !collision_cachedtrace_max)
1578 collision_cachedtrace_max = collision_cache.integer ? 128 : 1;
1579 collision_cachedtrace_firstfree = 1;
1580 collision_cachedtrace_lastused = 0;
1581 collision_cachedtrace_hashsize = collision_cachedtrace_max;
1582 collision_cachedtrace_array = (collision_cachedtrace_t *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(collision_cachedtrace_t));
1583 collision_cachedtrace_hash = (int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_hashsize * sizeof(int));
1584 collision_cachedtrace_arrayfullhashindex = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1585 collision_cachedtrace_arrayhashindex = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1586 collision_cachedtrace_arraynext = (unsigned int *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned int));
1587 collision_cachedtrace_arrayused = (unsigned char *)Mem_Alloc(collision_cachedtrace_mempool, collision_cachedtrace_max * sizeof(unsigned char));
1588 collision_cachedtrace_sequence = 1;
1589 collision_cachedtrace_rebuildhash = false;
1592 void Collision_Cache_Init(mempool_t *mempool)
1594 collision_cachedtrace_mempool = mempool;
1595 Collision_Cache_Reset(true);
1598 static void Collision_Cache_RebuildHash(void)
1601 int range = collision_cachedtrace_lastused + 1;
1602 int sequence = collision_cachedtrace_sequence;
1603 int firstfree = collision_cachedtrace_max;
1605 int *hash = collision_cachedtrace_hash;
1606 unsigned int hashindex;
1607 unsigned int *arrayhashindex = collision_cachedtrace_arrayhashindex;
1608 unsigned int *arraynext = collision_cachedtrace_arraynext;
1609 collision_cachedtrace_rebuildhash = false;
1610 memset(collision_cachedtrace_hash, 0, collision_cachedtrace_hashsize * sizeof(int));
1611 for (index = 1;index < range;index++)
1613 if (collision_cachedtrace_arrayused[index] == sequence)
1615 hashindex = arrayhashindex[index];
1616 arraynext[index] = hash[hashindex];
1617 hash[hashindex] = index;
1622 if (firstfree > index)
1624 collision_cachedtrace_arrayused[index] = 0;
1627 collision_cachedtrace_firstfree = firstfree;
1628 collision_cachedtrace_lastused = lastused;
1631 void Collision_Cache_NewFrame(void)
1633 if (collision_cache.integer)
1635 if (collision_cachedtrace_max < 128)
1636 Collision_Cache_Reset(true);
1640 if (collision_cachedtrace_max > 1)
1641 Collision_Cache_Reset(true);
1643 // rebuild hash if sequence would overflow byte, otherwise increment
1644 if (collision_cachedtrace_sequence == 255)
1646 Collision_Cache_RebuildHash();
1647 collision_cachedtrace_sequence = 1;
1651 collision_cachedtrace_rebuildhash = true;
1652 collision_cachedtrace_sequence++;
1656 static unsigned int Collision_Cache_HashIndexForArray(unsigned int *array, unsigned int size)
1659 unsigned int hashindex = 0;
1660 // this is a super-cheesy checksum, designed only for speed
1661 for (i = 0;i < size;i++)
1662 hashindex += array[i] * (1 + i);
1666 static collision_cachedtrace_t *Collision_Cache_Lookup(dp_model_t *model, const matrix4x4_t *matrix, const matrix4x4_t *inversematrix, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
1669 unsigned int fullhashindex;
1672 int sequence = collision_cachedtrace_sequence;
1673 int *hash = collision_cachedtrace_hash;
1674 unsigned int *arrayfullhashindex = collision_cachedtrace_arrayfullhashindex;
1675 unsigned int *arraynext = collision_cachedtrace_arraynext;
1676 collision_cachedtrace_t *cached = collision_cachedtrace_array + index;
1677 collision_cachedtrace_parameters_t params;
1678 // all non-cached traces use the same index
1679 if (!collision_cache.integer)
1680 r_refdef.stats[r_stat_photoncache_traced]++;
1683 // cached trace lookup
1684 memset(¶ms, 0, sizeof(params));
1685 params.model = model;
1686 VectorCopy(start, params.start);
1687 VectorCopy(end, params.end);
1688 params.hitsupercontentsmask = hitsupercontentsmask;
1689 params.matrix = *matrix;
1690 fullhashindex = Collision_Cache_HashIndexForArray((unsigned int *)¶ms, sizeof(params) / sizeof(unsigned int));
1691 hashindex = (int)(fullhashindex % (unsigned int)collision_cachedtrace_hashsize);
1692 for (index = hash[hashindex];index;index = arraynext[index])
1694 if (arrayfullhashindex[index] != fullhashindex)
1696 cached = collision_cachedtrace_array + index;
1697 //if (memcmp(&cached->p, ¶ms, sizeof(params)))
1698 if (cached->p.model != params.model
1699 || cached->p.end[0] != params.end[0]
1700 || cached->p.end[1] != params.end[1]
1701 || cached->p.end[2] != params.end[2]
1702 || cached->p.start[0] != params.start[0]
1703 || cached->p.start[1] != params.start[1]
1704 || cached->p.start[2] != params.start[2]
1705 || cached->p.hitsupercontentsmask != params.hitsupercontentsmask
1706 || cached->p.matrix.m[0][0] != params.matrix.m[0][0]
1707 || cached->p.matrix.m[0][1] != params.matrix.m[0][1]
1708 || cached->p.matrix.m[0][2] != params.matrix.m[0][2]
1709 || cached->p.matrix.m[0][3] != params.matrix.m[0][3]
1710 || cached->p.matrix.m[1][0] != params.matrix.m[1][0]
1711 || cached->p.matrix.m[1][1] != params.matrix.m[1][1]
1712 || cached->p.matrix.m[1][2] != params.matrix.m[1][2]
1713 || cached->p.matrix.m[1][3] != params.matrix.m[1][3]
1714 || cached->p.matrix.m[2][0] != params.matrix.m[2][0]
1715 || cached->p.matrix.m[2][1] != params.matrix.m[2][1]
1716 || cached->p.matrix.m[2][2] != params.matrix.m[2][2]
1717 || cached->p.matrix.m[2][3] != params.matrix.m[2][3]
1718 || cached->p.matrix.m[3][0] != params.matrix.m[3][0]
1719 || cached->p.matrix.m[3][1] != params.matrix.m[3][1]
1720 || cached->p.matrix.m[3][2] != params.matrix.m[3][2]
1721 || cached->p.matrix.m[3][3] != params.matrix.m[3][3]
1724 // found a matching trace in the cache
1725 r_refdef.stats[r_stat_photoncache_cached]++;
1726 cached->valid = true;
1727 collision_cachedtrace_arrayused[index] = collision_cachedtrace_sequence;
1730 r_refdef.stats[r_stat_photoncache_traced]++;
1731 // find an unused cache entry
1732 for (index = collision_cachedtrace_firstfree, range = collision_cachedtrace_max;index < range;index++)
1733 if (collision_cachedtrace_arrayused[index] == 0)
1737 // all claimed, but probably some are stale...
1738 for (index = 1, range = collision_cachedtrace_max;index < range;index++)
1739 if (collision_cachedtrace_arrayused[index] != sequence)
1743 // found a stale one, rebuild the hash
1744 Collision_Cache_RebuildHash();
1748 // we need to grow the cache
1749 collision_cachedtrace_max *= 2;
1750 Collision_Cache_Reset(false);
1754 // link the new cache entry into the hash bucket
1755 collision_cachedtrace_firstfree = index + 1;
1756 if (collision_cachedtrace_lastused < index)
1757 collision_cachedtrace_lastused = index;
1758 cached = collision_cachedtrace_array + index;
1759 collision_cachedtrace_arraynext[index] = collision_cachedtrace_hash[hashindex];
1760 collision_cachedtrace_hash[hashindex] = index;
1761 collision_cachedtrace_arrayhashindex[index] = hashindex;
1762 cached->valid = false;
1764 collision_cachedtrace_arrayfullhashindex[index] = fullhashindex;
1765 collision_cachedtrace_arrayused[index] = collision_cachedtrace_sequence;
1770 void Collision_Cache_ClipLineToGenericEntitySurfaces(trace_t *trace, dp_model_t *model, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
1772 collision_cachedtrace_t *cached = Collision_Cache_Lookup(model, matrix, inversematrix, start, end, hitsupercontentsmask);
1775 *trace = cached->result;
1779 Collision_ClipLineToGenericEntity(trace, model, NULL, NULL, vec3_origin, vec3_origin, 0, matrix, inversematrix, start, end, hitsupercontentsmask, collision_extendmovelength.value, true);
1781 cached->result = *trace;
1784 void Collision_Cache_ClipLineToWorldSurfaces(trace_t *trace, dp_model_t *model, const vec3_t start, const vec3_t end, int hitsupercontents)
1786 collision_cachedtrace_t *cached = Collision_Cache_Lookup(model, &identitymatrix, &identitymatrix, start, end, hitsupercontents);
1789 *trace = cached->result;
1793 Collision_ClipLineToWorld(trace, model, start, end, hitsupercontents, collision_extendmovelength.value, true);
1795 cached->result = *trace;
1798 typedef struct extendtraceinfo_s
1804 float extendstart[3];
1806 float extenddelta[3];
1809 float scaletoextend;
1814 static void Collision_ClipExtendPrepare(extendtraceinfo_t *extendtraceinfo, trace_t *trace, const vec3_t tstart, const vec3_t tend, float textend)
1816 memset(trace, 0, sizeof(*trace));
1817 trace->fraction = trace->realfraction = 1;
1819 extendtraceinfo->trace = trace;
1820 VectorCopy(tstart, extendtraceinfo->realstart);
1821 VectorCopy(tend, extendtraceinfo->realend);
1822 VectorSubtract(extendtraceinfo->realend, extendtraceinfo->realstart, extendtraceinfo->realdelta);
1823 VectorCopy(extendtraceinfo->realstart, extendtraceinfo->extendstart);
1824 VectorCopy(extendtraceinfo->realend, extendtraceinfo->extendend);
1825 VectorCopy(extendtraceinfo->realdelta, extendtraceinfo->extenddelta);
1826 extendtraceinfo->reallength = VectorLength(extendtraceinfo->realdelta);
1827 extendtraceinfo->extendlength = extendtraceinfo->reallength;
1828 extendtraceinfo->scaletoextend = 1.0f;
1829 extendtraceinfo->extend = textend;
1831 // make the trace longer according to the extend parameter
1832 if (extendtraceinfo->reallength && extendtraceinfo->extend)
1834 extendtraceinfo->extendlength = extendtraceinfo->reallength + extendtraceinfo->extend;
1835 extendtraceinfo->scaletoextend = extendtraceinfo->extendlength / extendtraceinfo->reallength;
1836 VectorMA(extendtraceinfo->realstart, extendtraceinfo->scaletoextend, extendtraceinfo->realdelta, extendtraceinfo->extendend);
1837 VectorSubtract(extendtraceinfo->extendend, extendtraceinfo->extendstart, extendtraceinfo->extenddelta);
1841 static void Collision_ClipExtendFinish(extendtraceinfo_t *extendtraceinfo)
1843 trace_t *trace = extendtraceinfo->trace;
1845 if (trace->fraction != 1.0f)
1847 // undo the extended trace length
1848 trace->fraction *= extendtraceinfo->scaletoextend;
1849 trace->realfraction *= extendtraceinfo->scaletoextend;
1851 // if the extended trace hit something that the unextended trace did not hit (even considering the collision_impactnudge), then we have to clear the hit information
1852 if (trace->fraction > 1.0f)
1854 // note that ent may refer to either startsolid or fraction<1, we can't restore the startsolid ent unfortunately
1856 trace->hitq3surfaceflags = 0;
1857 trace->hitsupercontents = 0;
1858 trace->hittexture = NULL;
1859 VectorClear(trace->plane.normal);
1860 trace->plane.dist = 0.0f;
1865 trace->fraction = bound(0, trace->fraction, 1);
1866 trace->realfraction = bound(0, trace->realfraction, 1);
1868 // calculate the end position
1869 VectorMA(extendtraceinfo->realstart, trace->fraction, extendtraceinfo->realdelta, trace->endpos);
1872 void Collision_ClipToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t tstart, const vec3_t mins, const vec3_t maxs, const vec3_t tend, int hitsupercontentsmask, float extend)
1874 vec3_t starttransformed, endtransformed;
1875 extendtraceinfo_t extendtraceinfo;
1876 Collision_ClipExtendPrepare(&extendtraceinfo, trace, tstart, tend, extend);
1878 Matrix4x4_Transform(inversematrix, extendtraceinfo.extendstart, starttransformed);
1879 Matrix4x4_Transform(inversematrix, extendtraceinfo.extendend, endtransformed);
1880 #if COLLISIONPARANOID >= 3
1881 Con_Printf("trans(%f %f %f -> %f %f %f, %f %f %f -> %f %f %f)", extendtraceinfo.extendstart[0], extendtraceinfo.extendstart[1], extendtraceinfo.extendstart[2], starttransformed[0], starttransformed[1], starttransformed[2], extendtraceinfo.extendend[0], extendtraceinfo.extendend[1], extendtraceinfo.extendend[2], endtransformed[0], endtransformed[1], endtransformed[2]);
1884 if (model && model->TraceBox)
1886 if(model->TraceBrush && (inversematrix->m[0][1] || inversematrix->m[0][2] || inversematrix->m[1][0] || inversematrix->m[1][2] || inversematrix->m[2][0] || inversematrix->m[2][1]))
1888 // we get here if TraceBrush exists, AND we have a rotation component (SOLID_BSP case)
1889 // using starttransformed, endtransformed is WRONG in this case!
1890 // should rather build a brush and trace using it
1891 colboxbrushf_t thisbrush_start, thisbrush_end;
1892 Collision_BrushForBox(&thisbrush_start, mins, maxs, 0, 0, NULL);
1893 Collision_BrushForBox(&thisbrush_end, mins, maxs, 0, 0, NULL);
1894 Collision_TranslateBrush(extendtraceinfo.extendstart, &thisbrush_start.brush);
1895 Collision_TranslateBrush(extendtraceinfo.extendend, &thisbrush_end.brush);
1896 Collision_TransformBrush(inversematrix, &thisbrush_start.brush);
1897 Collision_TransformBrush(inversematrix, &thisbrush_end.brush);
1898 //Collision_TranslateBrush(starttransformed, &thisbrush_start.brush);
1899 //Collision_TranslateBrush(endtransformed, &thisbrush_end.brush);
1900 model->TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
1902 else // this is only approximate if rotated, quite useless
1903 model->TraceBox(model, frameblend, skeleton, trace, starttransformed, mins, maxs, endtransformed, hitsupercontentsmask);
1905 else // and this requires that the transformation matrix doesn't have angles components, like SV_TraceBox ensures; FIXME may get called if a model is SOLID_BSP but has no TraceBox function
1906 Collision_ClipTrace_Box(trace, bodymins, bodymaxs, starttransformed, mins, maxs, endtransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1908 Collision_ClipExtendFinish(&extendtraceinfo);
1911 // NOTE: this relies on plane.dist being directly after plane.normal
1912 Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1915 void Collision_ClipToWorld(trace_t *trace, dp_model_t *model, const vec3_t tstart, const vec3_t mins, const vec3_t maxs, const vec3_t tend, int hitsupercontents, float extend)
1917 extendtraceinfo_t extendtraceinfo;
1918 Collision_ClipExtendPrepare(&extendtraceinfo, trace, tstart, tend, extend);
1919 // ->TraceBox: TraceBrush not needed here, as worldmodel is never rotated
1920 if (model && model->TraceBox)
1921 model->TraceBox(model, NULL, NULL, trace, extendtraceinfo.extendstart, mins, maxs, extendtraceinfo.extendend, hitsupercontents);
1922 Collision_ClipExtendFinish(&extendtraceinfo);
1925 void Collision_ClipLineToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t tstart, const vec3_t tend, int hitsupercontentsmask, float extend, qboolean hitsurfaces)
1927 vec3_t starttransformed, endtransformed;
1928 extendtraceinfo_t extendtraceinfo;
1929 Collision_ClipExtendPrepare(&extendtraceinfo, trace, tstart, tend, extend);
1931 Matrix4x4_Transform(inversematrix, extendtraceinfo.extendstart, starttransformed);
1932 Matrix4x4_Transform(inversematrix, extendtraceinfo.extendend, endtransformed);
1933 #if COLLISIONPARANOID >= 3
1934 Con_Printf("trans(%f %f %f -> %f %f %f, %f %f %f -> %f %f %f)", extendtraceinfo.extendstart[0], extendtraceinfo.extendstart[1], extendtraceinfo.extendstart[2], starttransformed[0], starttransformed[1], starttransformed[2], extendtraceinfo.extendend[0], extendtraceinfo.extendend[1], extendtraceinfo.extendend[2], endtransformed[0], endtransformed[1], endtransformed[2]);
1937 if (model && model->TraceLineAgainstSurfaces && hitsurfaces)
1938 model->TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, starttransformed, endtransformed, hitsupercontentsmask);
1939 else if (model && model->TraceLine)
1940 model->TraceLine(model, frameblend, skeleton, trace, starttransformed, endtransformed, hitsupercontentsmask);
1942 Collision_ClipTrace_Box(trace, bodymins, bodymaxs, starttransformed, vec3_origin, vec3_origin, endtransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1944 Collision_ClipExtendFinish(&extendtraceinfo);
1947 // NOTE: this relies on plane.dist being directly after plane.normal
1948 Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1951 void Collision_ClipLineToWorld(trace_t *trace, dp_model_t *model, const vec3_t tstart, const vec3_t tend, int hitsupercontents, float extend, qboolean hitsurfaces)
1953 extendtraceinfo_t extendtraceinfo;
1954 Collision_ClipExtendPrepare(&extendtraceinfo, trace, tstart, tend, extend);
1956 if (model && model->TraceLineAgainstSurfaces && hitsurfaces)
1957 model->TraceLineAgainstSurfaces(model, NULL, NULL, trace, extendtraceinfo.extendstart, extendtraceinfo.extendend, hitsupercontents);
1958 else if (model && model->TraceLine)
1959 model->TraceLine(model, NULL, NULL, trace, extendtraceinfo.extendstart, extendtraceinfo.extendend, hitsupercontents);
1961 Collision_ClipExtendFinish(&extendtraceinfo);
1964 void Collision_ClipPointToGenericEntity(trace_t *trace, dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, const vec3_t bodymins, const vec3_t bodymaxs, int bodysupercontents, matrix4x4_t *matrix, matrix4x4_t *inversematrix, const vec3_t start, int hitsupercontentsmask)
1966 float starttransformed[3];
1967 memset(trace, 0, sizeof(*trace));
1968 trace->fraction = trace->realfraction = 1;
1970 Matrix4x4_Transform(inversematrix, start, starttransformed);
1971 #if COLLISIONPARANOID >= 3
1972 Con_Printf("trans(%f %f %f -> %f %f %f)", start[0], start[1], start[2], starttransformed[0], starttransformed[1], starttransformed[2]);
1975 if (model && model->TracePoint)
1976 model->TracePoint(model, NULL, NULL, trace, starttransformed, hitsupercontentsmask);
1978 Collision_ClipTrace_Point(trace, bodymins, bodymaxs, starttransformed, hitsupercontentsmask, bodysupercontents, 0, NULL);
1980 VectorCopy(start, trace->endpos);
1982 // NOTE: this relies on plane.dist being directly after plane.normal
1983 Matrix4x4_TransformPositivePlane(matrix, trace->plane.normal[0], trace->plane.normal[1], trace->plane.normal[2], trace->plane.dist, trace->plane.normal);
1986 void Collision_ClipPointToWorld(trace_t *trace, dp_model_t *model, const vec3_t start, int hitsupercontents)
1988 memset(trace, 0, sizeof(*trace));
1989 trace->fraction = trace->realfraction = 1;
1990 if (model && model->TracePoint)
1991 model->TracePoint(model, NULL, NULL, trace, start, hitsupercontents);
1992 VectorCopy(start, trace->endpos);
1995 void Collision_CombineTraces(trace_t *cliptrace, const trace_t *trace, void *touch, qboolean isbmodel)
1997 // take the 'best' answers from the new trace and combine with existing data
1998 if (trace->allsolid)
1999 cliptrace->allsolid = true;
2000 if (trace->startsolid)
2003 cliptrace->bmodelstartsolid = true;
2004 cliptrace->startsolid = true;
2005 if (cliptrace->realfraction == 1)
2006 cliptrace->ent = touch;
2007 if (cliptrace->startdepth > trace->startdepth)
2009 cliptrace->startdepth = trace->startdepth;
2010 VectorCopy(trace->startdepthnormal, cliptrace->startdepthnormal);
2013 // don't set this except on the world, because it can easily confuse
2014 // monsters underwater if there's a bmodel involved in the trace
2015 // (inopen && inwater is how they check water visibility)
2016 //if (trace->inopen)
2017 // cliptrace->inopen = true;
2019 cliptrace->inwater = true;
2020 if ((trace->realfraction < cliptrace->realfraction) && (VectorLength2(trace->plane.normal) > 0))
2022 cliptrace->fraction = trace->fraction;
2023 cliptrace->realfraction = trace->realfraction;
2024 VectorCopy(trace->endpos, cliptrace->endpos);
2025 cliptrace->plane = trace->plane;
2026 cliptrace->ent = touch;
2027 cliptrace->hitsupercontents = trace->hitsupercontents;
2028 cliptrace->hitq3surfaceflags = trace->hitq3surfaceflags;
2029 cliptrace->hittexture = trace->hittexture;
2031 cliptrace->startsupercontents |= trace->startsupercontents;
2034 void Collision_ShortenTrace(trace_t *trace, float shorten_factor, const vec3_t end)
2036 // now undo our moving end 1 qu farther...
2037 trace->fraction = bound(trace->fraction, trace->fraction / shorten_factor - 1e-6, 1); // we subtract 1e-6 to guard for roundoff errors
2038 trace->realfraction = bound(trace->realfraction, trace->realfraction / shorten_factor - 1e-6, 1); // we subtract 1e-6 to guard for roundoff errors
2039 if(trace->fraction >= 1) // trace would NOT hit if not expanded!
2041 trace->fraction = 1;
2042 trace->realfraction = 1;
2043 VectorCopy(end, trace->endpos);
2044 memset(&trace->plane, 0, sizeof(trace->plane));
2046 trace->hitsupercontentsmask = 0;
2047 trace->hitsupercontents = 0;
2048 trace->hitq3surfaceflags = 0;
2049 trace->hittexture = NULL;