Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 2x 2x 2x 15x 15x 15x 15x 1x 14x 14x 4x 10x 10x 2x 18x 18x 18x 18x 15x 15x 15x 10x 10x 18x | import { Vec3 } from 'playcanvas';
export interface AnnotationHitCandidate {
position: Vec3;
radius: number;
}
// Reused across calls: this runs per candidate per frame, where fresh vectors would be steady GC churn.
const scratchDir = new Vec3();
const scratchToCenter = new Vec3();
/**
* Distance along a (normalized) ray to where it first enters the sphere, or null if it never does.
* A ray starting inside the sphere returns 0.
*/
const raySphereEntryDistance = (origin: Vec3, dir: Vec3, center: Vec3, radius: number): number | null => {
const m = scratchToCenter.sub2(origin, center);
const b = m.dot(dir);
const c = m.dot(m) - radius * radius;
if (c > 0 && b > 0) {
return null;
}
const disc = b * b - c;
if (disc < 0) {
return null;
}
const t = -b - Math.sqrt(disc);
return t < 0 ? 0 : t;
};
/**
* Index of the closest candidate sphere the ray enters, or null if it hits none.
*/
export const nearestAnnotationHit = (
origin: Vec3,
direction: Vec3,
candidates: AnnotationHitCandidate[]
): number | null => {
const dir = scratchDir.copy(direction).normalize();
let bestIndex: number | null = null;
let bestDistance = Infinity;
for (let index = 0; index < candidates.length; index++) {
const candidate = candidates[index];
const distance = raySphereEntryDistance(origin, dir, candidate.position, candidate.radius);
if (distance !== null && distance < bestDistance) {
bestDistance = distance;
bestIndex = index;
}
}
return bestIndex;
};
|