134 lines
7.0 KiB
JavaScript
134 lines
7.0 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import { performance } from 'node:perf_hooks';
|
|
import * as THREE from 'three';
|
|
import { MeshBVH, acceleratedRaycast, estimateMemoryInBytes } from 'three-mesh-bvh';
|
|
|
|
export function summarize(samples) {
|
|
const sorted = [...samples].sort((a, b) => a - b);
|
|
return { samples, min: sorted[0], median: sorted[Math.floor(sorted.length / 2)],
|
|
p95: sorted[Math.ceil(sorted.length * 0.95) - 1], max: sorted.at(-1) };
|
|
}
|
|
|
|
// CPU-only mechanism benchmark using installed production dependencies. This is
|
|
// deliberately independent of evolving application source and is NOT app timing.
|
|
export function geometryBenchmark() {
|
|
const source = new THREE.SphereGeometry(1, 128, 64);
|
|
source.computeBoundingBox();
|
|
source.computeBoundingSphere();
|
|
const buildMs = [];
|
|
for (let trial = 0; trial < 9; trial++) {
|
|
const start = performance.now();
|
|
source.boundsTree = new MeshBVH(source, { indirect: true });
|
|
const elapsed = performance.now() - start;
|
|
if (trial >= 2) buildMs.push(elapsed);
|
|
if (trial < 8) source.boundsTree = undefined;
|
|
}
|
|
const buffers = new Set(Object.values(source.attributes).map(attribute => attribute.array.buffer));
|
|
buffers.add(source.index.array.buffer);
|
|
const geometryBytes = [...buffers].reduce((sum, buffer) => sum + buffer.byteLength, 0);
|
|
const bvhEstimatedBytes = estimateMemoryInBytes(source.boundsTree);
|
|
const counts = [1, 16, 64];
|
|
const variants = ['cloned-direct', 'retained-direct', 'retained-bvh'];
|
|
const results = [];
|
|
const resources = { liveGeometries: 1, liveMaterials: 0, peakGeometries: 1, peakMaterials: 0 };
|
|
function track(resource, kind) {
|
|
resources[`live${kind}`]++;
|
|
resources[`peak${kind}`] = Math.max(resources[`peak${kind}`], resources[`live${kind}`]);
|
|
resource.addEventListener('dispose', () => { resources[`live${kind}`]--; });
|
|
return resource;
|
|
}
|
|
source.addEventListener('dispose', () => { resources.liveGeometries--; });
|
|
try {
|
|
for (const count of counts) {
|
|
const columns = Math.ceil(Math.sqrt(count));
|
|
const rays = Array.from({ length: 128 }, (_, i) => {
|
|
const target = i % count;
|
|
// 25% are deterministic misses; hits are off triangle seams.
|
|
const ray = new THREE.Raycaster(new THREE.Vector3((target % columns) * 3 + (i % 4 === 0 ? 1.4 : 0.173),
|
|
Math.floor(target / columns) * 3 + 0.219, 4), new THREE.Vector3(0, 0, -1));
|
|
ray.firstHitOnly = true;
|
|
return ray;
|
|
});
|
|
const timings = Object.fromEntries(variants.map(variant => [variant, { createMs: [], pickBatchMs: [], disposeMs: [] }]));
|
|
let expected;
|
|
let maximumDistanceError = 0;
|
|
for (let trial = 0; trial < 9; trial++) {
|
|
// Rotate order to reduce a systematic JIT/thermal advantage.
|
|
const order = variants.map((_, index) => variants[(index + trial) % variants.length]);
|
|
for (const variant of order) {
|
|
const start = performance.now();
|
|
const meshes = [];
|
|
for (let i = 0; i < count; i++) {
|
|
const geometry = variant === 'cloned-direct' ? track(source.clone(), 'Geometries') : source;
|
|
if (variant === 'cloned-direct') assert.equal(geometry.boundsTree, undefined);
|
|
const mesh = new THREE.Mesh(geometry, track(new THREE.MeshBasicMaterial(), 'Materials'));
|
|
mesh.raycast = variant === 'retained-bvh' ? acceleratedRaycast : THREE.Mesh.prototype.raycast;
|
|
mesh.position.set((i % columns) * 3, Math.floor(i / columns) * 3, 0);
|
|
mesh.updateMatrixWorld(true);
|
|
mesh.userData.benchmarkIndex = i;
|
|
meshes.push(mesh);
|
|
}
|
|
const created = performance.now();
|
|
const hits = [];
|
|
const actual = [];
|
|
for (const ray of rays) {
|
|
hits.length = 0;
|
|
ray.intersectObjects(meshes, false, hits);
|
|
actual.push(hits.length ? [hits[0].object.userData.benchmarkIndex, hits[0].distance] : null);
|
|
}
|
|
const picked = performance.now();
|
|
if (!expected) expected = actual;
|
|
actual.forEach((hit, index) => {
|
|
assert.equal(hit?.[0], expected[index]?.[0], 'nearest hit identity must match');
|
|
if (hit) {
|
|
const difference = Math.abs(hit[1] - expected[index][1]);
|
|
maximumDistanceError = Math.max(maximumDistanceError, difference);
|
|
assert(difference < 1e-7, 'nearest hit distance must match');
|
|
}
|
|
});
|
|
assert.equal(actual.filter(Boolean).length, 96);
|
|
const disposalStart = performance.now();
|
|
for (const mesh of meshes) {
|
|
if (variant === 'cloned-direct') mesh.geometry.dispose();
|
|
mesh.material.dispose();
|
|
}
|
|
meshes.length = 0;
|
|
const disposed = performance.now();
|
|
assert.equal(resources.liveGeometries, 1);
|
|
assert.equal(resources.liveMaterials, 0);
|
|
if (trial >= 2) {
|
|
timings[variant].createMs.push(created - start);
|
|
timings[variant].pickBatchMs.push(picked - created);
|
|
timings[variant].disposeMs.push(disposed - disposalStart);
|
|
}
|
|
}
|
|
}
|
|
for (const variant of variants) results.push({ count, variant,
|
|
createMs: summarize(timings[variant].createMs), pickBatchMs: summarize(timings[variant].pickBatchMs),
|
|
disposeMs: summarize(timings[variant].disposeMs),
|
|
uniqueGeometriesIncludingTemplate: variant === 'cloned-direct' ? count + 1 : 1,
|
|
geometryTypedArrayBytesIncludingTemplate: geometryBytes * (variant === 'cloned-direct' ? count + 1 : 1),
|
|
materials: count, bvhEstimatedBytesIncludingTemplate: bvhEstimatedBytes,
|
|
nearestHitValidation: { hitRays: 96, missRays: 32, maximumDistanceError } });
|
|
}
|
|
} finally {
|
|
source.boundsTree = undefined;
|
|
source.dispose();
|
|
}
|
|
assert.equal(resources.liveGeometries, 0);
|
|
assert.equal(resources.liveMaterials, 0);
|
|
return { kind: 'Node CPU synthetic dependency microbenchmark', threeRevision: THREE.REVISION,
|
|
fixture: { type: 'SphereGeometry', widthSegments: 128, heightSegments: 64,
|
|
trianglesPerMesh: source.index.count / 3, repeatedMeshes: counts, raysPerBatch: 128,
|
|
warmupTrials: 2, measuredTrials: 7, firstHitOnly: true, bvhIndirect: true },
|
|
bvhBuildMs: summarize(buildMs), geometryBytes, bvhEstimatedBytes, resources, results,
|
|
limitations: [
|
|
'Uses installed three and three-mesh-bvh JavaScript, not the historical dependency code inside frozen dist.',
|
|
'Cloned-direct models deep geometry copies without a BVH; retained-direct isolates sharing; retained-bvh isolates accelerated picking.',
|
|
'Does not invoke application clone/cache/worker/renderer code or verify its ownership implementation.',
|
|
'Typed-array bytes are counted exactly; BVH bytes are library estimates. Neither is JS heap, process RSS, or GPU memory.',
|
|
'Dispose event accounting proves bounded harness resources, not garbage collection or application leak freedom.',
|
|
'Synthetic spheres and fixed rays do not represent an authenticated production assembly, mobile performance, or GPU FPS.',
|
|
] };
|
|
}
|