1c837766cd
Add backend-driven assembly and simulation experiences, MAKE branding, mobile rendering budgets and desktop-only CAD/PCB routes. Improve logo loading progress, document image recovery and URDF request handling; include dev packaging and regression coverage.
110 lines
7.3 KiB
JavaScript
110 lines
7.3 KiB
JavaScript
// Usage: node scripts/plan-assembly-axes.mjs --manifest steps.json --assets parts --out NEW.json
|
|
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
import { resolve, dirname, join } from 'node:path';
|
|
import { createHash } from 'node:crypto';
|
|
import assert from 'node:assert/strict';
|
|
import { NodeIO } from '@gltf-transform/core';
|
|
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
|
|
import { BufferGeometry, BufferAttribute, Matrix4, Quaternion, Vector3 } from 'three';
|
|
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
|
|
import { collider, chooseAxis, VIEW_AXES } from './lib/assembly-axis-planner.mjs';
|
|
|
|
const args = process.argv.slice(2);
|
|
const option = name => args.includes(name) ? args[args.indexOf(name) + 1] : null;
|
|
for (const name of ['--manifest', '--assets', '--out']) assert.ok(option(name), `${name} is required`);
|
|
const source = resolve(option('--manifest')), assets = resolve(option('--assets')), output = resolve(option('--out'));
|
|
assert.ok(output !== source && !existsSync(output), 'Choose a new output; source manifests are never overwritten');
|
|
const raw = JSON.parse(readFileSync(source, 'utf8'));
|
|
const config = validatePackage(raw, 'assembly', 'https://assets.example/manifest.json');
|
|
assert.ok(config.parts.every(p => p.parentId === null), 'First version supports flat rigid parts only; nested moving parents need explicit planning');
|
|
const result = structuredClone(raw), byId = new Map(result.parts.map(p => [p.id, p]));
|
|
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
|
|
const display = new Matrix4().makeRotationFromQuaternion(new Quaternion(...config.displayQuaternion));
|
|
const inverseDisplay = new Quaternion(...config.displayQuaternion).invert();
|
|
const cache = new Map(), colliders = new Map();
|
|
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
|
|
async function getCollider(part) {
|
|
if (colliders.has(part.id)) return colliders.get(part.id);
|
|
if (!cache.has(part.file)) {
|
|
const bytes = readFileSync(join(assets, part.file)), file = config.files.get(part.file);
|
|
assert.equal(bytes.length, file.bytes); assert.equal(hash(bytes), file.sha256);
|
|
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
|
|
cache.set(part.file, await io.readBinary(bytes));
|
|
}
|
|
const doc = cache.get(part.file), scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
|
|
assert.ok(scene, `No GLB scene: ${part.file}`);
|
|
const partMatrix = display.clone().multiply(new Matrix4().compose(new Vector3(...part.position), new Quaternion(...part.quaternion), new Vector3(...part.scale)));
|
|
const chunks = [], indices = [];
|
|
let count = 0;
|
|
scene.traverse(node => {
|
|
assert.ok(!node.getSkin() && !node.getWeights().length, 'Skinned/morphing GLBs need a posed collision mesh');
|
|
const matrix = partMatrix.clone().multiply(new Matrix4().fromArray(node.getWorldMatrix()));
|
|
for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
|
|
assert.equal(primitive.getMode(), 4, 'Only triangle meshes supported');
|
|
assert.equal(primitive.listTargets().length, 0, 'Morph targets require a posed mesh');
|
|
const source = primitive.getAttribute('POSITION');
|
|
assert.ok(source && !source.getNormalized(), 'Unsupported POSITION accessor');
|
|
const position = new BufferAttribute(new Float32Array(source.getArray()), 3);
|
|
position.applyMatrix4(matrix); chunks.push(position.array);
|
|
const idx = primitive.getIndices()?.getArray() ?? Array.from({length: position.count}, (_, i) => i);
|
|
for (const index of idx) indices.push(index + count);
|
|
count += position.count;
|
|
}
|
|
});
|
|
assert.ok(count && indices.length % 3 === 0, `No valid triangles: ${part.file}`);
|
|
const positions = new Float32Array(count * 3); let offset = 0;
|
|
for (const chunk of chunks) { positions.set(chunk, offset); offset += chunk.length; }
|
|
const g = new BufferGeometry().setAttribute('position', new BufferAttribute(positions, 3));
|
|
g.setIndex(new BufferAttribute(new Uint32Array(indices), 1));
|
|
const item = collider(part.id, g); colliders.set(part.id, item); return item;
|
|
}
|
|
|
|
const installed = [], records = [], start = performance.now();
|
|
for (const [index, step] of result.steps.entries()) {
|
|
const parts = step.parts.map(id => byId.get(id));
|
|
const active = await Promise.all(parts.map(getCollider));
|
|
let record = { id: step.id, label: step.label, files: parts.map(p => p.file), originalOffsets: parts.map(p => p.installOffset) };
|
|
if (parts.some(p => p.installation?.type === 'screw' || /螺钉|螺丝|screw/i.test(p.file))) {
|
|
record.status = 'fixed-fastener-axis'; // Do not route screws sideways; tool sweep is separate work.
|
|
} else if (!installed.length) {
|
|
record.status = 'foundation'; parts.forEach(p => { p.installOffset = [0, 0, 0]; });
|
|
} else {
|
|
const axes = structuredClone(VIEW_AXES);
|
|
const localFrame = new Quaternion(...config.displayQuaternion).multiply(new Quaternion(...parts[0].quaternion));
|
|
for (const base of VIEW_AXES) {
|
|
const vector = new Vector3(...base.vector).applyQuaternion(localFrame).normalize().toArray();
|
|
if (!axes.some(a => new Vector3(...a.vector).distanceTo(new Vector3(...vector)) < 1e-6))
|
|
axes.push({ name: `local${base.name}`, label: `沿零件局部 ${base.name} 方向进入`, vector });
|
|
}
|
|
const plan = chooseAxis(active, installed, { axes });
|
|
record = { ...record, ...plan, status: plan.selected ? 'clear-to-seating' : 'needs-review' };
|
|
if (plan.selected) {
|
|
const offset = new Vector3(...plan.selected.vector).multiplyScalar(plan.selected.travel).applyQuaternion(inverseDisplay);
|
|
parts.forEach(p => { p.installOffset = offset.toArray().map(n => Math.abs(n) < 1e-12 ? 0 : n); });
|
|
}
|
|
}
|
|
record.outputOffsets = parts.map(p => p.installOffset); records.push(record);
|
|
installed.push(...active);
|
|
console.log(`${index+1}/${result.steps.length} ${step.label}: ${record.status}${record.selected ? ` ${record.selected.label}` : ''}`);
|
|
}
|
|
// Only the animation offsets change. Sources, assembled poses and step order are immutable.
|
|
assert.deepEqual(result.steps, raw.steps); assert.deepEqual(result.files, raw.files);
|
|
for (const [i,p] of result.parts.entries()) {
|
|
const { installOffset: a, ...actual } = p, { installOffset: b, ...expected } = raw.parts[i];
|
|
assert.deepEqual(actual, expected);
|
|
}
|
|
validatePackage(result, 'assembly', 'https://assets.example/manifest.json');
|
|
mkdirSync(dirname(output), {recursive:true});
|
|
writeFileSync(output, JSON.stringify(result,null,2)+'\n');
|
|
const summary = records.reduce((r,s) => { r[s.status]=(r[s.status]??0)+1;return r; }, {});
|
|
writeFileSync(output.replace(/\.json$/i,'')+'.检查报告.json',JSON.stringify({
|
|
source,sourceSha256:hash(readFileSync(source)),library:'three-mesh-bvh@0.9.17',
|
|
method:'Six display-space axes plus six part-local axes; full triangle BVH surface distance; conservative translational advancement from an exterior AABB.',
|
|
seatingToleranceMeters:0.00015,numericToleranceMeters:0.000001,
|
|
limitations:['Final 0.15 mm seating interval is not collision-certified.', 'Fastener/tool sweeps are not planned.',
|
|
'A needs-review result retains the previous offset, which may collide.', 'No rotations, multi-segment paths, deformable parts or sequence changes.'],
|
|
seconds:(performance.now()-start)/1000,summary,steps:records,
|
|
},null,2)+'\n');
|
|
console.log(JSON.stringify({output,summary,seconds:(performance.now()-start)/1000}));
|