vehicle-generator/scripts/verify-glb.ts
CRT d8f3a6e3df Vehicle Generator 0.1.0 (alpha)
Procedural, game-ready vehicles for three.js: 13 body styles, blending, seeded
random vehicles, three LODs, colliders, 13 parametric mods, paint and livery,
a rig that drives, and GLB export that a game can load and drive. Ships with a
studio (browser or Tauri desktop app) and a Play mode.
2026-10-11 00:22:23 +00:00

151 lines
5.9 KiB
TypeScript

/**
* GLB round trip: export every body style, load it back, and check that what
* a game needs survived — not just that a file was written.
*
* - the same meshes, triangles and vertex colours;
* - every rigged node by name, at the same pivot;
* - `createRig()` on the LOADED scene finds the same wheels and openables and
* moves them to the same place as the rig of the generated vehicle;
* - the animation clips, by name, and that they target nodes that exist.
*
* bun scripts/verify-glb.ts
*/
import './glb-node.ts'
import { Box3, Mesh, type Object3D, Vector3 } from 'three'
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
import {
BODY_STYLES,
createRig,
exportVehicleGlb,
generateVehicle,
type OpenablePart,
preset,
randomSpec,
type VehicleSpec,
} from '../src/generator/index.ts'
const failures: string[] = []
let checks = 0
function expect(label: string, ok: boolean, detail = ''): void {
checks += 1
if (!ok) {
failures.push(label)
console.log(` FAIL ${label}${detail ? ` — ${detail}` : ''}`)
}
}
interface Summary { meshes: number; triangles: number; colours: number; names: Set<string> }
function summarise(root: Object3D): Summary {
let meshes = 0, triangles = 0, colours = 0
const names = new Set<string>()
root.traverse((o) => {
names.add(o.name)
if (!(o instanceof Mesh)) return
meshes += 1
const index = o.geometry.getIndex()
triangles += (index ? index.count : o.geometry.getAttribute('position').count) / 3
if (o.geometry.getAttribute('color')) colours += 1
})
return { meshes, triangles, colours, names }
}
const find = (root: Object3D, name: string): Object3D | undefined => {
let hit: Object3D | undefined
root.traverse((o) => { if (!hit && o.name === name) hit = o })
return hit
}
const worldBox = (node: Object3D): Box3 => {
node.updateWorldMatrix(true, true)
return new Box3().setFromObject(node)
}
const loader = new GLTFLoader()
let totalBytes = 0
const cases: [string, VehicleSpec][] = [
...BODY_STYLES.map((s) => [s, preset(s)] as [string, VehicleSpec]),
['random 42', randomSpec(42)],
['random 314', randomSpec(314)],
]
for (const [label, spec] of cases) {
const vehicle = generateVehicle(spec, { lods: [0] })
const source = vehicle.lods[0]!.group
const buffer = await exportVehicleGlb(vehicle)
totalBytes += buffer.byteLength
const header = new DataView(buffer)
expect(`${label}: GLB magic and version`, header.getUint32(0, true) === 0x46546c67 && header.getUint32(4, true) === 2)
const gltf = await loader.parseAsync(buffer, '')
const loaded = gltf.scene
const a = summarise(source)
const b = summarise(loaded)
expect(`${label}: mesh count preserved`, a.meshes === b.meshes, `${a.meshes} → ${b.meshes}`)
expect(`${label}: triangle count preserved`, a.triangles === b.triangles, `${a.triangles} → ${b.triangles}`)
expect(`${label}: vertex colours preserved`, a.colours === b.colours)
const missing = [...a.names].filter((n) => n && !b.names.has(n))
expect(`${label}: every node name survives`, missing.length === 0, missing.slice(0, 5).join(', '))
// Pivots: every rigged node at the same place.
let drift = 0
source.updateMatrixWorld(true)
loaded.updateMatrixWorld(true)
source.traverse((o) => {
if (!o.userData.vehicleGenerator) return
const twin = find(loaded, o.name)
if (!twin) { drift = Infinity; return }
drift = Math.max(drift, o.getWorldPosition(new Vector3()).distanceTo(twin.getWorldPosition(new Vector3())))
})
expect(`${label}: pivots in place after import`, drift < 1e-4, `${drift}`)
// The rig, rebuilt from the imported file alone.
const rigA = vehicle.rig
const rigB = createRig(loaded)
expect(`${label}: imported rig finds the wheels`, rigB.wheels.length === 4 && rigB.wheels.filter((w) => w.steer).length === 2)
expect(`${label}: imported rig finds the openables`,
[...rigA.openables].sort().join() === [...rigB.openables].sort().join(),
`${rigA.openables.join()} vs ${rigB.openables.join()}`)
for (const part of rigA.openables as OpenablePart[]) {
rigA.open(part, 0.8)
rigB.open(part, 0.8)
const na = find(source, part)!
const nb = find(loaded, part)!
const ba = worldBox(na)
const bb = worldBox(nb)
const d = ba.min.distanceTo(bb.min) + ba.max.distanceTo(bb.max)
expect(`${label}: ${part} opens the same after import`, d < 2e-3, `${d.toFixed(5)}`)
rigA.open(part, 0)
rigB.open(part, 0)
}
rigA.setSteer(-0.35)
rigB.setSteer(-0.35)
rigA.setWheelSpin(1.2)
rigB.setWheelSpin(1.2)
for (const id of ['FL', 'FR', 'RL', 'RR']) {
const ba = worldBox(find(source, `wheel_${id}`)!)
const bb = worldBox(find(loaded, `wheel_${id}`)!)
const d = ba.min.distanceTo(bb.min) + ba.max.distanceTo(bb.max)
expect(`${label}: wheel ${id} steers and rolls the same after import`, d < 2e-3, `${d.toFixed(5)}`)
}
const steerA = find(source, 'steering_wheel')
const steerB = find(loaded, 'steering_wheel')
if (steerA) expect(`${label}: steering wheel turns after import`, steerB !== undefined && Math.abs(steerA.quaternion.angleTo(steerB.quaternion)) < 1e-4)
// Animation clips survive by name and target real nodes.
const clipsA = vehicle.animations.map((c) => c.name).sort()
const clipsB = gltf.animations.map((c) => c.name).sort()
expect(`${label}: animation clips survive`, clipsA.join() === clipsB.join(), `${clipsA.length} → ${clipsB.length}`)
const dangling = gltf.animations.flatMap((c) => c.tracks.map((t) => t.name.split('.')[0]!)).filter((n) => !find(loaded, n))
expect(`${label}: every track targets a node`, dangling.length === 0, dangling.slice(0, 3).join())
vehicle.dispose()
}
console.log(`${cases.length} vehicles exported and re-imported · ${(totalBytes / 1024 / 1024).toFixed(1)} MB of GLB`)
console.log(`${checks} checks · ${failures.length} failed`)
console.log(failures.length === 0 ? 'All checks passed.' : 'Checks FAILED.')
if (failures.length > 0) process.exitCode = 1