Files
vibemake/scripts/package-duck-left-sequence.mjs
T
Jerry 1c837766cd feat: integrate robot assembly and simulation with resilient loading
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.
2026-10-30 18:38:39 +08:00

112 lines
9.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Match the numbered left-leg CAD list to existing GLBs. Never convert/rewrite GLBs.
import { readFileSync, writeFileSync, readdirSync, mkdirSync, copyFileSync, constants } from 'node:fs';
import { join } from 'node:path';
import { createHash } from 'node:crypto';
import assert from 'node:assert/strict';
import { Matrix4, Vector3, Quaternion } from '../vendor/three/build/three.module.min.js';
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
const root = new URL('..', import.meta.url).pathname;
const input = '/Users/jerry/Downloads/1-0腿装配(L)stp';
const previous = '/Users/jerry/Downloads/小鸭子-扳手装配';
const output = '/Users/jerry/Downloads/小鸭子-左腿编号装配-20261029';
const preview = join(root, 'deliverables/experience-packages/microduck-left-numbered');
const original = JSON.parse(readFileSync(join(previous, '鸭子-拼装步骤-带扳手.json'), 'utf8'));
const alignment = JSON.parse(readFileSync(join(root, 'deliverables/experience-packages/microduck-parts-assembly/alignment-report.json'), 'utf8'));
const byId = new Map(original.parts.map((p) => [p.id, p]));
const sha = (b) => createHash('sha256').update(b).digest('hex');
const numbered = readdirSync(input).filter((f) => /\.st(?:ep|p)$/i.test(f)).map((file) => {
const match = /^(\d+)-(\d+)-(.+)\.st(?:ep|p)$/i.exec(file);
assert.ok(match, `无法读取编号:${file}`);
return { file, major: +match[1], minor: +match[2], label: match[3], name: file.replace(/\.st(?:ep|p)$/i, '') };
}).filter((s) => s.minor !== 0).sort((a, b) => a.major - b.major || a.minor - b.minor);
assert.equal(numbered.length, 52);
assert.deepEqual(numbered.map((s) => s.minor), Array.from({ length: 52 }, (_, i) => i + 1));
// Read only placements/names to disambiguate identical fasteners; geometry stays GLB.
const cadBytes = readFileSync(join(input, '1-0-腿装配(L).STEP'));
const entities = new Map([...cadBytes.toString('latin1').matchAll(/#(\d+)\s*=\s*([\s\S]*?);/g)].map((m) => [m[1], m[2]]));
const refs = (id) => [...entities.get(id).matchAll(/#(\d+)/g)].map((m) => m[1]);
const decode = (s) => s.replace(/\\X2\\(.*?)\\X0\\/g, (_, hex) => String.fromCharCode(...hex.match(/.{4}/g).map((x) => parseInt(x, 16))));
const names = new Map();
for (const [id, e] of entities) if (/^PRODUCT_DEFINITION\s*\(/.test(e)) names.set(id, decode(entities.get(refs(refs(id)[0])[0]).match(/'([^']*)'/)[1]));
const vector = (id) => new Vector3(...[...entities.get(id).matchAll(/\(([^()]*)\)/g)].at(-1)[1].split(',').map(Number));
const axis = (id) => { const [p, z, x] = refs(id).map(vector); return new Matrix4().makeBasis(x, new Vector3().crossVectors(z, x), z).setPosition(p); };
const placements = new Map();
for (const [id, e] of entities) if (/^CONTEXT_DEPENDENT_SHAPE_REPRESENTATION\s*\(/.test(e)) {
const [relation, definition] = refs(id), occurrence = refs(definition)[0];
const [, child] = refs(occurrence), [a, b] = refs(refs(relation).at(-1));
const m = axis(a).multiply(axis(b).invert());
for (const i of [12, 13, 14]) m.elements[i] /= 1000;
placements.set(names.get(child), m);
}
const groups = new Map();
for (const r of alignment.parts.filter((r) => r.group === '腿装配(L)')) {
const key = r.path[2];
if (!groups.has(key)) groups.set(key, { key, label: key.split('@')[0], parts: [] });
groups.get(key).parts.push(byId.get(r.id));
}
const used = new Set(), matches = new Map();
const candidates = (s) => [...groups.values()].filter((g) => !used.has(g.key) && g.label === s.label.replace(/^0914舵机装配1$/, '0914舵机装配'));
const distance = (s, g) => new Vector3().setFromMatrixPosition(placements.get(s.name)).distanceTo(new Vector3(...g.parts[0].position));
// Reserve every unambiguous positional match before assigning moved same-type screws.
for (const s of numbered) {
assert.ok(placements.has(s.name), `总装中未找到 ${s.name}`);
const near = candidates(s).filter((g) => distance(s, g) < 0.0001);
assert.ok(near.length <= 1, `位置有歧义:${s.name}`);
if (near.length) { matches.set(s.name, { group: near[0], moved: false }); used.add(near[0].key); }
}
for (const s of numbered.filter((s) => !matches.has(s.name))) {
const available = candidates(s).sort((a, b) => a.parts[0].file.localeCompare(b.parts[0].file, 'en', { numeric: true }));
assert.ok(available.length && /螺钉/.test(s.label), `无法确定零件匹配:${s.name}`);
const group = available[0];
assert.equal(group.parts.length, 1);
matches.set(s.name, { group, moved: true }); used.add(group.key);
}
const parts = [], steps = [], records = [];
for (const s of numbered) {
const { group, moved } = matches.get(s.name);
const selected = structuredClone(group.parts);
if (moved) {
const p = selected[0], pos = new Vector3(), q = new Quaternion(), scale = new Vector3();
placements.get(s.name).decompose(pos, q, scale);
assert.ok(scale.toArray().every((x) => Math.abs(x - 1) < 1e-8));
p.position = pos.toArray(); p.quaternion = q.normalize().toArray();
p.installOffset = new Vector3(0, 0, 0.025).applyQuaternion(q).toArray();
}
const code = `${s.major}-${s.minor}`;
parts.push(...selected);
steps.push({ id: `left-${code}`, label: `${code} · ${s.label}`, parts: selected.map((p) => p.id) });
records.push({ code, source: s.file, name: s.label, glb: selected.map((p) => p.file), ids: selected.map((p) => p.id),
placement: moved ? '同规格未使用 GLB 实例;位置/朝向采用本次编号总装' : '名称/组件与总装位置匹配;沿用原 GLB 装配姿态',
previousPositions: group.parts.map((p) => p.position), positions: selected.map((p) => p.position) });
}
assert.equal(parts.length, 72);
assert.equal(new Set(parts.map((p) => p.id)).size, 72);
const fileNames = new Set([...parts.map((p) => p.file), ...original.tools.map((t) => t.file)]);
const manifest = { ...original, title: 'Microduck · 左腿 1-1 至 1-52 编号装配',
files: original.files.filter((f) => fileNames.has(f.path)), parts, steps };
validatePackage(manifest, 'assembly', 'http://localhost:8090/manifest.json');
mkdirSync(output, { recursive: true }); mkdirSync(preview, { recursive: true });
for (const f of manifest.files) {
const bytes = readFileSync(join(previous, '零件模型', f.path));
assert.equal(bytes.length, f.bytes); assert.equal(sha(bytes), f.sha256, `GLB 哈希不匹配:${f.path}`);
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
copyFileSync(join(previous, '零件模型', f.path), join(preview, f.path), constants.COPYFILE_FICLONE);
assert.equal(sha(readFileSync(join(preview, f.path))), f.sha256);
}
const filename = '小鸭子-左腿-按编号装配-52步.json';
const json = JSON.stringify(manifest, null, 2) + '\n';
writeFileSync(join(output, filename), json); writeFileSync(join(preview, 'manifest.json'), json);
const csv = [['步骤', '编号文件', '匹配的 GLB', '位置处理'], ...records.map((r) => [r.code, r.source, r.glb.join(';'), r.placement])]
.map((row) => row.map((s) => `"${s.replaceAll('"', '""')}"`).join(',')).join('\n');
writeFileSync(join(output, '编号与GLB对照.csv'), '\ufeff' + csv + '\n');
const unused = [...groups.values()].filter((g) => !used.has(g.key)).flatMap((g) => g.parts.map((p) => p.file));
writeFileSync(join(output, '匹配记录-无需上传.json'), JSON.stringify({ source: input, sourceSha256: sha(cadBytes), records, excludedFromThisLeftLegSequence: unused }, null, 2) + '\n');
writeFileSync(join(output, '上传说明.txt'), `上传文件:${filename}\n\n在小鸭子项目后台“拼装步骤”上传这个 JSON。\n沿用已经上传的零件 GLB,不上传 STEP,不用改 GLB 文件名。\n需包含“内六角扳手.glb”;如果上次尚未补传,请先补传扳手。\n\n本次只做左腿:按数值顺序 1-1 → 1-2 → … → 1-52,共 52 步、72 个 GLB 实例。\n1-0 是总装参考,不是安装步骤。这份目录没有 2-1 等其他部位的编号。\n舵机组件各对应 3 个 GLB,w_61702 轴承组件各对应 5 个 GLB,同一步一起安装。\n重复螺丝按左腿实例和位置匹配,未使用右腿零件。\n\n7 颗螺丝(1-8、1-36 至 1-41)在新编号总装中的位置与旧流程不同,已用同规格现有 GLB 放到新总装的位置;只修改 JSON 中的位姿。其他零件沿用原装配姿态。\n所有 GLB 文件、原始材质与颜色均未修改。标准杯头螺丝保留原有扳手动画;圆头螺丝沿用原来的插入动画。\n旧左腿中未列入这次编号的 5 个零件不加入本流程,也不追加其他身体部位。\n上传后 AI 装配的整体/逐步视图将展示这一版左腿;要恢复全鸭装配可重新上传之前的完整 JSON。\n\n“编号与GLB对照.csv”与“匹配记录-无需上传.json”仅供核对,不要上传到拼装步骤字段。\n已通过当前前端装配格式校验、步骤唯一性/覆盖校验、73 个 GLB 文件与 SHA-256 校验。\n这是按提供顺序制作的展示动画,未校验真实装配工具可达性。\n`);
console.log(JSON.stringify({ output: join(output, filename), steps: steps.length, parts: parts.length, files: manifest.files.length,
movedScrews: records.filter((r) => r.placement.startsWith('同规格')).map((r) => r.code), excluded: unused,
preview: '/deliverables/experience-packages/microduck-left-numbered/manifest.json' }, null, 2));