3D engine that AI agents drive
Query meshes, shrinkwrap and surface patches without three.js
Nguyen Xuan An8887b9f58ac8
diff --git a/src/mesh-query.js b/src/mesh-query.jsindex b31b2442..9198e7b6 100644--- a/src/mesh-query.js+++ b/src/mesh-query.js@@ -1,5 +1,6 @@-import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Line3, Matrix4, Ray, Triangle, Vector3 } from 'three';-import { MeshBVH, SAH } from 'three-mesh-bvh';+import { mat4, vec3 } from 'gl-matrix';+import { buildTriangleBvh, pointBoxDistance, rayBoxDistance, traverseBvhPairs, traverseTriangleBvh } from './triangle-bvh.js';+import { barycentricWeights, closestPointOnTriangle, intersectRayTriangle, readTriangle, triangleNormal, trianglesIntersect } from './triangle-math.js';const records = new WeakMap();const EPSILON = 1e-9;@@ -9,6 +10,15 @@ const NEAREST_OPTIONS = new Set(['maxDistance', 'maxTriangleTests']);const PROJECT_OPTIONS = new Set(['origin', 'direction', 'maxDistance', 'maxTriangleTests']);const DIRECTIONS = [[0, 0, 1], [1, 0.41421356237, 0.73205080757], [0.61803398875, 1, 0.27182818285], [0.17320508075, 0.44721359550, 1], [-1, 0.31622776602, 0.14142135624], [0.22360679775, -1, 0.70710678118]];+function createVector(x = 0, y = 0, z = 0) {+ return Float64Array.of(x, y, z);+}++// gl-matrix allocates Float32Array unless the caller supplies the output, which would lose precision here.+function createMatrix() {+ return mat4.identity(new Float64Array(16));+}+function optionsObject(options, fields) {if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Query options require an object.');for (const field of Object.keys(options)) if (!fields.has(field)) throw new TypeError(`Unsupported query option ${field}.`);@@ -37,22 +47,76 @@ function live(index) {return record;}-// BVH callbacks must unwind normally: the maintained cast stores module-global traversal state.-function cast(first, second, transform, counter, visitor) {- let failure;- const intersected = first.bvh.bvhcast(second.bvh, transform, {- intersectsTriangles(firstTriangle, secondTriangle, firstIndex, secondIndex) {- try {- counter.charge();- return visitor(firstTriangle, secondTriangle, first.bvh.resolveTriangleIndex(firstIndex), second.bvh.resolveTriangleIndex(secondIndex));- } catch (error) {- failure = error;- return true;- }- },+function isFloat32Triple(input) {+ return (Array.isArray(input) || ArrayBuffer.isView(input)) && input.length === 3 &&+ Array.from(input).every(value => typeof value === 'number' && Number.isFinite(value) && Number.isFinite(Math.fround(value)));+}++function transformPositions(positions, matrix) {+ const moved = new Float64Array(positions.length);+ const point = createVector();+ for (let offset = 0; offset < positions.length; offset += 3) {+ point[0] = positions[offset];+ point[1] = positions[offset + 1];+ point[2] = positions[offset + 2];+ vec3.transformMat4(point, point, matrix);+ moved.set(point, offset);+ }+ return moved;+}++function transformBounds(bounds, matrix) {+ const moved = Float64Array.of(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity);+ const corner = createVector();+ for (let mask = 0; mask < 8; mask++) {+ corner[0] = bounds[mask & 1 ? 3 : 0];+ corner[1] = bounds[mask & 2 ? 4 : 1];+ corner[2] = bounds[mask & 4 ? 5 : 2];+ vec3.transformMat4(corner, corner, matrix);+ for (let axis = 0; axis < 3; axis++) {+ moved[axis] = Math.min(moved[axis], corner[axis]);+ moved[3 + axis] = Math.max(moved[3 + axis], corner[axis]);+ }+ }+ return moved;+}++function boundsContainPoint(bounds, point) {+ for (let axis = 0; axis < 3; axis++) if (point[axis] < bounds[axis] || point[axis] > bounds[3 + axis]) return false;+ return true;+}++function boundsOverlap(first, second) {+ for (let axis = 0; axis < 3; axis++) if (first[axis] > second[3 + axis] || second[axis] > first[3 + axis]) return false;+ return true;+}++function transformDirection(direction, matrix) {+ return createVector(+ matrix[0] * direction[0] + matrix[4] * direction[1] + matrix[8] * direction[2],+ matrix[1] * direction[0] + matrix[5] * direction[1] + matrix[9] * direction[2],+ matrix[2] * direction[0] + matrix[6] * direction[1] + matrix[10] * direction[2],+ );+}++function rotationScaleNorm(matrix) {+ return Math.hypot(...[0, 1, 2, 4, 5, 6, 8, 9, 10].map(index => matrix[index]));+}++function maximumAbsolute(values) {+ return Math.max(...Array.from(values, Math.abs));+}++function castTriangles(first, second, secondToFirst, counter, visitor) {+ const secondPositions = transformPositions(second.positions, secondToFirst);+ const firstTriangle = new Float64Array(9);+ const secondTriangle = new Float64Array(9);+ return traverseBvhPairs(first.bvh, second.bvh, secondPositions, (firstId, secondId) => {+ counter.charge();+ readTriangle(first.positions, first.bvh.indices, firstId, firstTriangle);+ readTriangle(secondPositions, second.bvh.indices, secondId, secondTriangle);+ return visitor(firstTriangle, secondTriangle, firstId, secondId);});- if (failure) throw failure;- return intersected;}function validateGeometry(geometry, maxVertices, maxTriangles) {@@ -65,34 +129,43 @@ function validateGeometry(geometry, maxVertices, maxTriangles) {if (!(positions instanceof Float32Array) || positions.length === 0 || positions.length % 3 !== 0) throw new TypeError('Query positions require nonempty Float32 XYZ vertices.');if (!(indices instanceof Uint32Array) || indices.length === 0 || indices.length % 3 !== 0) throw new TypeError('Query indices require nonempty Uint32 triangles.');if (positions.length / 3 > maxVertices || indices.length / 3 > maxTriangles) throw new RangeError('Geometry exceeds maxVertices or maxTriangles.');- const bounds = new Box3();- const point = new Vector3();+ const low = [Infinity, Infinity, Infinity];+ const high = [-Infinity, -Infinity, -Infinity];for (let offset = 0; offset < positions.length; offset += 3) {- point.fromArray(positions, offset);- if (![point.x, point.y, point.z].every(Number.isFinite)) throw new RangeError('Query positions must remain finite.');- bounds.expandByPoint(point);+ for (let axis = 0; axis < 3; axis++) {+ const value = positions[offset + axis];+ if (!Number.isFinite(value)) throw new RangeError('Query positions must remain finite.');+ low[axis] = Math.min(low[axis], value);+ high[axis] = Math.max(high[axis], value);+ }}for (const index of indices) if (index >= positions.length / 3) throw new RangeError('Query index exceeds the vertex count.');- const center = bounds.getCenter(new Vector3());- const extent = bounds.getSize(new Vector3());- const scale = Math.max(extent.x, extent.y, extent.z);+ const center = createVector(...low.map((value, axis) => (value + high[axis]) / 2));+ const scale = Math.max(...high.map((value, axis) => value - low[axis]));if (scale === 0) throw new RangeError('Query geometry has no drawable extent.');- const first = new Vector3();- const second = new Vector3();- const third = new Vector3();- const cross = new Vector3();+ return { center, scale, minimumAltitude: minimumNormalizedAltitude(positions, indices, scale), vertexCount: positions.length / 3, triangleCount: indices.length / 3 };+}++function minimumNormalizedAltitude(positions, indices, scale) {+ const second = createVector();+ const third = createVector();+ const between = createVector();+ const cross = createVector();let minimumAltitude = Infinity;for (let offset = 0; offset < indices.length; offset += 3) {- first.fromArray(positions, indices[offset] * 3);- second.fromArray(positions, indices[offset + 1] * 3).sub(first).multiplyScalar(1 / scale);- third.fromArray(positions, indices[offset + 2] * 3).sub(first).multiplyScalar(1 / scale);- const longest = Math.max(second.length(), third.length(), first.subVectors(second, third).length());- cross.crossVectors(second, third);- const altitude = Math.hypot(cross.x, cross.y, cross.z) / longest;+ const firstOffset = indices[offset] * 3;+ for (let axis = 0; axis < 3; axis++) {+ second[axis] = (positions[indices[offset + 1] * 3 + axis] - positions[firstOffset + axis]) / scale;+ third[axis] = (positions[indices[offset + 2] * 3 + axis] - positions[firstOffset + axis]) / scale;+ }+ vec3.subtract(between, second, third);+ const longest = Math.max(vec3.length(second), vec3.length(third), vec3.length(between));+ vec3.cross(cross, second, third);+ const altitude = vec3.length(cross) / longest;if (!Number.isFinite(altitude) || altitude <= 1e-8) throw new RangeError('Query triangle is degenerate or below the normalized precision domain.');minimumAltitude = Math.min(minimumAltitude, altitude);}- return { center, scale, minimumAltitude, vertexCount: positions.length / 3, triangleCount: indices.length / 3 };+ return minimumAltitude;}function topology(geometry) {@@ -159,47 +232,57 @@ function topology(geometry) {return triangles;}+function subtractPoints(first, second) {+ return vec3.subtract(createVector(), first, second);+}++function cornerOf(triangle, corner) {+ return createVector(triangle[corner * 3], triangle[corner * 3 + 1], triangle[corner * 3 + 2]);+}+function coneContains(origin, first, second, point, normal) {- const edgeA = first.clone().sub(origin);- const edgeB = second.clone().sub(origin);- const direction = point.clone().sub(origin);- const cross = new Vector3();- const denominator = cross.crossVectors(edgeA, edgeB).dot(normal);- const firstWeight = cross.crossVectors(direction, edgeB).dot(normal) / denominator;- const secondWeight = cross.crossVectors(edgeA, direction).dot(normal) / denominator;+ const edgeA = subtractPoints(first, origin);+ const edgeB = subtractPoints(second, origin);+ const direction = subtractPoints(point, origin);+ const cross = createVector();+ const denominator = vec3.dot(vec3.cross(cross, edgeA, edgeB), normal);+ const firstWeight = vec3.dot(vec3.cross(cross, direction, edgeB), normal) / denominator;+ const secondWeight = vec3.dot(vec3.cross(cross, edgeA, direction), normal) / denominator;return firstWeight >= -EPSILON && secondWeight >= -EPSILON;}function validateSelfIntersections(record, welded, maximum) {const counter = budget(maximum, 'maxValidationPairs');- const segment = new Line3();- cast(record, record, new Matrix4(), counter, (first, second, firstId, secondId) => {+ const segment = new Float64Array(6);+ castTriangles(record, record, createMatrix(), counter, (first, second, firstId, secondId) => {if (firstId >= secondId) return false;- if (!first.intersectsTriangle(second, segment, true)) return false;+ if (!trianglesIntersect(first, second, segment)) return false;const firstIds = Array.from(welded.subarray(firstId * 3, firstId * 3 + 3));const secondIds = Array.from(welded.subarray(secondId * 3, secondId * 3 + 3));const shared = firstIds.filter(index => secondIds.includes(index));if (shared.length === 0 || shared.length === 3) throw new RangeError('Solid boundary intersects itself.');- const firstPoints = [first.a, first.b, first.c];- const secondPoints = [second.a, second.b, second.c];- const firstNormal = first.getNormal(new Vector3());- const secondNormal = second.getNormal(new Vector3());- const coplanar = new Vector3().crossVectors(firstNormal, secondNormal).length() <= EPSILON;+ const firstPoints = [0, 1, 2].map(corner => cornerOf(first, corner));+ const secondPoints = [0, 1, 2].map(corner => cornerOf(second, corner));+ const firstNormal = triangleNormal(first, createVector());+ const secondNormal = triangleNormal(second, createVector());+ const coplanar = vec3.length(vec3.cross(createVector(), firstNormal, secondNormal)) <= EPSILON;if (shared.length === 2) {if (coplanar) {const origin = firstPoints[firstIds.indexOf(shared[0])];- const edge = firstPoints[firstIds.indexOf(shared[1])].clone().sub(origin);- const firstTip = firstPoints[firstIds.findIndex(index => !shared.includes(index))].clone().sub(origin);- const secondTip = secondPoints[secondIds.findIndex(index => !shared.includes(index))].clone().sub(origin);- const firstSide = new Vector3().crossVectors(edge, firstTip).dot(firstNormal);- const secondSide = new Vector3().crossVectors(edge, secondTip).dot(firstNormal);+ const edge = subtractPoints(firstPoints[firstIds.indexOf(shared[1])], origin);+ const firstTip = subtractPoints(firstPoints[firstIds.findIndex(index => !shared.includes(index))], origin);+ const secondTip = subtractPoints(secondPoints[secondIds.findIndex(index => !shared.includes(index))], origin);+ const firstSide = vec3.dot(vec3.cross(createVector(), edge, firstTip), firstNormal);+ const secondSide = vec3.dot(vec3.cross(createVector(), edge, secondTip), firstNormal);if (firstSide * secondSide >= 0) throw new RangeError('Solid adjacent faces overlap or have ambiguous coplanar sides.');}return false;}const origin = firstPoints[firstIds.indexOf(shared[0])];if (!coplanar) {- if (segment.start.distanceTo(origin) > EPSILON || segment.end.distanceTo(origin) > EPSILON) throw new RangeError('Solid faces intersect beyond their shared vertex.');+ const segmentStart = segment.subarray(0, 3);+ const segmentEnd = segment.subarray(3, 6);+ if (vec3.distance(segmentStart, origin) > EPSILON || vec3.distance(segmentEnd, origin) > EPSILON) throw new RangeError('Solid faces intersect beyond their shared vertex.');return false;}const firstOther = firstPoints.filter((point, index) => firstIds[index] !== shared[0]);@@ -219,69 +302,66 @@ function matrixState(record, values) {return Math.fround(value);});if (elements[3] !== 0 || elements[7] !== 0 || elements[11] !== 0 || elements[15] !== 1) throw new RangeError('Query matrix must be affine.');- const matrix = new Matrix4().fromArray(elements).multiply(record.normalization);- const determinant = matrix.determinant();+ const matrix = mat4.multiply(createMatrix(), Float64Array.from(elements), record.normalization);+ const determinant = mat4.determinant(matrix);if (!Number.isFinite(determinant) || determinant === 0) throw new RangeError('Query matrix must be nonsingular.');- const inverse = matrix.clone().invert();- if (!inverse.elements.every(Number.isFinite)) throw new RangeError('Query matrix inverse exceeds the precision domain.');- const bounds = record.bounds.clone().applyMatrix4(matrix);- const coordinates = [...bounds.min.toArray(), ...bounds.max.toArray()];- if (!coordinates.every(value => Number.isFinite(value) && Number.isFinite(Math.fround(value)))) throw new RangeError('Query world coordinates exceed finite Float32 bounds.');- const inverseNorm = Math.hypot(...[0, 1, 2, 4, 5, 6, 8, 9, 10].map(index => inverse.elements[index]));- const resolution = Math.max(...coordinates.map(Math.abs)) * 2 ** -21 + 2 ** -149;- if (record.minimumAltitude / inverseNorm <= resolution) throw new RangeError('Query transformed triangles collapse within the Float32 precision domain.');+ const inverse = mat4.invert(createMatrix(), matrix);+ if (!inverse || !inverse.every(Number.isFinite)) throw new RangeError('Query matrix inverse exceeds the precision domain.');+ const bounds = transformBounds(record.bounds, matrix);+ if (!bounds.every(value => Number.isFinite(value) && Number.isFinite(Math.fround(value)))) throw new RangeError('Query world coordinates exceed finite Float32 bounds.');+ const resolution = maximumAbsolute(bounds) * 2 ** -21 + 2 ** -149;+ if (record.minimumAltitude / rotationScaleNorm(inverse) <= resolution) throw new RangeError('Query transformed triangles collapse within the Float32 precision domain.');return { matrix, inverse, bounds };}function relativeState(second, transform) {- const inverse = transform.clone().invert();- const inverseNorm = Math.hypot(...[0, 1, 2, 4, 5, 6, 8, 9, 10].map(index => inverse.elements[index]));- const bounds = second.bounds.clone().applyMatrix4(transform);- const maximum = Math.max(...bounds.min.toArray().map(Math.abs), ...bounds.max.toArray().map(Math.abs));+ const inverse = mat4.invert(createMatrix(), transform);+ const inverseNorm = inverse ? rotationScaleNorm(inverse) : 0;+ const maximum = maximumAbsolute(transformBounds(second.bounds, transform));if (!Number.isFinite(maximum) || maximum > 1e6 || second.minimumAltitude / inverseNorm <= 1e-8) {throw new RangeError('Relative mesh transform exceeds the normalized triangle precision domain.');}}function containment(record, point, counter) {- if (!record.bounds.containsPoint(point)) return { inside: false, attempts: 0 };+ if (!boundsContainPoint(record.bounds, point)) return { inside: false, attempts: 0 };+ const triangle = new Float64Array(9);+ const normal = createVector();+ const hit = createVector();+ const weights = createVector();let previous;let accepted = 0;let attempts = 0;for (const direction of DIRECTIONS) {attempts++;- const ray = new Ray(point, new Vector3(...direction).normalize());- const hit = new Vector3();- const weights = new Vector3();- const normal = new Vector3();+ const rayDirection = vec3.normalize(createVector(), direction);let count = 0;let ambiguous = false;- let failure;- record.bvh.shapecast({- intersectsBounds: bounds => ray.intersectsBox(bounds),- intersectsTriangle(triangle) {- try {- counter.charge();- triangle.getNormal(normal);- if (Math.abs(normal.dot(ray.direction)) <= EPSILON && Math.abs(normal.dot(point.clone().sub(triangle.a))) <= EPSILON) {- ambiguous = true;- return true;- }- if (!ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, hit)) return false;- triangle.getBarycoord(hit, weights);- if (hit.distanceTo(point) <= EPSILON || Math.min(weights.x, weights.y, weights.z) <= EPSILON) {- ambiguous = true;- return true;- }- count++;- return false;- } catch (error) {- failure = error;+ traverseTriangleBvh(+ record.bvh,+ (bounds, offset) => rayBoxDistance(point, rayDirection, bounds, offset),+ score => Number.isFinite(score),+ triangleId => {+ counter.charge();+ readTriangle(record.positions, record.bvh.indices, triangleId, triangle);+ triangleNormal(triangle, normal);+ const offsetFromCorner = subtractPoints(point, cornerOf(triangle, 0));+ if (Math.abs(vec3.dot(normal, rayDirection)) <= EPSILON && Math.abs(vec3.dot(normal, offsetFromCorner)) <= EPSILON) {+ ambiguous = true;+ return true;+ }+ const distance = intersectRayTriangle(point, rayDirection, triangle);+ if (distance < 0) return false;+ vec3.scaleAndAdd(hit, point, rayDirection, distance);+ barycentricWeights(hit, triangle, weights);+ if (distance <= EPSILON || Math.min(weights[0], weights[1], weights[2]) <= EPSILON) {+ ambiguous = true;return true;}+ count++;+ return false;},- });- if (failure) throw failure;+ );if (ambiguous) continue;const inside = count % 2 === 1;if (accepted && previous !== inside) throw new RangeError('Solid containment has inconsistent ray witnesses.');@@ -293,27 +373,24 @@ function containment(record, point, counter) {}function localVector(input, name) {- if ((!Array.isArray(input) && !ArrayBuffer.isView(input)) || input.length !== 3 ||- !Array.from(input).every(value => typeof value === 'number' && Number.isFinite(value) && Number.isFinite(Math.fround(value)))) {- throw new TypeError(`${name} requires three finite Float32-representable components.`);- }- return new Vector3(...input);+ if (!isFloat32Triple(input)) throw new TypeError(`${name} requires three finite Float32-representable components.`);+ return createVector(...input);}function queryLocalSurface(record, pointInput, directionInput, options) {const originalPoint = localVector(pointInput, 'Query point');- const point = originalPoint.clone().sub(record.center).multiplyScalar(1 / record.scale);- if (Math.max(...point.toArray().map(Math.abs)) > 1e6) throw new RangeError('Query point exceeds the normalized precision domain.');+ const point = vec3.scale(createVector(), subtractPoints(originalPoint, record.center), 1 / record.scale);+ if (maximumAbsolute(point) > 1e6) throw new RangeError('Query point exceeds the normalized precision domain.');const maximum = options.maxDistance ?? Infinity;if ((maximum !== Infinity && (!Number.isFinite(maximum) || !Number.isFinite(Math.fround(maximum)))) || maximum < 0) {throw new RangeError('maxDistance must be nonnegative and Float32-representable, or Infinity.');}const counter = budget(integer(options.maxTriangleTests ?? 2_000_000, 100_000_000, 'maxTriangleTests'), 'maxTriangleTests');- let ray;+ let rayDirection;if (directionInput !== undefined) {const direction = localVector(directionInput, 'Projection direction');- if (direction.length() === 0) throw new RangeError('Projection direction must be nonzero.');- ray = new Ray(point, direction.normalize());+ if (vec3.length(direction) === 0) throw new RangeError('Projection direction must be nonzero.');+ rayDirection = vec3.normalize(direction, direction);}let bestDistance = maximum / record.scale;let bestLocalDistance = maximum;@@ -321,56 +398,105 @@ function queryLocalSurface(record, pointInput, directionInput, options) {let bestPoint;let bestNormal;let bestWeights;- let failure;- const candidate = new Vector3();- const candidateLocal = new Vector3();- const boundsPoint = new Vector3();- record.bvh.shapecast({- boundsTraverseOrder(bounds) {- if (!ray) return bounds.clampPoint(point, boundsPoint).distanceTo(point);- // Ray.intersectBox returns the exit when the origin is inside. The lower bound is zero there.- if (bounds.containsPoint(point)) return 0;- return ray.intersectBox(bounds, boundsPoint) ? boundsPoint.distanceTo(point) : Infinity;- },- intersectsBounds: (bounds, leaf, score) => Number.isFinite(score) && score <= bestDistance + EPSILON,- intersectsTriangle(triangle, triangleIndex) {- try {- counter.charge();- if (ray) {- if (!ray.intersectTriangle(triangle.a, triangle.b, triangle.c, false, candidate)) return false;- } else {- triangle.closestPointToPoint(point, candidate);- }- const distance = candidate.distanceTo(point);- if (!Number.isFinite(distance)) throw new RangeError('Surface query exceeds the numerical precision domain.');- candidateLocal.copy(candidate).multiplyScalar(record.scale).add(record.center);- const localDistance = candidateLocal.distanceTo(originalPoint);- // Apply the caller's cutoff in its original frame, avoiding normalized subtraction at exact endpoints.- if (localDistance > bestLocalDistance || (localDistance === bestLocalDistance && triangleIndex >= bestTriangle)) return false;- const weights = triangle.getBarycoord(candidate, new Vector3());- const normal = triangle.getNormal(new Vector3());- if (!weights || !weights.toArray().every(Number.isFinite) || normal.length() === 0) throw new RangeError('Surface query has invalid triangle coordinates.');- bestDistance = distance;- bestLocalDistance = localDistance;- bestTriangle = triangleIndex;- bestPoint = candidateLocal.clone();- bestWeights = weights;- bestNormal = normal;- return false;- } catch (error) {- failure = error;- return true;+ const triangle = new Float64Array(9);+ const candidate = createVector();+ const candidateLocal = createVector();+ traverseTriangleBvh(+ record.bvh,+ (bounds, offset) => rayDirection ? rayBoxDistance(point, rayDirection, bounds, offset) : pointBoxDistance(point, bounds, offset),+ score => Number.isFinite(score) && score <= bestDistance + EPSILON,+ triangleId => {+ counter.charge();+ readTriangle(record.positions, record.bvh.indices, triangleId, triangle);+ if (rayDirection) {+ const hitDistance = intersectRayTriangle(point, rayDirection, triangle);+ if (hitDistance < 0) return false;+ vec3.scaleAndAdd(candidate, point, rayDirection, hitDistance);+ } else {+ closestPointOnTriangle(point, triangle, candidate);}+ const distance = vec3.distance(candidate, point);+ if (!Number.isFinite(distance)) throw new RangeError('Surface query exceeds the numerical precision domain.');+ vec3.add(candidateLocal, vec3.scale(candidateLocal, candidate, record.scale), record.center);+ const localDistance = vec3.distance(candidateLocal, originalPoint);+ // Apply the caller's cutoff in its original frame, avoiding normalized subtraction at exact endpoints.+ if (localDistance > bestLocalDistance || (localDistance === bestLocalDistance && triangleId >= bestTriangle)) return false;+ const weights = barycentricWeights(candidate, triangle, createVector());+ const normal = triangleNormal(triangle, createVector());+ if (!weights || !weights.every(Number.isFinite) || vec3.length(normal) === 0) throw new RangeError('Surface query has invalid triangle coordinates.');+ bestDistance = distance;+ bestLocalDistance = localDistance;+ bestTriangle = triangleId;+ bestPoint = Float64Array.from(candidateLocal);+ bestWeights = weights;+ bestNormal = normal;+ return false;},- });- if (failure) throw failure;+ );if (!bestPoint) return { hit: null, triangleTests: counter.tests };const distance = bestLocalDistance;- if (!Number.isFinite(distance) || !bestPoint.toArray().every(value => Number.isFinite(Math.fround(value)))) throw new RangeError('Surface query hit exceeds finite Float32 coordinates.');- return { hit: { point: bestPoint.toArray(), distance, triangle: bestTriangle, barycentric: bestWeights.toArray(), normal: bestNormal.toArray() }, triangleTests: counter.tests };+ if (!Number.isFinite(distance) || !bestPoint.every(value => Number.isFinite(Math.fround(value)))) throw new RangeError('Surface query hit exceeds finite Float32 coordinates.');+ return { hit: { point: Array.from(bestPoint), distance, triangle: bestTriangle, barycentric: Array.from(bestWeights), normal: Array.from(bestNormal) }, triangleTests: counter.tests };+}++function nearestRayHit(record, origin, direction) {+ const triangle = new Float64Array(9);+ let bestDistance = Infinity;+ let bestTriangle = -1;+ traverseTriangleBvh(+ record.bvh,+ (bounds, offset) => rayBoxDistance(origin, direction, bounds, offset),+ score => Number.isFinite(score) && score <= bestDistance,+ triangleId => {+ readTriangle(record.positions, record.bvh.indices, triangleId, triangle);+ const distance = intersectRayTriangle(origin, direction, triangle);+ if (distance >= 0 && distance < bestDistance) {+ bestDistance = distance;+ bestTriangle = triangleId;+ }+ return false;+ },+ );+ if (bestTriangle < 0) return null;+ return { triangle: bestTriangle, point: vec3.scaleAndAdd(createVector(), origin, direction, bestDistance) };+}++function readRayField(ray, field) {+ const input = ray[field];+ if (!isFloat32Triple(input)) throw new TypeError(`Ray ${field} requires three finite Float32 values.`);+ return createVector(...Array.from(input, Math.fround));+}++function raycastIndex(current, matrix, ray) {+ const state = matrixState(current, matrix);+ if (!ray || typeof ray !== 'object') throw new TypeError('ray requires origin and direction.');+ const origin = readRayField(ray, 'origin');+ const direction = readRayField(ray, 'direction');+ if (vec3.length(direction) === 0) throw new RangeError('Ray direction must be nonzero.');+ const maximum = ray.maxDistance ?? Infinity;+ if ((maximum !== Infinity && !Number.isFinite(maximum)) || maximum < 0) throw new RangeError('Ray maxDistance must be nonnegative.');+ const localOrigin = vec3.transformMat4(createVector(), origin, state.inverse);+ const localDirection = vec3.normalize(createVector(), transformDirection(vec3.normalize(createVector(), direction), state.inverse));+ if (maximumAbsolute(localOrigin) > 1e6) throw new RangeError('Ray origin exceeds the normalized query precision domain.');+ const result = nearestRayHit(current, localOrigin, localDirection);+ if (!result) return null;+ const worldPoint = vec3.transformMat4(createVector(), result.point, state.matrix);+ const distance = vec3.distance(worldPoint, origin);+ if (!Number.isFinite(distance) || !worldPoint.every(value => Number.isFinite(Math.fround(value)))) throw new RangeError('Ray hit exceeds finite world coordinates.');+ if (distance > maximum) return null;+ const triangle = new Float64Array(9);+ readTriangle(current.positions, current.bvh.indices, result.triangle, triangle);+ const weights = barycentricWeights(result.point, triangle, createVector());+ if (!weights || !weights.every(Number.isFinite)) throw new RangeError('Ray barycentric coordinates exceed the query precision domain.');+ return { point: Array.from(worldPoint), distance, triangle: result.triangle, barycentric: Array.from(weights) };}-/** Copies static geometry into a private normalized BVH. Returned handles expose no Three.js objects. */+function firstVertexIn(record, transform) {+ const offset = record.bvh.indices[0] * 3;+ return vec3.transformMat4(createVector(), record.positions.subarray(offset, offset + 3), transform);+}++/** Copies static geometry into a private normalized BVH. Returned handles expose no mesh internals. */export function createMeshQueryIndex(geometry, options = {}) {optionsObject(options, INDEX_OPTIONS);const maxTriangles = integer(options.maxTriangles ?? 250_000, 1_000_000, 'maxTriangles');@@ -384,78 +510,47 @@ export function createMeshQueryIndex(geometry, options = {}) {const reservedBytes = metadata.vertexCount * (solid ? 152 : 24) + metadata.triangleCount * (solid ? 512 : 128);if (reservedBytes > memoryBudgetMiB * 1024 * 1024) throw new RangeError('Mesh query allocation estimate exceeds memoryBudgetMiB.');const welded = solid ? topology(geometry) : null;- const source = new BufferGeometry();const positions = new Float64Array(geometry.positions.length);for (let offset = 0; offset < positions.length; offset += 3) {- for (let axis = 0; axis < 3; axis++) positions[offset + axis] = (geometry.positions[offset + axis] - metadata.center.getComponent(axis)) / metadata.scale;+ for (let axis = 0; axis < 3; axis++) positions[offset + axis] = (geometry.positions[offset + axis] - metadata.center[axis]) / metadata.scale;}- source.setAttribute('position', new BufferAttribute(positions, 3));- source.setIndex(new BufferAttribute(new Uint32Array(geometry.indices), 1));- const normalization = new Matrix4().makeScale(metadata.scale, metadata.scale, metadata.scale).setPosition(metadata.center);- const record = { ...metadata, normalization, geometry: source, bounds: new Box3().setFromBufferAttribute(source.attributes.position), bvh: null, disposed: false, solid };- try {- record.bvh = new MeshBVH(source, { indirect: true, strategy: SAH, maxDepth: 64, targetLeafSize: 8, verbose: false });- const validationPairs = solid ? validateSelfIntersections(record, welded, maxValidationPairs) : 0;- const memoryPlan = Object.freeze({ reservedBytes, memoryBudgetMiB, vertexCount: metadata.vertexCount, triangleCount: metadata.triangleCount, validationPairs });- const handle = Object.freeze({- solid,- memoryPlan,- info: Object.freeze({ vertexCount: metadata.vertexCount, triangleCount: metadata.triangleCount, estimatedBytes: reservedBytes }),- nearest(point, options = {}) {- optionsObject(options, NEAREST_OPTIONS);- return queryLocalSurface(live(handle), point, undefined, options);- },- project(ray) {- optionsObject(ray, PROJECT_OPTIONS);- if (ray.direction === undefined) throw new TypeError('Projection requires direction.');- return queryLocalSurface(live(handle), ray.origin, ray.direction, ray);- },- raycast(matrix, ray) {- const current = live(handle);- const state = matrixState(current, matrix);- if (!ray || typeof ray !== 'object') throw new TypeError('ray requires origin and direction.');- const read = field => {- const input = ray[field];- if ((!Array.isArray(input) && !ArrayBuffer.isView(input)) || input.length !== 3 || !Array.from(input).every(value => typeof value === 'number' && Number.isFinite(value) && Number.isFinite(Math.fround(value)))) throw new TypeError(`Ray ${field} requires three finite Float32 values.`);- return new Vector3(...Array.from(input, Math.fround));- };- const origin = read('origin');- const direction = read('direction');- if (direction.length() === 0) throw new RangeError('Ray direction must be nonzero.');- const maximum = ray.maxDistance ?? Infinity;- if ((maximum !== Infinity && !Number.isFinite(maximum)) || maximum < 0) throw new RangeError('Ray maxDistance must be nonnegative.');- const localRay = new Ray(origin.clone(), direction.normalize()).applyMatrix4(state.inverse);- if (Math.max(...localRay.origin.toArray().map(Math.abs)) > 1e6) throw new RangeError('Ray origin exceeds the normalized query precision domain.');- const result = current.bvh.raycastFirst(localRay, DoubleSide);- if (!result) return null;- const worldPoint = result.point.clone().applyMatrix4(state.matrix);- const distance = worldPoint.distanceTo(origin);- if (!Number.isFinite(distance) || !worldPoint.toArray().every(value => Number.isFinite(Math.fround(value)))) throw new RangeError('Ray hit exceeds finite world coordinates.');- if (distance > maximum) return null;- const triangle = result.faceIndex;- const positions = current.geometry.attributes.position;- const ids = current.geometry.index;- const first = new Vector3().fromBufferAttribute(positions, ids.getX(triangle * 3));- const second = new Vector3().fromBufferAttribute(positions, ids.getX(triangle * 3 + 1));- const third = new Vector3().fromBufferAttribute(positions, ids.getX(triangle * 3 + 2));- const weights = new Triangle(first, second, third).getBarycoord(result.point, new Vector3());- if (!weights || !weights.toArray().every(Number.isFinite)) throw new RangeError('Ray barycentric coordinates exceed the query precision domain.');- return { point: worldPoint.toArray(), distance, triangle, barycentric: weights.toArray() };- },- dispose() {- if (record.disposed) return;- record.disposed = true;- record.geometry.dispose();- record.geometry = null;- record.bvh = null;- },- });- records.set(handle, record);- return handle;- } catch (error) {- source.dispose();- throw error;+ const normalization = Float64Array.of(metadata.scale, 0, 0, 0, 0, metadata.scale, 0, 0, 0, 0, metadata.scale, 0, metadata.center[0], metadata.center[1], metadata.center[2], 1);+ const bounds = Float64Array.of(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity);+ for (let offset = 0; offset < positions.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) {+ bounds[axis] = Math.min(bounds[axis], positions[offset + axis]);+ bounds[3 + axis] = Math.max(bounds[3 + axis], positions[offset + axis]);+ }}+ const bvh = buildTriangleBvh(positions, new Uint32Array(geometry.indices), { leafSize: 8, maxDepth: 64 });+ const record = { ...metadata, normalization, positions, bounds, bvh, disposed: false, solid };+ const validationPairs = solid ? validateSelfIntersections(record, welded, maxValidationPairs) : 0;+ const memoryPlan = Object.freeze({ reservedBytes, memoryBudgetMiB, vertexCount: metadata.vertexCount, triangleCount: metadata.triangleCount, validationPairs });+ const handle = Object.freeze({+ solid,+ memoryPlan,+ info: Object.freeze({ vertexCount: metadata.vertexCount, triangleCount: metadata.triangleCount, estimatedBytes: reservedBytes }),+ nearest(point, options = {}) {+ optionsObject(options, NEAREST_OPTIONS);+ return queryLocalSurface(live(handle), point, undefined, options);+ },+ project(ray) {+ optionsObject(ray, PROJECT_OPTIONS);+ if (ray.direction === undefined) throw new TypeError('Projection requires direction.');+ return queryLocalSurface(live(handle), ray.origin, ray.direction, ray);+ },+ raycast(matrix, ray) {+ return raycastIndex(live(handle), matrix, ray);+ },+ dispose() {+ if (record.disposed) return;+ record.disposed = true;+ record.positions = null;+ record.bvh = null;+ },+ });+ records.set(handle, record);+ return handle;}/** Surface contacts are not proof of volume penetration. Closed solids additionally test containment. */@@ -474,14 +569,14 @@ export function createMeshPairQuery(indexA, indexB, options = {}) {const stateA = matrixState(currentA, matrixA);const stateB = matrixState(currentB, matrixB);const result = { kind: mode === 'surfaces' ? 'surface-disjoint' : 'separate', solidRelation: mode === 'surfaces' ? 'not-tested' : 'outside', triangles: null, triangleTests: 0, rayAttempts: 0 };- if (!stateA.bounds.intersectsBox(stateB.bounds)) return result;- const relativeB = stateA.inverse.clone().multiply(stateB.matrix);- const relativeA = stateB.inverse.clone().multiply(stateA.matrix);+ if (!boundsOverlap(stateA.bounds, stateB.bounds)) return result;+ const relativeB = mat4.multiply(createMatrix(), stateA.inverse, stateB.matrix);+ const relativeA = mat4.multiply(createMatrix(), stateB.inverse, stateA.matrix);relativeState(currentB, relativeB);relativeState(currentA, relativeA);const counter = budget(maximum, 'maxTriangleTests');- const contact = cast(currentA, currentB, relativeB, counter, (firstTriangle, secondTriangle, firstId, secondId) => {- if (!firstTriangle.intersectsTriangle(secondTriangle)) return false;+ const contact = castTriangles(currentA, currentB, relativeB, counter, (firstTriangle, secondTriangle, firstId, secondId) => {+ if (!trianglesIntersect(firstTriangle, secondTriangle)) return false;result.triangles = [firstId, secondId];return true;});@@ -489,10 +584,8 @@ export function createMeshPairQuery(indexA, indexB, options = {}) {result.kind = 'surface-intersection';result.solidRelation = mode === 'surfaces' ? 'not-tested' : 'boundaries-intersect';} else if (mode === 'closed-solids') {- const pointA = new Vector3().fromBufferAttribute(currentA.geometry.attributes.position, currentA.geometry.index.getX(0)).applyMatrix4(relativeA);- const pointB = new Vector3().fromBufferAttribute(currentB.geometry.attributes.position, currentB.geometry.index.getX(0)).applyMatrix4(relativeB);- const firstInside = containment(currentB, pointA, counter);- const secondInside = containment(currentA, pointB, counter);+ const firstInside = containment(currentB, firstVertexIn(currentA, relativeA), counter);+ const secondInside = containment(currentA, firstVertexIn(currentB, relativeB), counter);result.rayAttempts = firstInside.attempts + secondInside.attempts;if (firstInside.inside && secondInside.inside) throw new RangeError('Solid containment witnesses are inconsistent.');if (firstInside.inside || secondInside.inside) {diff --git a/src/shrinkwrap.js b/src/shrinkwrap.jsindex f7ed94f2..646dfdb4 100644--- a/src/shrinkwrap.js+++ b/src/shrinkwrap.js@@ -1,4 +1,4 @@-import { Matrix3, Matrix4, Vector3 } from 'three';+import { mat3, mat4, vec3 } from 'gl-matrix';import { createMeshQueryIndex } from './mesh-query.js';import { recomputeNormals } from './geometry-normals.js';@@ -9,18 +9,24 @@ function finite(value, label) {return value;}+function createVector(x = 0, y = 0, z = 0) {+ return Float64Array.of(x, y, z);+}+function limit(value, maximum, label) {if (!Number.isSafeInteger(value) || value < 1 || value > maximum) throw new RangeError(`${label} must be an integer from 1 through ${maximum}.`);return value;}function transform(input) {- if (input === undefined) return new Matrix4();+ // gl-matrix allocates Float32Array unless given an output, so every result below is created as Float64Array.+ if (input === undefined) return mat4.identity(new Float64Array(16));if ((!Array.isArray(input) && !ArrayBuffer.isView(input)) || input.length !== 16) throw new TypeError('sourceToTarget requires 16 affine components.');const components = Array.from(input, value => Math.fround(finite(value, 'sourceToTarget')));if (components[3] !== 0 || components[7] !== 0 || components[11] !== 0 || components[15] !== 1) throw new RangeError('sourceToTarget must be affine.');- const matrix = new Matrix4().fromArray(components);- if (!Number.isFinite(matrix.determinant()) || matrix.determinant() === 0) throw new RangeError('sourceToTarget must remain nonsingular.');+ const matrix = Float64Array.from(components);+ const determinant = mat4.determinant(matrix);+ if (!Number.isFinite(determinant) || determinant === 0) throw new RangeError('sourceToTarget must remain nonsingular.');return matrix;}@@ -28,11 +34,11 @@ function faceNormal(positions, indices, offset) {const first = indices[offset] * 3;const second = indices[offset + 1] * 3;const third = indices[offset + 2] * 3;- const edgeFirst = new Vector3(positions[second] - positions[first], positions[second + 1] - positions[first + 1], positions[second + 2] - positions[first + 2]);- const edgeSecond = new Vector3(positions[third] - positions[first], positions[third + 1] - positions[first + 1], positions[third + 2] - positions[first + 2]);- const normal = new Vector3().crossVectors(edgeFirst, edgeSecond);- const longest = Math.max(edgeFirst.length(), edgeSecond.length(), edgeFirst.clone().sub(edgeSecond).length());- return { normal, altitude: normal.length() / longest };+ const edgeFirst = createVector(positions[second] - positions[first], positions[second + 1] - positions[first + 1], positions[second + 2] - positions[first + 2]);+ const edgeSecond = createVector(positions[third] - positions[first], positions[third + 1] - positions[first + 1], positions[third + 2] - positions[first + 2]);+ const normal = vec3.cross(createVector(), edgeFirst, edgeSecond);+ const longest = Math.max(vec3.length(edgeFirst), vec3.length(edgeSecond), vec3.distance(edgeFirst, edgeSecond));+ return { normal, altitude: vec3.length(normal) / longest };}function validateSource(source, maxVertices, maxTriangles) {@@ -66,16 +72,16 @@ function validateTriangles(before, after, indices, hitNormals) {const output = faceNormal(after, indices, offset);const maximum = Math.max(...Array.from(indices.subarray(offset, offset + 3)).flatMap(vertex => Array.from(after.subarray(vertex * 3, vertex * 3 + 3), Math.abs)));if (!Number.isFinite(output.altitude) || output.altitude <= maximum * 2 ** -21 + 2 ** -149) throw new RangeError('Shrinkwrap collapses a triangle within Float32 precision. Reduce projection or clearance.');- if (output.normal.dot(original.normal) <= 0) throw new RangeError('Shrinkwrap flips or folds a triangle relative to the transformed source.');- const targetNormal = new Vector3();+ if (vec3.dot(output.normal, original.normal) <= 0) throw new RangeError('Shrinkwrap flips or folds a triangle relative to the transformed source.');+ const targetNormal = createVector();let allMatched = true;for (let corner = 0; corner < 3; corner++) {const vertex = indices[offset + corner];if (!hitNormals[vertex]) allMatched = false;- else targetNormal.add(hitNormals[vertex]);+ else vec3.add(targetNormal, targetNormal, hitNormals[vertex]);}// A closest point at a hard crease can select a perpendicular neighboring face.- if (allMatched && output.normal.dot(targetNormal) < 0) throw new RangeError('Shrinkwrap triangle faces away from its matched target surface.');+ if (allMatched && vec3.dot(output.normal, targetNormal) < 0) throw new RangeError('Shrinkwrap triangle faces away from its matched target surface.');}}@@ -89,8 +95,8 @@ export function shrinkwrapGeometry(source, target, options = {}) {const maxTriangleTests = limit(options.maxTriangleTests ?? 20_000_000, 100_000_000, 'maxTriangleTests');const count = validateSource(source, maxVertices, maxTriangles);const matrix = transform(options.sourceToTarget);- const normalMatrix = new Matrix3().getNormalMatrix(matrix);- if (!normalMatrix.elements.every(Number.isFinite)) throw new RangeError('sourceToTarget normal transform exceeds the precision domain.');+ const normalMatrix = mat3.normalFromMat4(new Float64Array(9), matrix);+ if (!normalMatrix || !normalMatrix.every(Number.isFinite)) throw new RangeError('sourceToTarget normal transform exceeds the precision domain.');const mode = options.mode ?? 'nearest';if (mode !== 'nearest' && mode !== 'project') throw new RangeError('Shrinkwrap mode must be nearest or project.');let direction;@@ -109,15 +115,18 @@ export function shrinkwrapGeometry(source, target, options = {}) {const before = new Float32Array(source.positions.length);const fallbackNormals = new Float32Array(source.normals.length);- const point = new Vector3();+ const point = createVector();for (let vertex = 0; vertex < count; vertex++) {const offset = vertex * 3;- point.fromArray(source.positions, offset).applyMatrix4(matrix);- for (const value of point.toArray()) finite(value, 'Transformed position');- before.set(point.toArray(), offset);- point.fromArray(source.normals, offset).applyMatrix3(normalMatrix).normalize();- if (!point.toArray().every(Number.isFinite) || point.length() === 0) throw new RangeError('Transformed source normal is invalid.');- fallbackNormals.set(point.toArray(), offset);+ point.set(source.positions.subarray(offset, offset + 3));+ vec3.transformMat4(point, point, matrix);+ for (const value of point) finite(value, 'Transformed position');+ before.set(point, offset);+ point.set(source.normals.subarray(offset, offset + 3));+ vec3.transformMat3(point, point, normalMatrix);+ vec3.normalize(point, point);+ if (!point.every(Number.isFinite) || vec3.length(point) === 0) throw new RangeError('Transformed source normal is invalid.');+ fallbackNormals.set(point, offset);}const groups = new Map();for (let vertex = 0; vertex < count; vertex++) {@@ -148,13 +157,13 @@ export function shrinkwrapGeometry(source, target, options = {}) {continue;}stats.matchedVertices++;- const normal = new Vector3(...query.hit.normal);+ const normal = createVector(...query.hit.normal);const roundedPoint = query.hit.point.map(Math.fround);const moved = query.hit.point.map((value, axis) => Math.fround(finite(value + query.hit.normal[axis] * clearance, 'Shrinkwrap position')));if (clearance > 0) {- const displacement = new Vector3(...moved).sub(new Vector3(...roundedPoint));- const actualGap = new Vector3(...moved).sub(new Vector3(...query.hit.point)).dot(normal);- if (displacement.dot(normal) <= 0 || actualGap <= 0) throw new RangeError('Clearance collapses against the geometric face at Float32 precision. Increase clearance or reduce coordinates.');+ const displacement = vec3.subtract(createVector(), moved, roundedPoint);+ const actualGap = vec3.dot(vec3.subtract(createVector(), moved, query.hit.point), normal);+ if (vec3.dot(displacement, normal) <= 0 || actualGap <= 0) throw new RangeError('Clearance collapses against the geometric face at Float32 precision. Increase clearance or reduce coordinates.');}for (const vertex of vertices) {result.positions.set(moved, vertex * 3);diff --git a/src/surface-decal.js b/src/surface-decal.jsnew file mode 100644index 00000000..dd3f7cec--- /dev/null+++ b/src/surface-decal.js@@ -0,0 +1,105 @@+import { mat4, vec3 } from 'gl-matrix';++// A decal vertex is six numbers: position x, y, z then normal x, y, z.+const CLIP_AXES = [[0, 1], [0, -1], [1, 1], [1, -1], [2, 1], [2, -1]];++/** Rigid projector matrix for XYZ Euler angles in radians, as a column-major Float64Array. */+export function createProjectorMatrix(position, rotation) {+ const [angleX, angleY, angleZ] = rotation;+ const a = Math.cos(angleX);+ const b = Math.sin(angleX);+ const c = Math.cos(angleY);+ const d = Math.sin(angleY);+ const e = Math.cos(angleZ);+ const f = Math.sin(angleZ);+ const ae = a * e;+ const af = a * f;+ const be = b * e;+ const bf = b * f;+ return Float64Array.of(+ c * e, af + be * d, bf - ae * d, 0,+ -c * f, ae - bf * d, be + af * d, 0,+ d, -b * c, a * c, 0,+ position[0], position[1], position[2], 1,+ );+}++export function invertMatrix(matrix) {+ return mat4.invert(new Float64Array(16), matrix);+}++function interpolate(first, second, along) {+ const vertex = new Float64Array(6);+ for (let component = 0; component < 6; component++) {+ vertex[component] = first[component] + along * (second[component] - first[component]);+ }+ return vertex;+}++function clipEdge(inside, outside, axis, sign, limit) {+ const insideDistance = sign * inside[axis] - limit;+ const outsideDistance = sign * outside[axis] - limit;+ return interpolate(inside, outside, insideDistance / (insideDistance - outsideDistance));+}++// Keeps the part of each triangle on the inner side of one projector face, in the order the original clipper emitted it.+function clipToFace(vertices, axis, sign, size) {+ const limit = 0.5 * size[axis];+ const clipped = [];+ for (let start = 0; start < vertices.length; start += 3) {+ const triangle = [vertices[start], vertices[start + 1], vertices[start + 2]];+ const outside = triangle.map(vertex => sign * vertex[axis] - limit > 0);+ const outsideCount = outside.filter(Boolean).length;+ if (outsideCount === 0) {+ clipped.push(...triangle);+ } else if (outsideCount === 1) {+ clipped.push(...clipOneCornerOut(triangle, outside.indexOf(true), axis, sign, limit));+ } else if (outsideCount === 2) {+ const inside = outside.indexOf(false);+ const keep = triangle[inside];+ const next = triangle[(inside + 1) % 3];+ const previous = triangle[(inside + 2) % 3];+ clipped.push(keep, clipEdge(keep, next, axis, sign, limit), clipEdge(keep, previous, axis, sign, limit));+ }+ }+ return clipped;+}++function clipOneCornerOut(triangle, outsideCorner, axis, sign, limit) {+ const out = triangle[outsideCorner];+ const first = triangle[(outsideCorner + 1) % 3];+ const second = triangle[(outsideCorner + 2) % 3];+ const firstCut = clipEdge(out, first, axis, sign, limit);+ const secondCut = clipEdge(out, second, axis, sign, limit);+ // The original clipper wound the middle corner's quad the other way round.+ if (outsideCorner === 1) return [secondCut, first, second, first, secondCut, firstCut];+ return [first, second, firstCut, secondCut, firstCut, second];+}++/**+ * Clips the selected triangles of a target to a box-shaped projector and returns patch arrays in target space.+ * Normals are normalized on entry and carried unchanged; uvs run from 0 to 1 across the projector face.+ */+export function clipTrianglesToProjector(positions, normals, indices, projectorMatrix, size) {+ const projectorInverse = invertMatrix(projectorMatrix);+ let vertices = [];+ const point = new Float64Array(3);+ for (const index of indices) {+ const vertex = new Float64Array(6);+ point.set(positions.subarray(index * 3, index * 3 + 3));+ vec3.transformMat4(point, point, projectorInverse);+ vertex.set(point, 0);+ vertex.set(vec3.normalize(new Float64Array(3), normals.subarray(index * 3, index * 3 + 3)), 3);+ vertices.push(vertex);+ }+ for (const [axis, sign] of CLIP_AXES) vertices = clipToFace(vertices, axis, sign, size);+ const patch = { positions: new Float32Array(vertices.length * 3), normals: new Float32Array(vertices.length * 3), uvs: new Float32Array(vertices.length * 2) };+ vertices.forEach((vertex, slot) => {+ patch.uvs[slot * 2] = 0.5 + vertex[0] / size[0];+ patch.uvs[slot * 2 + 1] = 0.5 + vertex[1] / size[1];+ vec3.transformMat4(point, vertex.subarray(0, 3), projectorMatrix);+ patch.positions.set(point, slot * 3);+ patch.normals.set(vertex.subarray(3, 6), slot * 3);+ });+ return patch;+}diff --git a/src/surface.js b/src/surface.jsindex 6af630b8..7b877306 100644--- a/src/surface.js+++ b/src/surface.js@@ -1,9 +1,13 @@-import { BufferAttribute, BufferGeometry, Euler, Matrix4, Mesh, Vector3 } from 'three';-import { DecalGeometry } from 'three/addons/geometries/DecalGeometry.js';+import { vec3 } from 'gl-matrix';+import { clipTrianglesToProjector, createProjectorMatrix, invertMatrix } from './surface-decal.js';const PROCEDURAL_TAGS = new Set(['armor', 'floor', 'water', 'foliage', 'grass', 'terrain', 'fire', 'smoke']);const OPTION_FIELDS = new Set(['position', 'rotation', 'size', 'clearance', 'maxAngle', 'maxVertices', 'maxTriangles']);+function createVector(x = 0, y = 0, z = 0) {+ return Float64Array.of(x, y, z);+}+function finiteFloat(value, label) {if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value))) {throw new TypeError(`${label} must be a finite Float32 value.`);@@ -57,61 +61,64 @@ function validateTarget(target, maxTriangles) {return geometry;}+function readPoint(array, vertex) {+ return createVector(array[vertex * 3], array[vertex * 3 + 1], array[vertex * 3 + 2]);+}++function faceDirection(points) {+ const first = vec3.subtract(createVector(), points[1], points[0]);+ const second = vec3.subtract(createVector(), points[2], points[0]);+ const face = vec3.cross(createVector(), first, second);+ const area = vec3.length(face);+ return area === 0 ? null : vec3.scale(face, face, 1 / area);+}+function candidateIndices(geometry, projectorInverse, direction, size, maxAngle, maxVertices) {const indices = [];- const points = [new Vector3(), new Vector3(), new Vector3()];- const projected = [new Vector3(), new Vector3(), new Vector3()];- const normal = new Vector3();- const edge = new Vector3();- const face = new Vector3();const minimumFacing = Math.max(0, Math.cos(maxAngle));let vertexBound = 0;let drawable = false;for (let offset = 0; offset < geometry.indices.length; offset += 3) {- for (let corner = 0; corner < 3; corner++) points[corner].fromArray(geometry.positions, geometry.indices[offset + corner] * 3);- face.subVectors(points[1], points[0]).cross(edge.subVectors(points[2], points[0]));- const area = Math.hypot(face.x, face.y, face.z);- if (area === 0) continue;+ const corners = [0, 1, 2].map(corner => geometry.indices[offset + corner]);+ const points = corners.map(vertex => readPoint(geometry.positions, vertex));+ const face = faceDirection(points);+ if (!face) continue;drawable = true;- face.multiplyScalar(1 / area);- const facing = face.dot(direction);+ const facing = vec3.dot(face, direction);if (facing <= 0 || facing < minimumFacing) continue;- for (let corner = 0; corner < 3; corner++) {- normal.fromArray(geometry.normals, geometry.indices[offset + corner] * 3);- if (normal.dot(face) <= 0) throw new RangeError('Surface target normals must face outward with their triangles.');- projected[corner].copy(points[corner]).applyMatrix4(projectorInverse);+ for (const vertex of corners) {+ if (vec3.dot(readPoint(geometry.normals, vertex), face) <= 0) throw new RangeError('Surface target normals must face outward with their triangles.');}+ const projected = points.map(point => vec3.transformMat4(createVector(), point, projectorInverse));let outside = false;let clippingPlanes = 0;for (let axis = 0; axis < 3; axis++) {- const minimum = Math.min(projected[0].getComponent(axis), projected[1].getComponent(axis), projected[2].getComponent(axis));- const maximum = Math.max(projected[0].getComponent(axis), projected[1].getComponent(axis), projected[2].getComponent(axis));+ const minimum = Math.min(projected[0][axis], projected[1][axis], projected[2][axis]);+ const maximum = Math.max(projected[0][axis], projected[1][axis], projected[2][axis]);const halfSize = size[axis] / 2;if (minimum > halfSize || maximum < -halfSize) outside = true;if (maximum > halfSize) clippingPlanes++;if (minimum < -halfSize) clippingPlanes++;}if (outside) continue;- // Each of the six maintained clipping passes can double triangle fragments.+ // Each of the six clipping passes can double triangle fragments.vertexBound += 3 * 2 ** clippingPlanes;if (vertexBound > maxVertices) throw new RangeError('Surface clipping reservation exceeds maxVertices. Reduce the projector or raise the limit.');- indices.push(geometry.indices[offset], geometry.indices[offset + 1], geometry.indices[offset + 2]);+ indices.push(...corners);}if (!drawable) throw new RangeError('Surface target has no drawable triangles.');if (indices.length === 0) throw new RangeError('Surface projector misses all outward-facing target triangles.');return indices;}-function patchGeometry(source, clearance, maxVertices) {- const sourcePositions = source.getAttribute('position').array;- const sourceNormals = source.getAttribute('normal').array;- const sourceUvs = source.getAttribute('uv').array;+function patchGeometry(decal, clearance, maxVertices) {+ const sourcePositions = decal.positions;const vertexCount = sourcePositions.length / 3;if (vertexCount === 0) throw new RangeError('Surface projector clips to an empty patch.');if (vertexCount > maxVertices) throw new RangeError('Surface output exceeds maxVertices.');const positions = new Float32Array(sourcePositions);- const normals = new Float32Array(sourceNormals);- const uvs = new Float32Array(sourceUvs);+ const normals = new Float32Array(decal.normals);+ const uvs = new Float32Array(decal.uvs);for (let vertex = 0; vertex < vertexCount; vertex++) {const offset = vertex * 3;const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]);@@ -130,35 +137,21 @@ function patchGeometry(source, clearance, maxVertices) {}}const indices = [];- const first = new Vector3();- const second = new Vector3();- const third = new Vector3();- const edge = new Vector3();- const sourceFirst = new Vector3();- const sourceSecond = new Vector3();- const sourceThird = new Vector3();- const sourceFace = new Vector3();- const displacement = new Vector3();for (let vertex = 0; vertex < vertexCount; vertex += 3) {- sourceFirst.fromArray(sourcePositions, vertex * 3);- sourceSecond.fromArray(sourcePositions, (vertex + 1) * 3).sub(sourceFirst);- sourceThird.fromArray(sourcePositions, (vertex + 2) * 3).sub(sourceFirst);- sourceFace.crossVectors(sourceSecond, sourceThird);- const sourceArea = Math.hypot(sourceFace.x, sourceFace.y, sourceFace.z);- if (sourceArea === 0) continue;- sourceFace.multiplyScalar(1 / sourceArea);+ const sourceCorners = [0, 1, 2].map(corner => readPoint(sourcePositions, vertex + corner));+ const sourceFace = faceDirection(sourceCorners);+ if (!sourceFace) continue;if (clearance > 0) {for (let corner = 0; corner < 3; corner++) {- const offset = (vertex + corner) * 3;- displacement.set(positions[offset] - sourcePositions[offset], positions[offset + 1] - sourcePositions[offset + 1], positions[offset + 2] - sourcePositions[offset + 2]);- if (displacement.dot(sourceFace) <= 0) throw new RangeError('Surface clearance cannot create a positive triangle-plane gap at Float32 precision. Increase clearance or center the target locally.');+ const displacement = vec3.subtract(createVector(), readPoint(positions, vertex + corner), sourceCorners[corner]);+ if (vec3.dot(displacement, sourceFace) <= 0) throw new RangeError('Surface clearance cannot create a positive triangle-plane gap at Float32 precision. Increase clearance or center the target locally.');}}- first.fromArray(positions, vertex * 3);- second.fromArray(positions, (vertex + 1) * 3).sub(first);- third.fromArray(positions, (vertex + 2) * 3).sub(first);- edge.crossVectors(second, third);- if (Math.hypot(edge.x, edge.y, edge.z) === 0 || edge.dot(sourceFace) <= 0) {+ const moved = [0, 1, 2].map(corner => readPoint(positions, vertex + corner));+ const edgeFirst = vec3.subtract(createVector(), moved[1], moved[0]);+ const edgeSecond = vec3.subtract(createVector(), moved[2], moved[0]);+ const edge = vec3.cross(createVector(), edgeFirst, edgeSecond);+ if (vec3.length(edge) === 0 || vec3.dot(edge, sourceFace) <= 0) {throw new RangeError('Surface clearance collapses or reverses a triangle. Reduce clearance.');}indices.push(vertex, vertex + 1, vertex + 2);@@ -186,23 +179,10 @@ export function createSurfacePatch(target, options = {}) {const maxVertices = limit(options.maxVertices ?? 250_000, 3, 'maxVertices');const maxTriangles = limit(options.maxTriangles ?? 250_000, 1, 'maxTriangles');const geometry = validateTarget(target, maxTriangles);- const orientation = new Euler(...rotation, 'XYZ');- const projector = new Matrix4().makeRotationFromEuler(orientation).setPosition(...position);- const inverse = projector.clone().invert();- const direction = new Vector3(0, 0, 1).transformDirection(projector);- const selected = candidateIndices(geometry, inverse, direction, size, maxAngle, maxVertices);- const source = new BufferGeometry();- let decal;- try {- source.setAttribute('position', new BufferAttribute(geometry.positions, 3));- source.setAttribute('normal', new BufferAttribute(geometry.normals, 3));- source.setIndex(new BufferAttribute(new Uint32Array(selected), 1));- const mesh = new Mesh(source, null);- // Identity matrix keeps DecalGeometry output in target-local space.- decal = new DecalGeometry(mesh, new Vector3(...position), orientation, new Vector3(...size));- return patchGeometry(decal, clearance, maxVertices);- } finally {- decal?.dispose();- source.dispose();- }+ const projector = createProjectorMatrix(position, rotation);+ const direction = vec3.normalize(createVector(), createVector(projector[8], projector[9], projector[10]));+ const selected = candidateIndices(geometry, invertMatrix(projector), direction, size, maxAngle, maxVertices);+ // Clipping happens in target-local space, so the patch lands where the target's own vertices are.+ const decal = clipTrianglesToProjector(geometry.positions, geometry.normals, selected, projector, size);+ return patchGeometry(decal, clearance, maxVertices);}diff --git a/src/triangle-bvh.js b/src/triangle-bvh.jsnew file mode 100644index 00000000..704d7d57--- /dev/null+++ b/src/triangle-bvh.js@@ -0,0 +1,299 @@+// Bounding volume hierarchy over triangles, stored in typed arrays. Nodes sit in depth-first order:+// the left child of node n is n + 1 and rightChild[n] holds the right child, or -1 for a leaf.+const BIN_COUNT = 16;++function triangleBoundsAndCentroids(positions, indices) {+ const triangleCount = indices.length / 3;+ const bounds = new Float64Array(triangleCount * 6);+ const centroids = new Float64Array(triangleCount * 3);+ for (let triangle = 0; triangle < triangleCount; triangle++) {+ for (let axis = 0; axis < 3; axis++) {+ const first = positions[indices[triangle * 3] * 3 + axis];+ const second = positions[indices[triangle * 3 + 1] * 3 + axis];+ const third = positions[indices[triangle * 3 + 2] * 3 + axis];+ const low = Math.min(first, second, third);+ const high = Math.max(first, second, third);+ bounds[triangle * 6 + axis] = low;+ bounds[triangle * 6 + 3 + axis] = high;+ centroids[triangle * 3 + axis] = (low + high) / 2;+ }+ }+ return { bounds, centroids };+}++function unionBounds(triangleBounds, order, start, end, out, outOffset) {+ for (let axis = 0; axis < 3; axis++) {+ out[outOffset + axis] = Infinity;+ out[outOffset + 3 + axis] = -Infinity;+ }+ for (let slot = start; slot < end; slot++) {+ const offset = order[slot] * 6;+ for (let axis = 0; axis < 3; axis++) {+ out[outOffset + axis] = Math.min(out[outOffset + axis], triangleBounds[offset + axis]);+ out[outOffset + 3 + axis] = Math.max(out[outOffset + 3 + axis], triangleBounds[offset + 3 + axis]);+ }+ }+}++function surfaceArea(bounds, offset) {+ const width = bounds[offset + 3] - bounds[offset];+ const height = bounds[offset + 4] - bounds[offset + 1];+ const depth = bounds[offset + 5] - bounds[offset + 2];+ return width < 0 ? 0 : 2 * (width * height + height * depth + depth * width);+}++function centroidAxis(centroids, order, start, end) {+ const low = [Infinity, Infinity, Infinity];+ const high = [-Infinity, -Infinity, -Infinity];+ for (let slot = start; slot < end; slot++) {+ for (let axis = 0; axis < 3; axis++) {+ low[axis] = Math.min(low[axis], centroids[order[slot] * 3 + axis]);+ high[axis] = Math.max(high[axis], centroids[order[slot] * 3 + axis]);+ }+ }+ const extents = high.map((value, axis) => value - low[axis]);+ const axis = extents.indexOf(Math.max(...extents));+ return { axis, low: low[axis], extent: extents[axis] };+}++// Cheapest surface area heuristic split over equal-width centroid bins, as the bin index of the last left bin.+function bestBinSplit(triangleBounds, centroids, order, start, end, split) {+ const counts = new Uint32Array(BIN_COUNT);+ const binBounds = new Float64Array(BIN_COUNT * 6);+ for (let bin = 0; bin < BIN_COUNT; bin++) unionBounds(triangleBounds, order, 0, 0, binBounds, bin * 6);+ const scale = BIN_COUNT / split.extent;+ for (let slot = start; slot < end; slot++) {+ const triangle = order[slot];+ const bin = Math.min(BIN_COUNT - 1, Math.floor((centroids[triangle * 3 + split.axis] - split.low) * scale));+ counts[bin]++;+ for (let axis = 0; axis < 3; axis++) {+ binBounds[bin * 6 + axis] = Math.min(binBounds[bin * 6 + axis], triangleBounds[triangle * 6 + axis]);+ binBounds[bin * 6 + 3 + axis] = Math.max(binBounds[bin * 6 + 3 + axis], triangleBounds[triangle * 6 + 3 + axis]);+ }+ }+ const leftCost = sweepCosts(counts, binBounds, 0, 1);+ const rightCost = sweepCosts(counts, binBounds, BIN_COUNT - 1, -1);+ let bestBin = -1;+ let bestCost = Infinity;+ let leftCount = 0;+ for (let bin = 0; bin < BIN_COUNT - 1; bin++) {+ leftCount += counts[bin];+ if (leftCount === 0 || leftCount === end - start) continue;+ const cost = leftCost[bin] + rightCost[bin + 1];+ if (cost < bestCost) {+ bestCost = cost;+ bestBin = bin;+ }+ }+ return bestBin;+}++function sweepCosts(counts, binBounds, firstBin, step) {+ const costs = new Float64Array(BIN_COUNT);+ const running = new Float64Array(6);+ unionBounds(binBounds, [], 0, 0, running, 0);+ let count = 0;+ for (let bin = firstBin; bin >= 0 && bin < BIN_COUNT; bin += step) {+ count += counts[bin];+ for (let axis = 0; axis < 3; axis++) {+ running[axis] = Math.min(running[axis], binBounds[bin * 6 + axis]);+ running[3 + axis] = Math.max(running[3 + axis], binBounds[bin * 6 + 3 + axis]);+ }+ costs[bin] = count * surfaceArea(running, 0);+ }+ return costs;+}++function partition(order, centroids, start, end, axis, isLeft) {+ let left = start;+ let right = end - 1;+ while (left <= right) {+ if (isLeft(centroids[order[left] * 3 + axis])) {+ left++;+ } else {+ const swapped = order[left];+ order[left] = order[right];+ order[right] = swapped;+ right--;+ }+ }+ return left;+}++function splitRange(triangleBounds, centroids, order, start, end) {+ const split = centroidAxis(centroids, order, start, end);+ if (!(split.extent > 0)) return -1;+ const bestBin = bestBinSplit(triangleBounds, centroids, order, start, end, split);+ const boundary = split.low + split.extent * (bestBin + 1) / BIN_COUNT;+ let middle = bestBin < 0 ? start : partition(order, centroids, start, end, split.axis, value => value < boundary);+ if (middle === start || middle === end) {+ const midpoint = split.low + split.extent / 2;+ middle = partition(order, centroids, start, end, split.axis, value => value < midpoint);+ }+ return middle === start || middle === end ? -1 : middle;+}++/**+ * Builds a hierarchy over the triangles of an indexed mesh. The mesh arrays are kept by reference.+ * `triangleOrder` maps leaf slots back to triangle ids.+ */+export function buildTriangleBvh(positions, indices, { leafSize = 8, maxDepth = 64 } = {}) {+ const triangleCount = indices.length / 3;+ const { bounds: triangleBounds, centroids } = triangleBoundsAndCentroids(positions, indices);+ const triangleOrder = Uint32Array.from({ length: triangleCount }, (value, slot) => slot);+ const capacity = Math.max(1, triangleCount * 2);+ const nodeBounds = new Float64Array(capacity * 6);+ const rightChild = new Int32Array(capacity).fill(-1);+ const rangeStart = new Uint32Array(capacity);+ const rangeCount = new Uint32Array(capacity);+ let nodeCount = 0;+ const pending = [{ start: 0, end: triangleCount, depth: 0, parent: -1 }];+ while (pending.length) {+ const { start, end, depth, parent } = pending.pop();+ const node = nodeCount++;+ if (parent >= 0) rightChild[parent] = node;+ unionBounds(triangleBounds, triangleOrder, start, end, nodeBounds, node * 6);+ rangeStart[node] = start;+ rangeCount[node] = end - start;+ const middle = end - start <= leafSize || depth >= maxDepth ? -1 : splitRange(triangleBounds, centroids, triangleOrder, start, end);+ if (middle < 0) continue;+ pending.push({ start: middle, end, depth: depth + 1, parent: node });+ pending.push({ start, end: middle, depth: depth + 1, parent: -1 });+ }+ return { positions, indices, triangleOrder, nodeBounds, rightChild, rangeStart, rangeCount, nodeCount };+}++/**+ * Visits triangles nearest first. `scoreBounds(nodeBounds, offset)` rates a node box (Infinity skips it),+ * `shouldVisit(score)` is asked again when a node is popped so a shrinking limit prunes it, and+ * `visitTriangle(triangleId)` returns true to stop the traversal.+ */+export function traverseTriangleBvh(bvh, scoreBounds, shouldVisit, visitTriangle) {+ const stack = [0];+ // The root is always entered, so a query that misses the whole mesh still reports the triangles it tested.+ const scores = [0];+ while (stack.length) {+ const node = stack.pop();+ if (!shouldVisit(scores.pop())) continue;+ const right = bvh.rightChild[node];+ if (right < 0) {+ const end = bvh.rangeStart[node] + bvh.rangeCount[node];+ for (let slot = bvh.rangeStart[node]; slot < end; slot++) {+ if (visitTriangle(bvh.triangleOrder[slot])) return true;+ }+ continue;+ }+ const left = node + 1;+ const leftScore = scoreBounds(bvh.nodeBounds, left * 6);+ const rightScore = scoreBounds(bvh.nodeBounds, right * 6);+ const nearFirst = leftScore <= rightScore;+ stack.push(nearFirst ? right : left);+ scores.push(nearFirst ? rightScore : leftScore);+ stack.push(nearFirst ? left : right);+ scores.push(nearFirst ? leftScore : rightScore);+ }+ return false;+}++/** Distance from a point to a node box; zero inside. */+export function pointBoxDistance(point, bounds, offset) {+ let squared = 0;+ for (let axis = 0; axis < 3; axis++) {+ const gap = Math.max(bounds[offset + axis] - point[axis], 0, point[axis] - bounds[offset + 3 + axis]);+ squared += gap * gap;+ }+ return Math.sqrt(squared);+}++/** Distance along a ray to a node box (zero when the origin is inside), or Infinity for a miss. */+export function rayBoxDistance(origin, direction, bounds, offset) {+ let entry = 0;+ let exit = Infinity;+ for (let axis = 0; axis < 3; axis++) {+ const low = bounds[offset + axis] - origin[axis];+ const high = bounds[offset + 3 + axis] - origin[axis];+ if (direction[axis] === 0) {+ if (low > 0 || high < 0) return Infinity;+ continue;+ }+ const first = low / direction[axis];+ const second = high / direction[axis];+ entry = Math.max(entry, Math.min(first, second));+ exit = Math.min(exit, Math.max(first, second));+ }+ return entry <= exit * (1 + 1e-12) + 1e-12 ? entry : Infinity;+}++function transformedTriangleBounds(first, second, secondPositions, out) {+ const { nodeCount, rightChild, rangeStart, rangeCount, triangleOrder, indices } = second;+ for (let node = nodeCount - 1; node >= 0; node--) {+ const offset = node * 6;+ if (rightChild[node] >= 0) {+ const children = [node + 1, rightChild[node]];+ for (let axis = 0; axis < 3; axis++) {+ out[offset + axis] = Math.min(out[children[0] * 6 + axis], out[children[1] * 6 + axis]);+ out[offset + 3 + axis] = Math.max(out[children[0] * 6 + 3 + axis], out[children[1] * 6 + 3 + axis]);+ }+ continue;+ }+ for (let axis = 0; axis < 3; axis++) {+ out[offset + axis] = Infinity;+ out[offset + 3 + axis] = -Infinity;+ }+ for (let slot = rangeStart[node]; slot < rangeStart[node] + rangeCount[node]; slot++) {+ for (let corner = 0; corner < 3; corner++) {+ const vertex = indices[triangleOrder[slot] * 3 + corner] * 3;+ for (let axis = 0; axis < 3; axis++) {+ out[offset + axis] = Math.min(out[offset + axis], secondPositions[vertex + axis]);+ out[offset + 3 + axis] = Math.max(out[offset + 3 + axis], secondPositions[vertex + axis]);+ }+ }+ }+ }+ return out;+}++function boxesOverlap(firstBounds, firstOffset, secondBounds, secondOffset) {+ for (let axis = 0; axis < 3; axis++) {+ if (firstBounds[firstOffset + axis] > secondBounds[secondOffset + 3 + axis]) return false;+ if (secondBounds[secondOffset + axis] > firstBounds[firstOffset + 3 + axis]) return false;+ }+ return true;+}++function boxSize(bounds, offset) {+ return Math.max(bounds[offset + 3] - bounds[offset], bounds[offset + 4] - bounds[offset + 1], bounds[offset + 5] - bounds[offset + 2]);+}++/**+ * Calls `visitPair(firstTriangleId, secondTriangleId)` for every triangle pair whose leaf boxes overlap.+ * `secondPositions` holds the second mesh vertices already moved into the first mesh space.+ * The visitor returns true to stop; the result is whether it did.+ */+export function traverseBvhPairs(first, second, secondPositions, visitPair) {+ const secondBounds = transformedTriangleBounds(first, second, secondPositions, new Float64Array(second.nodeCount * 6));+ const stack = [[0, 0]];+ while (stack.length) {+ const [firstNode, secondNode] = stack.pop();+ if (!boxesOverlap(first.nodeBounds, firstNode * 6, secondBounds, secondNode * 6)) continue;+ const firstIsLeaf = first.rightChild[firstNode] < 0;+ const secondIsLeaf = second.rightChild[secondNode] < 0;+ if (firstIsLeaf && secondIsLeaf) {+ if (visitLeafPair(first, second, firstNode, secondNode, visitPair)) return true;+ } else if (secondIsLeaf || (!firstIsLeaf && boxSize(first.nodeBounds, firstNode * 6) >= boxSize(secondBounds, secondNode * 6))) {+ stack.push([first.rightChild[firstNode], secondNode], [firstNode + 1, secondNode]);+ } else {+ stack.push([firstNode, second.rightChild[secondNode]], [firstNode, secondNode + 1]);+ }+ }+ return false;+}++function visitLeafPair(first, second, firstNode, secondNode, visitPair) {+ for (let firstSlot = first.rangeStart[firstNode]; firstSlot < first.rangeStart[firstNode] + first.rangeCount[firstNode]; firstSlot++) {+ for (let secondSlot = second.rangeStart[secondNode]; secondSlot < second.rangeStart[secondNode] + second.rangeCount[secondNode]; secondSlot++) {+ if (visitPair(first.triangleOrder[firstSlot], second.triangleOrder[secondSlot])) return true;+ }+ }+ return false;+}diff --git a/src/triangle-math.js b/src/triangle-math.jsnew file mode 100644index 00000000..046c45c1--- /dev/null+++ b/src/triangle-math.js@@ -0,0 +1,232 @@+// Triangle helpers on plain numbers. A triangle is a Float64Array of nine values: a, b, c.+const PLANE_EPSILON = 1e-12;+const INTERVAL_EPSILON = 1e-12;++export function readTriangle(positions, indices, triangleId, triangle) {+ for (let corner = 0; corner < 3; corner++) {+ const source = indices[triangleId * 3 + corner] * 3;+ triangle[corner * 3] = positions[source];+ triangle[corner * 3 + 1] = positions[source + 1];+ triangle[corner * 3 + 2] = positions[source + 2];+ }+}++function crossOfEdges(triangle, out) {+ const firstX = triangle[3] - triangle[0];+ const firstY = triangle[4] - triangle[1];+ const firstZ = triangle[5] - triangle[2];+ const secondX = triangle[6] - triangle[0];+ const secondY = triangle[7] - triangle[1];+ const secondZ = triangle[8] - triangle[2];+ out[0] = firstY * secondZ - firstZ * secondY;+ out[1] = firstZ * secondX - firstX * secondZ;+ out[2] = firstX * secondY - firstY * secondX;+}++/** Unit normal of the counterclockwise face, or zeros for a degenerate triangle. */+export function triangleNormal(triangle, out) {+ crossOfEdges(triangle, out);+ const length = Math.hypot(out[0], out[1], out[2]);+ if (length === 0) return out;+ out[0] /= length;+ out[1] /= length;+ out[2] /= length;+ return out;+}++/** Writes the point of the triangle nearest to the query point (Ericson, Real-Time Collision Detection). */+export function closestPointOnTriangle(point, triangle, out) {+ const [ax, ay, az, bx, by, bz, cx, cy, cz] = triangle;+ const abX = bx - ax;+ const abY = by - ay;+ const abZ = bz - az;+ const acX = cx - ax;+ const acY = cy - ay;+ const acZ = cz - az;+ const apX = point[0] - ax;+ const apY = point[1] - ay;+ const apZ = point[2] - az;+ const d1 = abX * apX + abY * apY + abZ * apZ;+ const d2 = acX * apX + acY * apY + acZ * apZ;+ if (d1 <= 0 && d2 <= 0) return setPoint(out, ax, ay, az);+ const bpX = point[0] - bx;+ const bpY = point[1] - by;+ const bpZ = point[2] - bz;+ const d3 = abX * bpX + abY * bpY + abZ * bpZ;+ const d4 = acX * bpX + acY * bpY + acZ * bpZ;+ if (d3 >= 0 && d4 <= d3) return setPoint(out, bx, by, bz);+ const vc = d1 * d4 - d3 * d2;+ if (vc <= 0 && d1 >= 0 && d3 <= 0) {+ const along = d1 / (d1 - d3);+ return setPoint(out, ax + abX * along, ay + abY * along, az + abZ * along);+ }+ const cpX = point[0] - cx;+ const cpY = point[1] - cy;+ const cpZ = point[2] - cz;+ const d5 = abX * cpX + abY * cpY + abZ * cpZ;+ const d6 = acX * cpX + acY * cpY + acZ * cpZ;+ if (d6 >= 0 && d5 <= d6) return setPoint(out, cx, cy, cz);+ const vb = d5 * d2 - d1 * d6;+ if (vb <= 0 && d2 >= 0 && d6 <= 0) {+ const along = d2 / (d2 - d6);+ return setPoint(out, ax + acX * along, ay + acY * along, az + acZ * along);+ }+ const va = d3 * d6 - d5 * d4;+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {+ const along = (d4 - d3) / (d4 - d3 + d5 - d6);+ return setPoint(out, bx + (cx - bx) * along, by + (cy - by) * along, bz + (cz - bz) * along);+ }+ const scale = 1 / (va + vb + vc);+ const secondWeight = vb * scale;+ const thirdWeight = vc * scale;+ return setPoint(out, ax + abX * secondWeight + acX * thirdWeight, ay + abY * secondWeight + acY * thirdWeight, az + abZ * secondWeight + acZ * thirdWeight);+}++function setPoint(out, x, y, z) {+ out[0] = x;+ out[1] = y;+ out[2] = z;+ return out;+}++/** Distance along the ray to a two-sided triangle hit, or -1 for a miss. Edges count as hits. */+export function intersectRayTriangle(origin, direction, triangle) {+ const edgeFirstX = triangle[3] - triangle[0];+ const edgeFirstY = triangle[4] - triangle[1];+ const edgeFirstZ = triangle[5] - triangle[2];+ const edgeSecondX = triangle[6] - triangle[0];+ const edgeSecondY = triangle[7] - triangle[1];+ const edgeSecondZ = triangle[8] - triangle[2];+ const pivotX = direction[1] * edgeSecondZ - direction[2] * edgeSecondY;+ const pivotY = direction[2] * edgeSecondX - direction[0] * edgeSecondZ;+ const pivotZ = direction[0] * edgeSecondY - direction[1] * edgeSecondX;+ const determinant = edgeFirstX * pivotX + edgeFirstY * pivotY + edgeFirstZ * pivotZ;+ if (determinant === 0) return -1;+ const offsetX = origin[0] - triangle[0];+ const offsetY = origin[1] - triangle[1];+ const offsetZ = origin[2] - triangle[2];+ const firstWeight = (offsetX * pivotX + offsetY * pivotY + offsetZ * pivotZ) / determinant;+ if (firstWeight < 0 || firstWeight > 1) return -1;+ const queryX = offsetY * edgeFirstZ - offsetZ * edgeFirstY;+ const queryY = offsetZ * edgeFirstX - offsetX * edgeFirstZ;+ const queryZ = offsetX * edgeFirstY - offsetY * edgeFirstX;+ const secondWeight = (direction[0] * queryX + direction[1] * queryY + direction[2] * queryZ) / determinant;+ if (secondWeight < 0 || firstWeight + secondWeight > 1) return -1;+ const distance = (edgeSecondX * queryX + edgeSecondY * queryY + edgeSecondZ * queryZ) / determinant;+ return distance >= 0 ? distance : -1;+}++/** Weights of corners a, b and c for a point on the triangle plane, or null for a degenerate triangle. */+export function barycentricWeights(point, triangle, out) {+ const edgeSecondX = triangle[6] - triangle[0];+ const edgeSecondY = triangle[7] - triangle[1];+ const edgeSecondZ = triangle[8] - triangle[2];+ const edgeFirstX = triangle[3] - triangle[0];+ const edgeFirstY = triangle[4] - triangle[1];+ const edgeFirstZ = triangle[5] - triangle[2];+ const offsetX = point[0] - triangle[0];+ const offsetY = point[1] - triangle[1];+ const offsetZ = point[2] - triangle[2];+ const dotSecondSecond = edgeSecondX * edgeSecondX + edgeSecondY * edgeSecondY + edgeSecondZ * edgeSecondZ;+ const dotSecondFirst = edgeSecondX * edgeFirstX + edgeSecondY * edgeFirstY + edgeSecondZ * edgeFirstZ;+ const dotSecondOffset = edgeSecondX * offsetX + edgeSecondY * offsetY + edgeSecondZ * offsetZ;+ const dotFirstFirst = edgeFirstX * edgeFirstX + edgeFirstY * edgeFirstY + edgeFirstZ * edgeFirstZ;+ const dotFirstOffset = edgeFirstX * offsetX + edgeFirstY * offsetY + edgeFirstZ * offsetZ;+ const denominator = dotSecondSecond * dotFirstFirst - dotSecondFirst * dotSecondFirst;+ if (denominator === 0) return null;+ const thirdWeight = (dotFirstFirst * dotSecondOffset - dotSecondFirst * dotFirstOffset) / denominator;+ const secondWeight = (dotSecondSecond * dotFirstOffset - dotSecondFirst * dotSecondOffset) / denominator;+ out[0] = 1 - thirdWeight - secondWeight;+ out[1] = secondWeight;+ out[2] = thirdWeight;+ return out;+}++function planeDistances(triangle, planeNormal, planePoint) {+ const distances = [0, 0, 0];+ for (let corner = 0; corner < 3; corner++) {+ const distance = (triangle[corner * 3] - planePoint[0]) * planeNormal[0]+ + (triangle[corner * 3 + 1] - planePoint[1]) * planeNormal[1]+ + (triangle[corner * 3 + 2] - planePoint[2]) * planeNormal[2];+ distances[corner] = Math.abs(distance) <= PLANE_EPSILON ? 0 : distance;+ }+ return distances;+}++function onOneSide(distances) {+ return distances.every(distance => distance > 0) || distances.every(distance => distance < 0);+}++function lineInterval(triangle, distances, axis) {+ const points = [];+ for (let corner = 0; corner < 3; corner++) {+ if (distances[corner] === 0) points.push(triangle.slice(corner * 3, corner * 3 + 3));+ const next = (corner + 1) % 3;+ if (distances[corner] * distances[next] < 0) {+ const along = distances[corner] / (distances[corner] - distances[next]);+ points.push([0, 1, 2].map(component => triangle[corner * 3 + component] + (triangle[next * 3 + component] - triangle[corner * 3 + component]) * along));+ }+ }+ points.sort((first, second) => first[axis] - second[axis]);+ return { low: points[0], high: points[points.length - 1] };+}++function coplanarTrianglesOverlap(first, second, normal) {+ for (const triangle of [first, second]) {+ for (let corner = 0; corner < 3; corner++) {+ const next = (corner + 1) % 3;+ const edge = [0, 1, 2].map(component => triangle[next * 3 + component] - triangle[corner * 3 + component]);+ const axis = [edge[1] * normal[2] - edge[2] * normal[1], edge[2] * normal[0] - edge[0] * normal[2], edge[0] * normal[1] - edge[1] * normal[0]];+ if (projectionsSeparate(first, second, axis)) return false;+ }+ }+ return true;+}++function projectionsSeparate(first, second, axis) {+ const firstRange = projectionRange(first, axis);+ const secondRange = projectionRange(second, axis);+ return firstRange.high < secondRange.low - INTERVAL_EPSILON || secondRange.high < firstRange.low - INTERVAL_EPSILON;+}++function projectionRange(triangle, axis) {+ let low = Infinity;+ let high = -Infinity;+ for (let corner = 0; corner < 3; corner++) {+ const projection = triangle[corner * 3] * axis[0] + triangle[corner * 3 + 1] * axis[1] + triangle[corner * 3 + 2] * axis[2];+ low = Math.min(low, projection);+ high = Math.max(high, projection);+ }+ return { low, high };+}++/**+ * Touching counts as intersecting. For triangles that cross along a line the optional segment+ * receives the shared piece (six values); coplanar triangles leave it at zero.+ */+export function trianglesIntersect(first, second, segment = null) {+ const firstNormal = triangleNormal(first, [0, 0, 0]);+ const secondNormal = triangleNormal(second, [0, 0, 0]);+ const firstDistances = planeDistances(first, secondNormal, second);+ const secondDistances = planeDistances(second, firstNormal, first);+ if (onOneSide(firstDistances) || onOneSide(secondDistances)) return false;+ if (segment) segment.fill(0);+ if (firstDistances.every(distance => distance === 0)) return coplanarTrianglesOverlap(first, second, firstNormal);+ const direction = [+ firstNormal[1] * secondNormal[2] - firstNormal[2] * secondNormal[1],+ firstNormal[2] * secondNormal[0] - firstNormal[0] * secondNormal[2],+ firstNormal[0] * secondNormal[1] - firstNormal[1] * secondNormal[0],+ ];+ const magnitudes = direction.map(Math.abs);+ const axis = magnitudes.indexOf(Math.max(...magnitudes));+ const firstInterval = lineInterval(first, firstDistances, axis);+ const secondInterval = lineInterval(second, secondDistances, axis);+ const start = firstInterval.low[axis] >= secondInterval.low[axis] ? firstInterval.low : secondInterval.low;+ const end = firstInterval.high[axis] <= secondInterval.high[axis] ? firstInterval.high : secondInterval.high;+ if (start[axis] > end[axis] + INTERVAL_EPSILON) return false;+ if (segment) {+ segment.set(start, 0);+ segment.set(end, 3);+ }+ return true;+}