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.
This commit is contained in:
Jerry
2026-10-30 18:38:39 +08:00
parent 8212c41bed
commit 1c837766cd
391 changed files with 46889 additions and 212 deletions
+188
View File
@@ -0,0 +1,188 @@
// Restore the supplied loose GLBs using the reference assembly, without changing their geometry/materials.
import { Document, NodeIO } from '@gltf-transform/core';
import { mergeDocuments, unpartition } from '@gltf-transform/functions';
import { Matrix4, Vector3, Quaternion } from '../vendor/three/build/three.module.min.js';
import { mkdirSync, readdirSync, readFileSync, writeFileSync, cpSync, rmSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import assert from 'node:assert/strict';
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
const ROOT = fileURLToPath(new URL('..', import.meta.url));
const args = process.argv.slice(2);
const option = (name, fallback) => args.includes(name) ? args[args.indexOf(name) + 1] : fallback;
const SOURCE = resolve(option('--parts', '/Users/jerry/Downloads/glb分散零件'));
const REFERENCE = resolve(option('--reference', '/Users/jerry/Downloads/机器人.glb'));
const OUT = join(ROOT, 'deliverables/experience-packages');
const NAME = 'microban-parts-assembly';
const DIRECTORY = join(OUT, NAME);
const io = new NodeIO();
const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
const saveJson = (path, data) => writeFileSync(path, JSON.stringify(data, null, 2) + '\n');
const reference = await io.read(REFERENCE);
const references = new Map(reference.getRoot().listNodes().filter((node) => node.getMesh()).map((node) => [node.getName(), node]));
const sources = readdirSync(SOURCE).filter((name) => /\.glb$/i.test(name)).sort();
assert.equal(sources.length, references.size, '分件数量与参考总装不一致');
// The supplied exporters bake an extra -90° X rotation into loose geometry.
// Reversing it gives EXACTLY the same triangle surfaces as the reference.
const undoExportRotation = new Matrix4().makeRotationX(Math.PI / 2);
const displayQuaternion = [-Math.SQRT1_2, 0, 0, Math.SQRT1_2];
const root = new Document();
const scene = root.createScene('机器人 · 分件重组');
root.getRoot().setDefaultScene(scene);
const templates = new Map();
const files = [], records = [], parts = [];
let maxPositionError = 0, triangles = 0;
// Compare surfaces independently of vertex ordering, winding and material splits.
// Two supplied parts have different material splits but identical surfaces.
function surface(mesh, undoRotation) {
const counts = new Map();
let count = 0;
for (const primitive of mesh.listPrimitives()) {
assert.equal(primitive.getMode(), 4, '只支持三角网格');
const positions = primitive.getAttribute('POSITION').getArray();
const indices = primitive.getIndices()?.getArray() || Array.from({ length: positions.length / 3 }, (_, i) => i);
for (let i = 0; i < indices.length; i += 3) {
const vertices = [];
for (let k = 0; k < 3; k++) {
const offset = indices[i + k] * 3;
const [x, y, z] = positions.subarray(offset, offset + 3);
vertices.push((undoRotation ? [x, -z, y] : [x, y, z]).join(','));
}
const key = vertices.sort().join(';');
counts.set(key, (counts.get(key) || 0) + 1);
count++;
}
}
return { counts, count };
}
// Exported copies often differ only in object names. Keep one byte-identical
// source GLB per visual definition; each instance still has its original pose.
function visualFingerprint(bytes) {
const jsonLength = bytes.readUInt32LE(12);
const json = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString());
const clean = (value) => Array.isArray(value) ? value.map(clean) : value && typeof value === 'object'
? Object.fromEntries(Object.keys(value).sort().filter((key) => key !== 'name').map((key) => [key, clean(value[key])])) : value;
const hash = createHash('sha256');
hash.update(JSON.stringify(clean(json)));
hash.update(bytes.subarray(20 + jsonLength));
return hash.digest('hex');
}
rmSync(DIRECTORY, { recursive: true, force: true });
mkdirSync(join(DIRECTORY, 'parts'), { recursive: true });
for (const filename of sources) {
const path = join(SOURCE, filename), bytes = readFileSync(path);
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
const source = await io.read(path);
assert.equal(source.getRoot().listNodes().length, 1, `分件层级改变:${filename}`);
const node = source.getRoot().listNodes()[0];
assert.deepEqual(node.getMatrix(), new Matrix4().toArray(), `分件已带额外变换:${filename}`);
const target = references.get(node.getName());
assert.ok(target, `无法匹配:${filename}`);
const a = surface(target.getMesh(), false), b = surface(node.getMesh(), true);
assert.equal(a.count, b.count, `三角面数量改变:${filename}`);
assert.equal(a.counts.size, b.counts.size, `表面不匹配:${filename}`);
for (const [key, count] of a.counts) assert.equal(b.counts.get(key), count, `表面不匹配:${filename}`);
triangles += a.count;
const referenceWorld = new Matrix4().fromArray(target.getWorldMatrix());
const expected = referenceWorld.clone().multiply(undoExportRotation);
const position = new Vector3(), rotation = new Quaternion(), scale = new Vector3();
expected.decompose(position, rotation, scale);
rotation.normalize();
const restored = new Matrix4().compose(position, rotation, scale);
let error = 0;
for (const primitive of node.getMesh().listPrimitives()) {
const positions = primitive.getAttribute('POSITION').getArray();
for (let i = 0; i < positions.length; i += 3) {
const point = new Vector3().fromArray(positions, i);
error = Math.max(error, point.clone().applyMatrix4(expected).distanceTo(point.applyMatrix4(restored)));
}
}
assert.ok(error < 1e-6, `恢复后的顶点误差过大:${filename} ${error}`);
maxPositionError = Math.max(maxPositionError, error);
const fingerprint = visualFingerprint(bytes);
let template = templates.get(fingerprint);
if (!template) {
const file = `parts/${filename}`;
cpSync(path, join(DIRECTORY, file));
files.push({ path: file, bytes: bytes.length, sha256: sha(bytes) });
const copied = mergeDocuments(root, source);
const mesh = copied.get(node).getMesh();
copied.get(source.getRoot().listScenes()[0]).dispose();
copied.get(node).dispose();
template = { file, mesh };
templates.set(fingerprint, template);
}
const id = `part-${String(parts.length + 1).padStart(3, '0')}`;
const part = { id, file: template.file, position: position.toArray(), quaternion: rotation.toArray(), scale: scale.toArray(),
installOffset: [0.035, position.y > 0 ? 0.055 : -0.055, 0.035] };
parts.push(part);
scene.addChild(root.createNode(node.getName()).setMesh(template.mesh).setTranslation(part.position).setRotation(part.quaternion).setScale(part.scale));
records.push({ id, source: filename, sourceSha256: sha(bytes), file: part.file, referenceNode: target.getName(),
referenceGroup: target.getParentNode()?.getName(), triangleCount: a.count, maxPositionErrorMeters: error, surfaceMatches: true });
}
assert.equal(new Set(records.map((record) => record.referenceNode)).size, references.size, '存在重复匹配或缺件');
const groups = [
['foot _1_', '脚部 1'], ['foot _2_', '脚部 2'], ['ankle_block _2_', '踝部 1'], ['ankle_block _3_', '踝部 2'],
['tibia _1_', '小腿 1'], ['tibia _2_', '小腿 2'], ['femur _1_', '大腿 1'], ['femur _2_', '大腿 2'],
['hip_block _1_', '髋部支架 1'], ['hip_block _3_', '髋部支架 2'], ['hip _1_', '髋部 1'], ['hip _2_', '髋部 2'],
['trunk _1_', '躯干'], ['shoulder _1_', '肩部 1'], ['shoulder _2_', '肩部 2'],
['humerus _1_', '上臂 1'], ['humerus _2_', '上臂 2'], ['radius _1_', '前臂 1'], ['radius _2_', '前臂 2'], ['head _1_', '头部'],
];
const label = (name) => {
for (const [pattern, value] of [[/^(STP39|BTS2)/, '螺钉'], [/^XL330/, '舵机'], [/^(foot)/, '脚板'], [/^tibia/, '小腿外壳'], [/^femur/, '大腿外壳'], [/^chest/, '胸部面板'], [/^head/, '头部外壳'], [/^raspberry/, '主控板'], [/^battery/, '电池'], [/^switch/, '开关'], [/^(.*shim|washer)/, '垫片'], [/^spacer/, '隔柱'], [/^DC15/, '关节连接件']]) if (pattern.test(name)) return value;
return '结构零件';
};
const rank = (name) => /^(STP39|BTS2)/.test(name) ? 4 : /(shim|washer|spacer|DC15)/.test(name) ? 3 : /^XL330/.test(name) ? 1 : 0;
const ordered = groups.flatMap(([group, title]) => records.filter((item) => item.referenceGroup === group)
.sort((a, b) => rank(a.source) - rank(b.source) || a.source.localeCompare(b.source, 'en', { numeric: true }))
.map((item) => ({ ...item, title })));
assert.equal(ordered.length, parts.length, '存在未编排的子总成');
const steps = ordered.map((item, i) => ({ id: `step-${i + 1}`, label: `${item.title} · ${label(item.source)}`, parts: [item.id] }));
const manifest = { schemaVersion: 1, kind: 'assembly', title: 'Microban · 275 零件装配', unit: 'meter', displayQuaternion, files, parts, steps };
validatePackage(manifest, 'assembly', `https://assets.example.com/${NAME}/manifest.json`);
saveJson(join(DIRECTORY, 'manifest.json'), manifest);
const report = { referenceSha256: sha(readFileSync(REFERENCE)), partCount: parts.length, uniqueGlbs: files.length,
triangleCount: triangles, maxPositionErrorMeters: maxPositionError, allTriangleSurfacesMatch: true,
materialSource: 'Unmodified supplied loose GLBs; these differ from the reference model materials.',
coordinateMethod: 'Reference world matrix × inverse of loose-export X(-90deg) rotation; no independent centering/scaling.',
stepOrder: 'Presentation sequence by source subassembly, not a validated manufacturing process.', parts: records };
saveJson(join(DIRECTORY, 'alignment-report.json'), report);
writeFileSync(join(DIRECTORY, 'README.txt'), `Microban 分件装配包\n\n${parts.length} 个零件实例,根据完整机器人 GLB 的原始变换恢复。\n${files.length} 个独立 GLB:几何、材质和内嵌变换完全相同的分件复用一份原文件,减少下载与解析。\n所有模型三角面已逐件核对;总计 ${triangles} 个三角面。\n恢复位置的最大数值误差:${maxPositionError.toExponential(3)} 米。\nGLB 原文件与材质未改动。新分件的材质与旧整机有所不同,预览使用新分件自带材质。\n完整校验映射见 alignment-report.json。\n\n上传此 ZIP,后端解压后将 manifest.json 的地址写入 assemblyManifestUrl。\n显示整体时,275 个实例按原始位置组成机器人。逐步装配时,每步安装一个零件,可播放、暂停或拖动进度。\n安装最终位置来自原模型;显示顺序按子总成编排,用于展示,不代表已验证的制造工艺。\n`);
await root.transform(unpartition());
const assembledFile = join(OUT, 'microban-reassembled.glb');
await io.write(assembledFile, root);
// Verify that serializing the combined GLB has not changed any recovered pose.
const reread = await io.read(assembledFile);
assert.equal(reread.getRoot().listNodes().filter((node) => node.getMesh()).length, parts.length);
let exportedPositionError = 0;
for (const node of reread.getRoot().listNodes()) {
const expected = new Matrix4().fromArray(references.get(node.getName()).getWorldMatrix()).multiply(undoExportRotation);
const exported = new Matrix4().fromArray(node.getWorldMatrix());
for (const primitive of node.getMesh().listPrimitives()) {
const positions = primitive.getAttribute('POSITION').getArray();
for (let i = 0; i < positions.length; i += 3) {
const point = new Vector3().fromArray(positions, i);
exportedPositionError = Math.max(exportedPositionError, point.clone().applyMatrix4(expected).distanceTo(point.applyMatrix4(exported)));
}
}
}
assert.ok(exportedPositionError < 1e-6, '合并 GLB 导出后的顶点误差过大');
report.combinedGlbPositionErrorMeters = exportedPositionError;
report.combinedGlbSha256 = sha(readFileSync(assembledFile));
saveJson(join(DIRECTORY, 'alignment-report.json'), report);
const zip = join(OUT, NAME + '.zip');
rmSync(zip, { force: true });
execFileSync('zip', ['-q', '-r', zip, '.'], { cwd: DIRECTORY });
execFileSync('unzip', ['-tq', zip]);
console.log(JSON.stringify({ package: zip, combined: assembledFile, parts: parts.length, uniqueGlbs: files.length,
triangles, maxPositionErrorMeters: maxPositionError, packageMB: readFileSync(zip).length / 1048576 }, null, 2));
+162
View File
@@ -0,0 +1,162 @@
// Recover the supplied GLBs' assembly poses from their matching SolidWorks STEP.
// GLB bytes (including materials, colors and textures) are never rewritten.
import { readFileSync, writeFileSync, readdirSync, mkdirSync, copyFileSync, constants } from 'node:fs';
import { resolve, join, extname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
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 = fileURLToPath(new URL('..', import.meta.url));
const args = process.argv.slice(2);
const option = (name, fallback) => args.includes(name) ? args[args.indexOf(name) + 1] : fallback;
const source = resolve(option('--parts', '/Users/jerry/Downloads/鸭子glb零件'));
const reference = resolve(option('--reference', '/Users/jerry/Downloads/鸭子.zip'));
const output = resolve(option('--out', join(ROOT, 'deliverables/experience-packages/microduck-parts-assembly')));
const sha = (value) => createHash('sha256').update(value).digest('hex');
const save = (path, data) => writeFileSync(path, JSON.stringify(data, null, 2) + '\n');
const stepBytes = extname(reference).toLowerCase() === '.zip'
? execFileSync('python3', ['-c', "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); n=[n for n in z.namelist() if n.lower().endswith(('.step','.stp'))]; assert len(n)==1; sys.stdout.buffer.write(z.read(n[0]))", reference], { maxBuffer: 100 * 1024 * 1024 })
: readFileSync(reference);
// Names are STEP X2 escapes; ASCII parsing preserves all geometry/assembly data.
const entities = new Map([...stepBytes.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 = (name) => name.replace(/\\X2\\(.*?)\\X0\\/g, (_, hex) => String.fromCharCode(...hex.match(/.{4}/g).map((x) => parseInt(x, 16))));
const names = new Map();
for (const [id, entity] of entities) if (/^PRODUCT_DEFINITION\s*\(/.test(entity)) {
const product = entities.get(refs(refs(id)[0])[0]);
names.set(id, decode(product.match(/'([^']*)'/)[1]));
}
function vector(id) {
const inner = [...entities.get(id).matchAll(/\(([^()]*)\)/g)].at(-1)[1];
return new Vector3(...inner.split(',').map(Number));
}
function axis(id) {
const [p, z, x] = refs(id).map(vector);
const y = new Vector3().crossVectors(z, x);
return new Matrix4().makeBasis(x, y, z).setPosition(p);
}
const occurrences = [];
for (const [id, entity] of entities) if (/^CONTEXT_DEPENDENT_SHAPE_REPRESENTATION\s*\(/.test(entity)) {
const [relation, definition] = refs(id), occurrence = refs(definition)[0];
const [parent, child] = refs(occurrence);
const [a, b] = refs(refs(relation).at(-1));
occurrences.push({ id: occurrence, parent, child, matrix: axis(a).multiply(axis(b).invert()) });
}
occurrences.sort((a, b) => Number(a.id) - Number(b.id));
const children = new Map();
for (const item of occurrences) {
if (!children.has(item.parent)) children.set(item.parent, []);
children.get(item.parent).push(item);
}
const roots = [...names.keys()].filter((id) => !occurrences.some((item) => item.child === id));
assert.equal(roots.length, 1, 'STEP 必须只有一个总装根节点');
const leaves = [];
function walk(id, matrix, path) {
if (!children.has(id)) leaves.push({ label: names.get(id), matrix, path });
else for (const child of children.get(id)) walk(child.child, matrix.clone().multiply(child.matrix), [...path, `${names.get(child.child)}@${child.id}`]);
}
walk(roots[0], new Matrix4(), [names.get(roots[0])]);
const filenames = readdirSync(source).filter((name) => /\.glb$/i.test(name));
const baseName = (name) => name.slice(0, -4).replace(/\.\d{3}$/, '');
const suffix = (name) => Number(name.match(/\.(\d{3})\.glb$/i)?.[1] ?? 0);
const sources = new Map();
for (const filename of filenames) {
const base = baseName(filename);
if (!sources.has(base)) sources.set(base, []);
sources.get(base).push(filename);
}
for (const [label, files] of sources) {
files.sort((a, b) => suffix(a) - suffix(b));
assert.equal(files.length, leaves.filter((leaf) => leaf.label === label).length, `零件数量不匹配:${label}`);
}
assert.equal(filenames.length, leaves.length, 'GLB 与 STEP 实例数量不匹配');
mkdirSync(output, { recursive: true });
const files = [], parts = [], records = [];
const used = new Map();
for (const [index, leaf] of leaves.entries()) {
const occurrenceIndex = used.get(leaf.label) ?? 0;
const filename = sources.get(leaf.label)?.[occurrenceIndex];
assert.ok(filename, `缺少分件:${leaf.label}`);
used.set(leaf.label, occurrenceIndex + 1);
const bytes = readFileSync(join(source, filename));
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
const glb = JSON.parse(bytes.subarray(20, 20 + bytes.readUInt32LE(12)).toString());
assert.equal(glb.nodes.length, 1, `GLB 层级已改变:${filename}`);
assert.ok(!['matrix', 'translation', 'rotation', 'scale'].some((key) => key in glb.nodes[0]), `GLB 已带额外变换:${filename}`);
const matrix = leaf.matrix.clone();
for (const n of [12, 13, 14]) matrix.elements[n] /= 1000; // STEP millimeters → GLB meters.
const position = new Vector3(), quaternion = new Quaternion(), scale = new Vector3();
matrix.decompose(position, quaternion, scale);
quaternion.normalize();
assert.ok(scale.toArray().every((n) => Math.abs(n - 1) < 1e-8), `STEP 包含非刚性变换:${filename}`);
const restored = new Matrix4().compose(position, quaternion, new Vector3(1, 1, 1));
assert.ok(Math.max(...matrix.elements.map((n, i) => Math.abs(n - restored.elements[i]))) < 1e-8);
const group = leaf.path[1].split('@')[0];
let offset;
if (/螺钉/.test(leaf.label)) offset = new Vector3(0, 0, 0.025).applyQuaternion(quaternion);
else if (/^w_61702/.test(leaf.label)) offset = new Vector3(0.025, 0, 0).applyQuaternion(quaternion);
else if (/腿/.test(group)) offset = new Vector3(0, 0, position.z >= 0 ? 0.055 : -0.055);
else if (/嘴/.test(group)) offset = new Vector3(0, 0.055, 0);
else if (/头|脖/.test(group)) offset = new Vector3(-0.055, 0, 0);
else offset = new Vector3(0, 0.055, 0);
const part = { id: `duck-part-${String(index + 1).padStart(3, '0')}`, file: filename, parentId: null,
position: position.toArray(), quaternion: quaternion.toArray(), scale: [1, 1, 1], installOffset: offset.toArray() };
parts.push(part);
files.push({ path: filename, bytes: bytes.length, sha256: sha(bytes) });
copyFileSync(join(source, filename), join(output, filename), constants.COPYFILE_FICLONE);
assert.equal(sha(readFileSync(join(output, filename))), sha(bytes), '复制后 GLB 内容发生变化');
records.push({ ...leaf, matrix: matrix.toArray(), id: part.id, file: filename, group,
sourceNode: glb.nodes[0].name, materials: (glb.materials ?? []).map((material) => material.name), sha256: sha(bytes) });
}
// Display sequence, not a collision-checked manufacturing process.
// Repeated fasteners/servo components/bearing components are installed as groups.
const groupOrder = ['躯干装配', '腿装配 (R)', '腿装配(L)', '脖子装配', '头部', '嘴装配'];
const prettyGroup = (name) => ({ '腿装配 (R)': '右腿', '腿装配(L)': '左腿', '躯干装配': '躯干', '脖子装配': '颈部', '嘴装配': '嘴部' })[name] || name;
const rank = (name) => /^(trunk_base|foot_left|镜向foot_left)$/.test(name) ? 0 : /螺钉/.test(name) ? 5 : /shell/.test(name) ? 4 : /^(主舵|副舵|舵机主体)$/.test(name) ? 2 : /^w_|轴承/.test(name) ? 3 : 1;
const labels = {
trunk_base: '躯干底架', banana_pcb_locker: '板卡固定件', np_f970: '电池', power_support: '电源支架',
right_shell: '右侧外壳', '镜向left_shell': '左侧外壳', IMU: '惯性传感器', trunk_shell_left: '躯干盖板',
foot_left: '左脚脚板', '镜向foot_left': '右脚脚板', sole_left: '左脚鞋底', '镜向sole_left': '右脚鞋底',
ankle_left: '左踝支架', '镜向ankle_left': '右踝支架', left_upper_leg: '左大腿支架', '镜向left_upper_leg': '右大腿支架',
hip_I: '髋部连接件', leg: '腿部连杆', bearing_roll: '轴承支架', yaw2roll: '关节连接件',
upper_leg_rigidity_plate: '左大腿加强板', '镜向upper_leg_rigidity_plate': '右大腿加强板',
neck_holder: '颈部支架', 'neck_pitch-1': '颈部俯仰连接件', motor_support: '头部电机支架',
m12_lens_holder: '镜头固定座', lens: '镜头', face_part: '头部前面板', yaw_roll_motion: '头部转动连接件',
'noenoeil-': '眼部组件', 'bottom_head_shell-2': '头部下壳', 'top_head_shell-2': '头部上壳',
'BU elec_rpi_robot_hat_without_header': '无排针控制板', elec_rpi_robot_hat_with_header: '带排针控制板',
soft_mouth_top: '上嘴软质件', jaw: '下颌支架', jaw_soft: '下嘴软质件',
};
const steps = [];
for (const group of groupOrder) {
const batches = new Map();
for (const item of records.filter((r) => r.group === group)) {
const parentPath = item.path.slice(0, -1).join('/');
const kind = /^(主舵|副舵|舵机主体)$/.test(item.label) ? '舵机组件' : /^w_61702/.test(item.label) ? '轴承组件' : item.label;
const key = `${parentPath}/${kind}`;
if (!batches.has(key)) batches.set(key, { label: kind, parts: [], rank: rank(item.label) });
batches.get(key).parts.push(item.id);
}
for (const batch of [...batches.values()].sort((a, b) => a.rank - b.rank)) {
steps.push({ id: `duck-step-${String(steps.length + 1).padStart(3, '0')}`, label: `${prettyGroup(group)} · ${labels[batch.label] || batch.label}${batch.parts.length > 1 ? `(${batch.parts.length} 件)` : ''}`, parts: batch.parts });
}
}
const manifest = { schemaVersion: 1, kind: 'assembly', title: 'Microduck · 292 零件装配', unit: 'meter',
// Original STEP uses -X as up. Rotate the entire assembly once for the viewer.
displayQuaternion: [0, 0, -Math.SQRT1_2, Math.SQRT1_2], files, parts, steps };
validatePackage(manifest, 'assembly', 'https://assets.example.com/microduck/manifest.json');
save(join(output, 'manifest.json'), manifest);
save(join(output, 'alignment-report.json'), {
stepSha256: sha(stepBytes), partCount: parts.length, typeCount: sources.size, stepCount: steps.length,
method: 'STEP parent × child placements; translations converted from millimeters to meters. GLB local axes checked against the matching CAD surfaces.',
repeatedInstances: 'Same-name copies assigned in numeric GLB filename order to STEP occurrence traversal order. Exported loose GLBs have no original instance transforms.',
materials: 'Every supplied GLB is copied byte-for-byte; no material, texture, color or geometry overrides.',
sequence: 'Presentation sequence and insertion offsets; not a validated manufacturing or collision-free procedure.',
parts: records.map(({ matrix, ...record }) => ({ ...record, worldMatrix: matrix })),
});
console.log(JSON.stringify({ output, files: files.length, parts: parts.length, steps: steps.length,
totalMiB: files.reduce((sum, file) => sum + file.bytes, 0) / 1048576 }, null, 2));
+73
View File
@@ -0,0 +1,73 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { BoxGeometry } from 'three';
import { collider, checkAxis, chooseAxis, checkFiniteAxis } from './lib/assembly-axis-planner.mjs';
const box = (id, size, position) => collider(id, new BoxGeometry(...size).translate(...position));
test('a part fits down an open pocket while the side route hits the wall', () => {
const moving = [box('part',[0.8,0.3,0.8],[0,0.25,0])];
const obstacles = [box('floor',[2,0.2,2],[0,0,0]), box('right',[0.2,1,2],[0.7,0.6,0]), box('left',[0.2,1,2],[-0.7,0.6,0])];
assert.equal(checkAxis(moving,obstacles,[1,0,0]).status,'blocked-or-touching');
assert.equal(chooseAxis(moving,obstacles).selected.name,'+Y');
});
test('conservative advancement cannot jump over a very thin obstruction', () => {
const moving = [box('part',[0.001,0.001,0.001],[0,0,0])];
const obstacles = [box('foil',[0.000001,1,1],[0.02,0,0])];
assert.equal(checkAxis(moving,obstacles,[1,0,0]).status,'blocked-or-touching');
});
test('closed enclosure does not produce a fake valid axis or contained start', () => {
const moving=[box('part',[0.1,0.1,0.1],[0,0,0])], walls=[];
for (let axis=0;axis<3;axis++) for (const sign of [-1,1]) {
const size=[1,1,1],p=[0,0,0];size[axis]=0.1;p[axis]=sign*0.5;
walls.push(box(`wall${axis}${sign}`,size,p));
}
assert.equal(chooseAxis(moving,walls).selected,null);
});
test('insufficient query budget reports review, never a collision-free result', () => {
const moving=[box('part',[0.1,0.1,0.1],[0,0,0])], obstacles=[box('wall',[1,0.1,1],[0,-0.2,0])];
const result=checkAxis(moving,obstacles,[0,1,0],{maxIterations:0});
assert.equal(result.status,'needs-review');
});
test('part-local axes work when the complete assembly is tilted in the viewer', () => {
const angle=0.65, make=(id,s,p)=>collider(id,new BoxGeometry(...s).translate(...p).rotateZ(angle));
const moving=[make('part',[0.8,0.3,0.8],[0,0.25,0])];
const obstacles=[make('floor',[2,0.2,2],[0,0,0]),make('right',[0.2,1,2],[0.7,0.6,0]),make('left',[0.2,1,2],[-0.7,0.6,0])];
const result=checkAxis(moving,obstacles,[-Math.sin(angle),Math.cos(angle),0]);
assert.equal(result.status,'clear-to-seating');
});
test('touching subcomponents move as a rigid group without colliding with each other', () => {
const moving=[box('a',[0.1,0.1,0.1],[0,0.15,0]),box('b',[0.1,0.1,0.1],[0.1,0.15,0])];
const obstacles=[box('floor',[1,0.2,1],[0,0,0])];
const result=checkAxis(moving,obstacles,[0,1,0]);
assert.equal(result.status,'clear-to-seating');
});
test('finite entry does not start beyond an unrelated opposite limb', () => {
const moving=[box('screw',[.002,.002,.004],[0,0,0])];
const obstacles=[box('opposite-leg',[.03,.03,.03],[0,0,.1])];
assert.equal(checkAxis(moving,obstacles,[0,0,1]).status,'blocked-or-touching');
const result=checkFiniteAxis(moving,obstacles,[0,0,1],.02);
assert.equal(result.status,'foundation');
assert.equal(result.travel,.02);
assert.equal(result.relevantObstacles,0);
});
test('finite entry still detects a thin barrier and a contained start', () => {
const moving=[box('screw',[.002,.002,.004],[0,0,0])];
const foil=[box('foil',[.03,.03,.000001],[0,0,.01])];
assert.equal(checkFiniteAxis(moving,foil,[0,0,1],.02).status,'blocked-or-touching');
const solid=[box('enclosure',[.1,.1,.1],[0,0,0])];
assert.equal(checkFiniteAxis(moving,solid,[0,0,1],.02).status,'blocked-or-touching');
});
test('clear short paths reach the seating endpoint without a floating-point stall', () => {
const moving=[box('part',[.002,.002,.002],[0,.015,0])];
const obstacles=[box('base',[.1,.002,.1],[0,0,0])];
for(const minimumTravel of [.003,.035,.055,.07,.137]) {
const result=checkAxis(moving,obstacles,[0,1,0],{minimumTravel});
assert.equal(result.status,'clear-to-seating');
assert.ok(result.uncheckedFinalDistance<=.00015);
}
});
+76
View File
@@ -0,0 +1,76 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Box3, BoxGeometry, Group, Mesh, MeshStandardMaterial, Vector3 } from '../vendor/three/build/three.module.min.js';
import { createExplodedLayout } from '../js/assembly-explode.js';
const near = (a, b) => assert.ok(a.distanceTo(b) < 1e-9, `${a.toArray()} ≠ ${b.toArray()}`);
function fixture(coincident = false) {
const root = new Group(), instances = new Map();
root.rotation.set(0.4, 0.8, -0.2);
root.scale.set(0.8, 1.2, 0.6);
root.position.set(2, 3, -1);
const parts = [
{ id: 'body', parentId: null, position: [0, 0, 0], installOffset: [0, 1, 0] },
{ id: 'nested', parentId: 'body', position: coincident ? [0, 0, 0] : [2, -1, 0.5], installOffset: [0, 0, 1] },
{ id: 'shell', parentId: null, position: coincident ? [0, 0, 0] : [-1, 3, -2], installOffset: [-1, 0, 0] },
];
for (const part of parts) {
const group = new Group();
group.add(new Mesh(new BoxGeometry(0.4, 0.6, 0.8), new MeshStandardMaterial({color: 0xfeaa33, metalness: 0.7})));
group.position.fromArray(part.position);
if (!coincident) group.rotation.set(0.2, -0.3, 0.1);
instances.set(part.id, group);
(part.parentId ? instances.get(part.parentId) : root).add(group);
}
root.updateMatrixWorld(true);
return { root, instances, config: { parts } };
}
test('nested parts move by their own world displacement under rotated and scaled parents', () => {
const { root, config, instances } = fixture();
const layout = createExplodedLayout(config, instances);
for (const amount of [0, 0.3, 1, 0.65, 0]) {
layout.apply(amount);
root.updateMatrixWorld(true);
const actualBounds = new Box3().setFromObject(root);
for (const record of layout.records) {
const center = new Box3().setFromObject(record.instance.children[0]).getCenter(new Vector3());
near(center, record.center.clone().addScaledVector(record.worldOffset, amount));
}
near(actualBounds.min, layout.boundsAt(amount).min);
near(actualBounds.max, layout.boundsAt(amount).max);
assert.ok(actualBounds.min.y >= layout.originalBounds.min.y - 1e-9);
}
});
test('repeated adjustments restore exact transforms and never change GLB materials or geometry', () => {
const { config, instances } = fixture();
const original = [...instances.values()].map(instance => ({
instance, position: instance.position.toArray(), quaternion: instance.quaternion.toArray(),
scale: instance.scale.toArray(), material: instance.children[0].material, geometry: instance.children[0].geometry,
}));
const json = JSON.stringify(config), layout = createExplodedLayout(config, instances);
for (let i = 0; i < 100; i++) layout.apply((i % 11) / 10);
layout.apply(0);
for (const saved of original) {
assert.deepEqual(saved.instance.position.toArray(), saved.position);
assert.deepEqual(saved.instance.quaternion.toArray(), saved.quaternion);
assert.deepEqual(saved.instance.scale.toArray(), saved.scale);
assert.equal(saved.instance.children[0].material, saved.material);
assert.equal(saved.instance.children[0].geometry, saved.geometry);
}
assert.equal(JSON.stringify(config), json);
});
test('coincident parts separate deterministically and invalid/out-of-range amounts stay bounded', () => {
const { config, instances } = fixture(true);
const layout = createExplodedLayout(config, instances);
assert.notDeepEqual(layout.records[0].worldOffset.toArray(), layout.records[1].worldOffset.toArray());
const again = createExplodedLayout(config, instances);
layout.records.forEach((record, i) => near(record.offset, again.records[i].offset));
for (const value of [-1, NaN, Infinity]) {
layout.apply(value);
config.parts.forEach(part => assert.deepEqual(instances.get(part.id).position.toArray(), part.position));
}
near(layout.boundsAt(100).max, layout.boundsAt(1).max);
});
+134
View File
@@ -0,0 +1,134 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Group, Vector3, Quaternion, Mesh, BoxGeometry } from '../vendor/three/build/three.module.min.js';
import { ScrewTransition, screwDuration, inferToolTipAxis } from '../js/assembly-motion.js';
import { validatePackage } from '../js/experience-packages.js';
const raw = () => ({ schemaVersion: 1, kind: 'assembly', unit: 'meter',
files: ['part.glb', 'tool.glb'].map(path => ({ path, bytes: 100, sha256: 'a'.repeat(64) })),
tools: [{ id: 'hex', file: 'tool.glb', tipPosition: [0.00525, 0, 0.03277] }],
parts: [{ id: 'screw', file: 'part.glb', position: [0.3, 0.2, 0.1],
quaternion: new Quaternion().setFromAxisAngle(new Vector3(1, 1, 0).normalize(), 0.7).toArray(),
installOffset: [0.05, 0.02, 0.03], installation: {
type: 'screw', toolId: 'hex', axis: [0, 0, -1], socketPosition: [0.01, -0.03, -0.0009],
toolQuaternion: [0, 0, Math.sin(Math.PI / 12), Math.cos(Math.PI / 12)],
direction: 'clockwise', turns: 3, travel: 0.0012,
} }], steps: [{ id: 'step', parts: ['screw'] }],
});
const validate = p => validatePackage(p, 'assembly', 'https://example.com/manifest.json');
function fixture(delay = 0) {
const pkg = validate(raw()), part = pkg.parts[0], toolConfig = pkg.tools[0];
const parent = new Group(), instance = new Group(), tool = new Group();
parent.position.set(-2, 3, -4);
parent.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), 1.1);
parent.scale.setScalar(2);
parent.add(instance);
const transition = new ScrewTransition(instance, part, tool, toolConfig, delay);
return { parent, instance, tool, part, toolConfig, transition, m: part.installation };
}
const near = (a, b, eps = 1e-10) => assert.ok(a.distanceTo(b) < eps, `${a.toArray()} ≠ ${b.toArray()}`);
test('new instructions are retained; old packages remain tools-free and slide-only', () => {
const pkg = validate(raw());
assert.equal(pkg.parts[0].installation.toolId, 'hex');
assert.deepEqual(pkg.tools[0].tipPosition, [0.00525, 0, 0.03277]);
const old = raw(); delete old.tools; delete old.parts[0].installation;
assert.deepEqual(validate(old).tools, []);
assert.equal(validate(old).parts[0].installation, undefined);
});
test('invalid tool references, axes, timing and distorted parent scales fail before playback', () => {
for (const mutate of [
p => p.tools.push(p.tools[0]), p => p.tools[0].file = 'missing.glb',
p => p.tools[0].tipPosition = [NaN, 0, 0], p => p.tools[0].tipAxis = [0, 0, 2],
p => p.tools[0].tipAxis = [0, 0, 0], p => p.parts[0].installation.toolId = 'missing',
p => p.parts[0].installation.axis = [0, 0, 0], p => p.parts[0].installation.axis = [0, 0, 2],
p => p.parts[0].installation.turns = 2.5, p => p.parts[0].installation.turns = 0,
p => p.parts[0].installation.direction = 'left', p => p.parts[0].installation.travel = -1,
p => p.parts[0].installation.tightenDuration = Infinity, p => p.parts[0].installation.socketPosition = [],
p => p.parts[0].scale = [1, 2, 1],
p => { p.parts.push({id: 'parent', file: 'part.glb', scale: [1, 2, 1]}); p.parts[0].parentId = 'parent'; },
]) { const p = raw(); mutate(p); assert.throws(() => validate(p)); }
});
test('legacy tool direction is measured at the tip end cap including GLB node transforms', () => {
const template = new Group(), shaft = new Mesh(new BoxGeometry(0.002, 0.002, 0.04));
shaft.position.set(0.00525, 0, 0.05277);
template.add(shaft);
near(new Vector3(...inferToolTipAxis(template, [0.00525, 0, 0.03277])), new Vector3(0, 0, -1));
shaft.geometry.dispose();
});
test('reversed legacy tool faces the screw head, with its handle outside throughout tightening', () => {
for (const axis of [[0, 0, -1], [0, 0, 1], new Vector3(0.03193, -0.02235, -0.99924).normalize().toArray()]) {
const rawPkg = raw();
rawPkg.tools[0].tipAxis = [0, 0, -1];
rawPkg.parts[0].installation.axis = axis;
// The faulty export aligned +Z instead of the actual -Z working end.
rawPkg.parts[0].installation.toolQuaternion = new Quaternion().setFromUnitVectors(new Vector3(0, 0, 1), new Vector3(...axis)).toArray();
const pkg = validate(rawPkg), part = pkg.parts[0], config = pkg.tools[0];
const instance = new Group(), tool = new Group();
const t = new ScrewTransition(instance, part, tool, config), m = part.installation;
for (const progress of [0, 0.25, 0.5, 0.75, 1]) {
t.sample(m.approachDuration + m.engageDuration + progress * m.tightenDuration);
instance.updateMatrixWorld(true);
const tip = tool.localToWorld(new Vector3(...config.tipPosition));
const handle = tool.localToWorld(new Vector3(...config.tipPosition).add(new Vector3(0, 0, 0.04)));
const inward = new Vector3(...axis).applyQuaternion(instance.quaternion);
near(tip, instance.localToWorld(new Vector3(...m.socketPosition)));
assert.ok(handle.sub(tip).dot(inward) < -0.03999, 'handle must remain outside the screw head');
}
}
});
test('tool tip stays exactly in the rotating socket through tightening under parent transforms', () => {
const { parent, instance, tool, part, toolConfig, transition, m } = fixture();
for (let i = 0; i <= 100; i++) {
const progress = i / 100, eased = progress ** 2 * (3 - 2 * progress);
transition.sample(m.approachDuration + m.engageDuration + progress * m.tightenDuration);
parent.updateMatrixWorld(true);
const tip = tool.localToWorld(new Vector3(...toolConfig.tipPosition));
const socket = instance.localToWorld(new Vector3(...m.socketPosition));
near(tip, socket);
// The pivot lies on one straight insertion axis, even for an off-center GLB origin.
const expected = new Vector3(...m.socketPosition).addScaledVector(new Vector3(...m.axis), -m.travel * (1 - eased))
.applyQuaternion(new Quaternion(...part.quaternion)).add(new Vector3(...part.position));
near(socket, parent.localToWorld(expected));
}
});
test('clockwise rotates toward -Y from +X when looking from +Z into a -Z hole', () => {
const p = raw(); p.parts[0].quaternion = [0, 0, 0, 1];
const pkg = validate(p), part = pkg.parts[0], instance = new Group();
const t = new ScrewTransition(instance, part, new Group(), pkg.tools[0]);
t.sample(part.installation.approachDuration + part.installation.engageDuration + 0.1);
assert.ok(new Vector3(1, 0, 0).applyQuaternion(instance.quaternion).y < 0);
part.installation.direction = 'counterclockwise';
t.sample(part.installation.approachDuration + part.installation.engageDuration + 0.1);
assert.ok(new Vector3(1, 0, 0).applyQuaternion(instance.quaternion).y > 0);
});
test('tool approaches and retracts along the configured insertion axis; ends at exact original pose', () => {
const { instance, tool, part, toolConfig, transition, m } = fixture();
const localTip = () => new Vector3(...toolConfig.tipPosition).applyQuaternion(tool.quaternion).add(tool.position);
transition.sample(m.approachDuration);
near(localTip(), new Vector3(...m.socketPosition).addScaledVector(new Vector3(...m.axis), -m.toolClearance));
transition.sample(m.approachDuration + m.engageDuration);
near(localTip(), new Vector3(...m.socketPosition));
transition.sample(screwDuration(m) - m.retractDuration / 2);
near(localTip(), new Vector3(...m.socketPosition).addScaledVector(new Vector3(...m.axis), -m.toolClearance / 2));
transition.sample(100);
assert.deepEqual(instance.position.toArray(), part.position);
assert.deepEqual(instance.quaternion.toArray(), part.quaternion);
assert.equal(tool.visible, false);
assert.equal(instance.visible, true);
});
test('delayed fasteners wait their turn; cancelling removes temporary tool without disposing shared assets', () => {
const { transition, instance, tool } = fixture(3);
assert.equal(instance.visible, false);
transition.sample(2.99); assert.equal(tool.visible, false);
transition.sample(3); assert.equal(instance.visible, true);
transition.dispose(); assert.equal(tool.parent, null);
assert.equal(instance.children.length, 0);
});
+31 -11
View File
@@ -1,6 +1,6 @@
// 打包上线文件到 dist/,并生成 dist.zip(静态网站,直接放到网站根目录)。
// 网站没有编译步骤,这里只挑出上线需要的文件,每个页面放进同名目录。
// 用法:node scripts/build.mjs
// 用法:node scripts/build.mjs [--env=dev]
import { cpSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { execFileSync } from 'node:child_process';
@@ -9,13 +9,21 @@ import { compressRobot } from './meshes.mjs';
const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
const DIST = join(ROOT, 'dist');
const BUILD_ENV = process.argv.find((arg) => arg.startsWith('--env='))?.slice(6) || 'auto';
if (!['auto', 'dev'].includes(BUILD_ENV)) throw new Error(`不支持的打包环境:${BUILD_ENV}`);
const SKIP = /(^|\/)(\.DS_Store|Thumbs\.db)$/;
const copy = (rel) => cpSync(join(ROOT, rel), join(DIST, rel), { recursive: true, filter: (src) => !SKIP.test(src) });
rmSync(DIST, { recursive: true, force: true });
mkdirSync(DIST);
for (const f of ['index.html', 'css', 'js', 'assets', 'data', 'vendor']) copy(f);
for (const f of ['index.html', 'css', 'js', 'assets', 'data', 'vendor', 'play']) copy(f);
const apiFile = join(DIST, 'js/api.js');
const apiSource = readFileSync(apiFile, 'utf8');
if (!apiSource.includes("export const BUILD_ENV = 'auto';")) throw new Error('未找到接口环境标记,停止打包');
writeFileSync(apiFile, apiSource.replace("export const BUILD_ENV = 'auto';", `export const BUILD_ENV = '${BUILD_ENV}';`));
// 浏览器标签、收藏夹和添加到手机桌面使用独立的简化机器人图标。
for (const f of ['favicon.svg', 'favicon.ico', 'apple-touch-icon.png', 'site.webmanifest', 'icon-16.png', 'icon-32.png', 'icon-48.png', 'icon-64.png', 'icon-192.png', 'icon-512.png']) copy(f);
// 静态网站:每个页面放进同名目录的 index.html,地址是 /explore/、/studio/、/cad/、/pcb/、/project/?id=…、/workspace/?code=…
for (const page of ['explore', 'project', 'studio', 'cad', 'pcb', 'workspace']) {
mkdirSync(join(DIST, page));
@@ -37,16 +45,28 @@ for (const r of robots) {
console.log(` ${r.id.padEnd(16)} ${String(files).padStart(3)} 个网格 ${mb(before)} MB → ${mb(after)} MB (${Date.now() - t0} ms)`);
}
writeFileSync(join(DIST, 'DEPLOY.md'), `# 部署
writeFileSync(join(DIST, 'build-info.json'), JSON.stringify({
environment: BUILD_ENV,
builtAt: new Date().toISOString(),
...(BUILD_ENV === 'dev' ? { frontend: 'https://dev-vibemake.robotquan.com', apiBase: 'https://dev-vibemake-api.robotquan.com/api' } : {}),
}, null, 2) + '\n');
静态网站,1Panel 新建「静态网站」,把本目录所有文件放到网站根目录即可,不需要改任何配置。
writeFileSync(join(DIST, 'DEPLOY.md'), `# ${BUILD_ENV === 'dev' ? 'DEV 环境部署' : '部署'}
${BUILD_ENV === 'dev' ? `本包仅用于 dev 环境,接口固定为 https://dev-vibemake-api.robotquan.com/api,始终读取接口数据。
推荐域名:https://dev-vibemake.robotquan.com。
1. 将 dist-dev.zip 上传到 dev 静态网站根目录。
2. 将压缩包内的文件直接解压到网站根目录;根目录应能看到 index.html、js/、css/、play/,不要再套一层 dist 目录。
3. 保留网站原有的 nginx、HTTPS、CORS 等配置,解压时覆盖同名文件。
4. 打开网站并强制刷新,检查社区详情、AI 装配和行走演示;手机端 CAD / PCB 应跳转首页。
` : ''}静态网站,1Panel 新建「静态网站」,把本目录所有文件放到网站根目录即可,不需要运行 npm 或 Node 服务。
- 页面地址:\`/\`、\`/explore/\`、\`/studio/\`、\`/cad/\`、\`/pcb/\`、\`/project/?id=<编号>\`、\`/workspace/\`、\`/workspace/?code=<编号>\`
- 页面嵌入:/cad/ 加载 https://cadworld-studio.robotquan.com/cad,/pcb/ 加载 https://cadworld-studio.robotquan.com/pcb。
- 接口:浏览器按访问的域名直接请求后端(js/api.js 的 API_HOSTS)
- dev-vibemake.robotquan.com → https://dev-vibemake-api.robotquan.com/api
- vibemake.robotquan.com → https://vibemake-api.robotquan.com/api
- **后端需要允许这两个前端域名跨域**(CORS:允许来源 https://dev-vibemake.robotquan.com、https://vibemake.robotquan.com;
- 页面嵌入:/cad/ 加载 https://cadworld-studio.robotquan.com/cad,/pcb/ 加载 https://cadworld-studio.robotquan.com/pcb;仅电脑端开放,手机 / 平板或 820px 及以下窄屏访问时回到首页,且不加载编辑器。
- 接口:${BUILD_ENV === 'dev' ? '固定连接 https://dev-vibemake-api.robotquan.com/api。' : '浏览器按访问的域名直接请求后端(js/api.js 的 API_HOSTS):dev-vibemake.robotquan.com → https://dev-vibemake-api.robotquan.com/api;vibemake.robotquan.com → https://vibemake-api.robotquan.com/api。'}
- **后端需要允许前端域名跨域**(CORS:允许来源 ${BUILD_ENV === 'dev' ? 'https://dev-vibemake.robotquan.com' : 'https://dev-vibemake.robotquan.com、https://vibemake.robotquan.com'};
方法 GET/POST/PUT/PATCH/DELETE/OPTIONS;请求头 Authorization、Content-Type、Accept;暴露 X-Request-Id)。
- 阿里云 OSS(Bucket linkerbot)跨域规则也要加上这两个域名,否则封面上传会失败。
- 第三方库(three.js、urdf-loader、marked、DOMPurify)和字体都在 vendor/ 里,不依赖任何外部 CDN。
@@ -58,7 +78,7 @@ for (const f of ['index.html', 'explore/index.html', 'project/index.html', 'stud
const file = join(DIST, f);
writeFileSync(file, readFileSync(file, 'utf8')
.replace(/href="css\/(style|fonts)\.css"/g, `href="css/$1.css?v=${BUILD_ID}"`)
.replace(/src="js\/shell\.js"/, `src="js/shell.js?v=${BUILD_ID}"`));
.replace(/src="(\/?js\/(?:shell|desktop-tools)\.js)"/g, `src="$1?v=${BUILD_ID}"`));
}
// 检查:不能有 .mjs(静态服务器常把它当成二进制文件返回,模块脚本加载失败)
@@ -67,7 +87,7 @@ const mjs = walk(DIST).filter((f) => f.endsWith('.mjs'));
if (mjs.length) throw new Error(`dist 里有 .mjs 文件,请改成 .js:${mjs.join(', ')}`);
// 打 zip(macOS / Linux 自带 zip)
const zip = join(ROOT, 'dist.zip');
const zip = join(ROOT, BUILD_ENV === 'dev' ? 'dist-dev.zip' : 'dist.zip');
rmSync(zip, { force: true });
try {
execFileSync('zip', ['-qr', zip, '.'], { cwd: DIST });
+26
View File
@@ -0,0 +1,26 @@
// 可重复生成的协议验证积木,不是实际机器人的安装步骤。
import { Document, NodeIO } from '@gltf-transform/core';
import { mkdirSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
const root=fileURLToPath(new URL('../deliverables/experience-packages/multipart-check/',import.meta.url));
mkdirSync(root,{recursive:true});
const positions = new Float32Array([-1,-1,1,1,-1,1,1,1,1,-1,1,1, -1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1]);
const indices=new Uint16Array([0,1,2,0,2,3,4,5,6,4,6,7,4,0,3,4,3,5,1,7,6,1,6,2,3,2,6,3,6,5,4,7,1,4,1,0]);
const files=[];
for(const [name,color] of [['base',[0.1,0.3,0.9,1]],['arm',[0.4,0.8,0.15,1]],['cap',[0.9,0.2,0.1,1]]]){
const doc=new Document(), buffer=doc.createBuffer();
const mat=doc.createMaterial().setBaseColorFactor(color).setMetallicFactor(0.2).setRoughnessFactor(0.4);
const primitive=doc.createPrimitive().setAttribute('POSITION',doc.createAccessor().setType('VEC3').setArray(positions).setBuffer(buffer)).setIndices(doc.createAccessor().setType('SCALAR').setArray(indices).setBuffer(buffer)).setMaterial(mat);
doc.createScene().addChild(doc.createNode().setMesh(doc.createMesh().addPrimitive(primitive)));
const bytes=await new NodeIO().writeBinary(doc);writeFileSync(root+name+'.glb',bytes);
files.push({path:name+'.glb',bytes:bytes.length,sha256:createHash('sha256').update(bytes).digest('hex')});
}
const manifest={schemaVersion:1,kind:'assembly',unit:'meter',title:'多零件测试积木',files,parts:[
{id:'base',file:'base.glb',scale:[0.2,0.04,0.15]},
{id:'left',file:'arm.glb',parentId:'base',position:[-0.6,3,0],scale:[0.2,2,0.3],installOffset:[0,4,0]},
{id:'right',file:'arm.glb',parentId:'base',position:[0.6,3,0],scale:[0.2,2,0.3],installOffset:[0,4,0]},
{id:'cap',file:'cap.glb',position:[0,0.24,0],scale:[0.2,0.04,0.15]}],steps:[
{id:'s1',label:'安装底座',parts:['base']},{id:'s2',label:'安装左侧支撑',parts:['left']},{id:'s3',label:'安装右侧支撑(复用 GLB)',parts:['right']},{id:'s4',label:'安装顶部',parts:['cap']}]};
writeFileSync(root+'manifest.json',JSON.stringify(manifest,null,2));
console.log(root+'manifest.json');
+105
View File
@@ -0,0 +1,105 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { packageUrl, assetPath, assetUrl, validatePackage, visibleAssemblyParts, validateEmbeddedGlb, readLimited } from '../js/experience-packages.js';
import { expectedController, validateController } from '../sandbox/src/game/package-config.js';
import { projectExperiences } from '../js/project-experiences.js';
const url = 'https://cdn.example.com/projects/another/assembly/v2/manifest.json';
const file = { path: 'parts/body.glb', bytes: 80, sha256: 'a'.repeat(64) };
const fixture = () => ({ schemaVersion: 1, kind: 'assembly', unit: 'meter', files: [file], parts: [
{ id: 'base', file: file.path }, { id: 'left', file: file.path, parentId: 'base', position: [1, 0, 0] },
{ id: 'right', file: file.path, parentId: 'base', position: [-1, 0, 0] },
], steps: [{ id: 's1', label: '底座', parts: ['base'] }, { id: 's2', label: '左侧', parts: ['left'] }, { id: 's3', label: '右侧', parts: ['right'] }] });
test('backend bindings are authoritative on every host; missing resources never use another robot', () => {
const project = { code: 'ppsx17fhhtzq', assemblyManifestUrl: null, walkingManifestUrl: null };
for (const host of ['localhost', '127.0.0.1', '10.10.12.218', 'vibemake.robotquan.com']) {
assert.equal(projectExperiences(project, host), project);
assert.equal(projectExperiences(project, host).walkingManifestUrl, null);
}
});
test('two backend fields independently control availability without a project ID lookup', () => {
assert.equal(packageUrl({ code: 'ppsx17fhhtzq' }, 'assembly', url), null);
assert.equal(packageUrl({ code: 'ppsx17fhhtzq' }, 'walking', url), null);
const project = { code: 'unrelated', assemblyManifestUrl: url, walkingManifestUrl: null };
assert.equal(packageUrl(project, 'assembly'), url);
assert.equal(packageUrl(project, 'walking'), null);
assert.equal(packageUrl({ walkingManifestUrl: '/walk/manifest.json' }, 'walking', url), 'https://cdn.example.com/walk/manifest.json');
for (const value of ['', null, 'javascript:alert(1)', 'data:application/json,{}', 'https://user:pass@example.com/m.json']) {
assert.equal(packageUrl({ assemblyManifestUrl: value }, 'assembly', url), null);
}
});
test('relocation preserves nested asset paths and rejects paths outside the package', () => {
assert.equal(assetUrl('parts/左腿.glb', url), 'https://cdn.example.com/projects/another/assembly/v2/parts/%E5%B7%A6%E8%85%BF.glb');
for (const path of ['../body.glb', '/body.glb', 'https://evil.test/a.glb', 'a/../../b.glb', 'a\\b.glb', 'a/%2e%2e/b.glb', 'a.glb?x', 'a//b.glb']) assert.throws(() => assetPath(path));
});
test('assembly steps add parts cumulatively and preserve instances of the same file', () => {
const pkg = validatePackage(fixture(), 'assembly', url);
assert.equal(pkg.files.size, 1);
assert.equal(pkg.parts.length, 3);
assert.deepEqual([...visibleAssemblyParts(pkg, 0)], ['base']);
assert.deepEqual([...visibleAssemblyParts(pkg, 1)], ['base', 'left']);
assert.deepEqual([...visibleAssemblyParts(pkg, null)], ['base', 'left', 'right']);
assert.deepEqual(pkg.parts[2].position, [-1, 0, 0]);
assert.throws(() => visibleAssemblyParts(pkg, 3));
});
test('GLB assets above 50 MB and packages above 200 MB retain their integrity metadata', () => {
const raw = fixture();
raw.files[0] = { ...file, bytes: 310 * 1024 * 1024 };
const pkg = validatePackage(raw, 'assembly', url);
assert.equal(pkg.files.get(file.path).bytes, 310 * 1024 * 1024);
assert.equal(pkg.files.get(file.path).sha256, file.sha256);
});
test('invalid hierarchy, installation order, transforms and incomplete steps are rejected', () => {
const changes = [
p => { p.parts[0].parentId = 'left'; },
p => { p.parts[1].parentId = 'unknown'; },
p => { p.parts[1].id = 'base'; },
p => { p.parts[1].file = 'missing.glb'; },
p => { p.parts[1].quaternion = [0, 0, 0, 0]; },
p => { p.parts[1].position = [Infinity, 0, 0]; },
p => { p.parts[1].scale = [0, 1, 1]; },
p => { p.steps.reverse(); },
p => { p.steps.pop(); },
p => { p.steps[1].parts.push('base'); },
p => { p.files.push({ ...file }); },
p => { p.schemaVersion = 2; },
];
for (const change of changes) { const p = fixture(); change(p); assert.throws(() => validatePackage(p, 'assembly', url)); }
});
test('GLB rejects external images and malformed headers', () => {
const json = JSON.stringify({ asset: { version: '2.0' }, images: [{ uri: 'https://elsewhere.test/texture.png' }] });
const padding = (4 - json.length % 4) % 4;
const buffer = Buffer.alloc(20 + json.length + padding, 32);
buffer.writeUInt32LE(0x46546c67, 0); buffer.writeUInt32LE(2, 4); buffer.writeUInt32LE(buffer.length, 8);
buffer.writeUInt32LE(json.length + padding, 12); buffer.writeUInt32LE(0x4e4f534a, 16); buffer.write(json, 20);
assert.throws(() => validateEmbeddedGlb(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.length)), /嵌入/);
assert.throws(() => validateEmbeddedGlb(new ArrayBuffer(4)));
});
test('walking controller rejects a different joint order or timing even when dimensions match', () => {
assert.doesNotThrow(() => validateController(expectedController()));
const swapped = expectedController();
[swapped.jointNames[0], swapped.jointNames[1]] = [swapped.jointNames[1], swapped.jointNames[0]];
assert.throws(() => validateController(swapped), /jointNames/);
assert.throws(() => validateController({ ...expectedController(), physicsTimestep: 0.01 }), /physicsTimestep/);
assert.throws(() => validateController({ ...expectedController(), actionSize: 19 }), /actionSize/);
});
test('JSON and asset readers reject oversized responses with or without Content-Length', async () => {
await assert.rejects(readLimited(new Response('12345'), 4), /超过/);
await assert.rejects(readLimited(new Response('12', { headers: { 'Content-Length': '100' } }), 4), /超过/);
assert.equal(new TextDecoder().decode(await readLimited(new Response('1234'), 4)), '1234');
});
test('shipped source GLB remains a self-contained valid assembly asset', () => {
const bytes = readFileSync(new URL('../assets/models/microban-assembly.glb', import.meta.url));
assert.doesNotThrow(() => validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length)));
});
+48
View File
@@ -0,0 +1,48 @@
// User preference: retain yesterday's confirmed leg directions, without replanning.
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import {Vector3,Quaternion} from 'three';
import {validatePackage} from '../js/experience-packages.js';
const root=new URL('../deliverables/experience-packages/microduck-current/',import.meta.url).pathname;
const old=JSON.parse(fs.readFileSync('/Users/jerry/Downloads/小鸭子-双腿及躯干-当前上传/小鸭子-双腿及躯干-149步装配.json'));
const out=JSON.parse(fs.readFileSync(path.join(root,'manifest.json')));
const oldParts=new Map(old.parts.map(p=>[p.id,p])),parts=new Map(out.parts.map(p=>[p.id,p]));
const steps=new Map(out.steps.map(s=>[s.id,s])),q=new Quaternion(...old.displayQuaternion),retained=[];
for(const s of old.steps){
const code=s.id.split('-').slice(-2).join('-');
// Previous body directions are also retained wherever the same numbered step exists.
const target=steps.get(`step-${code}`);if(!target)continue;
const original=oldParts.get(s.parts[0]),offset=new Vector3(...original.installOffset).applyQuaternion(q);
for(const id of target.parts){const p=parts.get(id);
if(/螺钉/.test(p.file)){
// Same axial-entry rule; new exported screw geometry can have baked local rotations.
const direction=new Vector3(...p.installOffset).normalize();p.installOffset=direction.multiplyScalar(offset.length()).toArray();
}else p.installOffset=offset.toArray().map(n=>Math.abs(n)<1e-11?0:n);
}
retained.push(code);
}
assert.equal(retained.filter(c=>/^[12]-/.test(c)).length,104);
out.title='小鸭子 · 完整编号装配(239步,沿用双腿规则)';
validatePackage(out,'assembly','http://localhost:8090/manifest.json');
fs.writeFileSync(path.join(root,'manifest.json'),JSON.stringify(out,null,2)+'\n');
const notes=JSON.parse(fs.readFileSync(path.join(root,'manifest.notes.json')));
out.steps.forEach((s,i)=>{if(retained.includes(s.id.replace('step-','')))notes.steps[i].reason='沿用已确认的编号装配规则;位置来自本次整机,螺丝沿自身轴线进入。';});
fs.writeFileSync(path.join(root,'manifest.notes.json'),JSON.stringify(notes,null,2)+'\n');
const review=JSON.parse(fs.readFileSync(path.join(root,'axis-review.json')));
for(const r of review.records)if(retained.includes(r.code)){
r.experimentalCandidate=r.selected;r.experimentalCheck=r.check;
r.finalDirectionSource='user-requested-previous-numbered-rules';r.check={status:'retained-previous-rule'};
r.offsets=steps.get(`step-${r.code}`).parts.map(id=>parts.get(id).installOffset);
r.selected={name:'沿用昨日规则',vector:new Vector3(...r.offsets[0]).normalize().toArray(),travel:Math.hypot(...r.offsets[0])};
}
fs.writeFileSync(path.join(root,'axis-review.json'),JSON.stringify(review,null,2)+'\n');
const destination='/Users/jerry/Downloads/小鸭子-最新完整装配-20261030';
fs.mkdirSync(path.join(destination,'零件模型'),{recursive:true});
for(const f of out.files)fs.copyFileSync(path.join(root,f.path),path.join(destination,'零件模型',f.path));
fs.copyFileSync(path.join(root,'manifest.json'),path.join(destination,'小鸭子-完整装配步骤.json'));
const mapping=JSON.parse(fs.readFileSync(path.join(root,'mapping.json')));
const text=`小鸭子最新完整装配 · 239 步\n\n上传方式\n1. 后台“零件模型”:选择本目录中的“零件模型”文件夹(242 个整机零件 + 1 个扳手)。\n2. 后台“拼装步骤”:上传“小鸭子-完整装配步骤.json”。\n3. 使用当前本地前端打开 AI 装配。新的 GLB 使用 Draco 压缩,旧版前端需更新装配播放器后再部署。\n\n这次整机的零件划分、文件名与旧包不同,请把配套零件一起上传,不要混用旧文件夹。\n\n顺序与方向\n左腿 52 步 → 右腿 52 步 → 躯干 47 步 → 颈部 24 步 → 头部 64 步。\n两条腿沿用之前确认的安装方向规则;已有躯干步骤也保留旧规则。\n螺丝沿本次实际几何体的轴线进入,保留扳手拧入动画。\n新 GLB 为 Y 向上,installOffset 表示“起点相对最终位置的偏移”,不是运动速度方向。\n所有最终位置来自本次整机;压缩几何、材质参数、贴图字节保持原样。\n这是一份可上传的装配展示 JSON,不代表机械工艺或全程无碰撞认证。保留顺序和原始终点时,部分源模型配合面接触不能仅靠改变轴向消除。\n\n与编号清单的差异(保留新整机实际模型,没有改螺丝)\n${mapping.mismatches.map(x=>`${x.code}:清单 ${x.label};整机 ${x.name}`).join('\n')}\n\n整机附带但顺序未单列的对象\n${mapping.extras.map(x=>`${x.code}:${x.reason}`).join('\n')}\n原先跳过的 3-36、3-37 在新整机找到对应 M2x4.070、M2x4.071,本次已加入。\n`;
fs.writeFileSync(path.join(destination,'上传说明.txt'),text);
fs.writeFileSync(path.join(root,'retained-rules.json'),JSON.stringify({source:'previous 149-step package',retained,legSteps:104},null,2)+'\n');
console.log(JSON.stringify({destination,steps:out.steps.length,parts:out.parts.length,files:out.files.length,retained:retained.length},null,2));
+66
View File
@@ -0,0 +1,66 @@
import {readFileSync,writeFileSync,mkdirSync} from 'node:fs';
import {join} from 'node:path';
import {createHash} from 'node:crypto';
import assert from 'node:assert/strict';
import {validatePackage,validateEmbeddedGlb} from '../js/experience-packages.js';
const folder=new URL('../deliverables/experience-packages/microduck-numbered-body/',import.meta.url);
const bytes=readFileSync(new URL('manifest.json',folder));
const raw=JSON.parse(bytes),source=JSON.parse(readFileSync(new URL('input.json',folder)));
const left=JSON.parse(readFileSync('/Users/jerry/Downloads/小鸭子-52步装配-当前上传/小鸭子-左腿-52步装配.json'));
const review=JSON.parse(readFileSync(new URL('axis-review.json',folder)));
const config=validatePackage(raw,'assembly','http://localhost:8090/manifest.json');
assert.equal(raw.steps.length,149);assert.equal(raw.parts.length,201);assert.ok(bytes.length<2*1024*1024);
assert.deepEqual(raw.steps.slice(0,52),left.steps);assert.deepEqual(raw.parts.slice(0,72),left.parts);
assert.deepEqual(raw.steps.slice(52,104).map(s=>s.id),Array.from({length:52},(_,i)=>`right-2-${i+1}`));
assert.deepEqual(raw.steps.slice(104).map(s=>s.id),Array.from({length:47},(_,i)=>i+1).filter(n=>![36,37].includes(n)).map(n=>`trunk-3-${n}`));
assert.deepEqual(raw.files,source.files);assert.deepEqual(raw.tools,source.tools);
assert.equal(review.steps.length,149);assert.ok(review.finiteVisualChanges);
for(let i=0;i<raw.parts.length;i++){
const {installOffset:a,...p}=raw.parts[i],{installOffset:b,...q}=source.parts[i];assert.deepEqual(p,q);
}
const poses=new Set();
for(const p of config.parts){
const key=JSON.stringify([p.file,p.position,p.quaternion]);assert.ok(!poses.has(key),`Duplicate instance at the same pose: ${p.file}`);poses.add(key);
}
for(const f of raw.files){
const b=readFileSync(join('/Users/jerry/Downloads/小鸭子-扳手装配/零件模型',f.path));
assert.equal(b.length,f.bytes);assert.equal(createHash('sha256').update(b).digest('hex'),f.sha256);
validateEmbeddedGlb(b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength));
assert.equal(createHash('sha256').update(readFileSync(new URL(f.path,folder))).digest('hex'),f.sha256);
}
const output='/Users/jerry/Downloads/小鸭子-双腿及躯干-当前上传';
const name='小鸭子-双腿及躯干-149步装配.json';
mkdirSync(output,{recursive:true});writeFileSync(join(output,name),bytes);
writeFileSync(join(output,'上传说明.txt'),`只上传这个文件:${name}
后台小鸭子项目 → 拼装步骤 → 选择上面的 JSON,替换旧步骤。
沿用后台已经上传的完整小鸭子零件目录及内六角扳手,不用重新上传 GLB 或 STEP。
上传后刷新社区页面,关闭并重新打开 AI 装配。
顺序:左腿 1-1~1-52 → 右腿 2-1~2-52 → 躯干 3-1~3-47。
按本次确认,跳过 3-36、3-37;后面的编号不变。
共 149 步、201 个零件实例。舵机及轴承组件同一步同步装入。
本次范围只有左右腿和躯干,不包含尚未提供编号的头部/颈部装配。
GLB 文件的材质、颜色、几何均未修改。
左腿保留上一版修订结果。右腿按新编号总装的位置及朝向匹配,其中两组轴承和七颗螺丝使用新总装位置。
躯干按原整机位置匹配。同规格螺丝按配套组件孔位分组;因单件 STEP 没有实例坐标,同一组内同规格螺丝不能从文件名恢复唯一孔位编号。
重复使用同规格螺丝的 GLB 时使用独立实例,不会移动已装好的另一颗螺丝。
新增 97 步已跑离线 BVH 检查,考虑前面已经安装的零件。
比较可用轴向,并按局部空间调整进入距离;螺丝保持自身轴线和已有扳手动画。
右腿髋部支架缩短为从两腿间的空隙装入;IMU 从贴近安装位的空间装入。
这些计算已写入 JSON,手机和电脑播放时不需要运行这套碰撞计算。
实际限制:一些步骤仍有途中干涉或最终配合处交叠,特别是当前先装双腿再装躯干的顺序下,部分轴承和连接支架不能只换一条直线轴向就消除干涉。
本文件是可播放的方向优化版本,不是 149 步全程无碰撞认证。未改变安装顺序或最终结构来隐藏这些问题。
后续若要彻底消除这些情况,需要调整子装配顺序或配置多段进入路径。
本地预览:http://localhost:8090/examples/duck-numbered-assembly.html?step=149
`);
const validation={output:join(output,name),steps:raw.steps.length,parts:raw.parts.length,filesVerified:raw.files.length,
skipped:['3-36','3-37'],leftUnchanged:true,posesAndMaterialsUnchangedByOptimization:true,
sha256:createHash('sha256').update(bytes).digest('hex'),jsonBytes:bytes.length,collisionCertified:false};
writeFileSync(new URL('validation.json',folder),JSON.stringify(validation,null,2)+'\n');
console.log(JSON.stringify(validation,null,2));
+105
View File
@@ -0,0 +1,105 @@
// Offline only: no collision code is loaded by the community player.
import { Box3, Matrix4, Vector3 } from 'three';
import { MeshBVH, SAH } from 'three-mesh-bvh';
export const VIEW_AXES = [
{ name: '+Y', label: '从上往下', vector: [0, 1, 0] },
{ name: '+Z', label: '从前往后', vector: [0, 0, 1] },
{ name: '-Z', label: '从后往前', vector: [0, 0, -1] },
{ name: '+X', label: '从右往左', vector: [1, 0, 0] },
{ name: '-X', label: '从左往右', vector: [-1, 0, 0] },
{ name: '-Y', label: '从下往上', vector: [0, -1, 0] },
];
export function collider(id, geometry) {
// Caller provides a collision-only copy in display/world meters.
geometry.clearGroups();
geometry.computeBoundingBox();
geometry.boundsTree = new MeshBVH(geometry, { strategy: SAH, targetLeafSize: 8 });
return { id, geometry, box: geometry.boundingBox.clone(), bvh: geometry.boundsTree };
}
function union(items) {
const b = new Box3();
for (const item of items) b.union(item.box);
return b;
}
function boxDistance(a, b) {
return Math.hypot(...['x', 'y', 'z'].map(k => Math.max(0, a.min[k] - b.max[k], b.min[k] - a.max[k])));
}
// Minimum surface separation. An AABB is only a broad phase, never proof that
// shapes intersect: hollow shells and bearing holes must remain navigable.
function separation(moving, obstacles, offset) {
const matrix = new Matrix4().makeTranslation(...offset.toArray());
let distance = Infinity, blocker = null;
const pairs = [];
for (const a of moving) for (const b of obstacles) {
const lower = boxDistance(a.box.clone().translate(offset), b.box);
pairs.push({ a, b, lower });
}
pairs.sort((a, b) => a.lower - b.lower);
for (const { a, b, lower } of pairs) {
if (lower >= distance) continue;
const hit = b.bvh.closestPointToGeometry(a.geometry, matrix, {}, null, 0, distance);
if (hit && hit.distance < distance) { distance = hit.distance; blocker = b.id; }
if (distance === 0) break;
}
return { distance, blocker };
}
// Conservative advancement for fixed-rotation, straight translation. Surface
// separation cannot shrink faster than translation distance. Never jump by a
// fixed sampling interval: that could tunnel through a thin sheet.
// Starting outside the complete obstacle AABB also prevents an initially
// contained closed mesh from being mistaken for a clear route.
export function checkAxis(moving, obstacles, vector, {
minimumTravel = 0.035, startMargin = 0.004, seatingTolerance = 0.00015,
numericTolerance = 0.000001, maxIterations = 600, maxMilliseconds = 15000,
} = {}) {
if (!obstacles.length) return { status: 'foundation', travel: 0, checks: 0 };
const axis = new Vector3(...vector).normalize();
if (!axis.lengthSq() || !axis.toArray().every(Number.isFinite)) throw new Error('Invalid insertion axis');
const a = union(moving), b = union(obstacles);
const project = (box, sign) => ['x','y','z'].reduce((s,k) => s + axis[k] * box[axis[k] * sign >= 0 ? 'max' : 'min'][k], 0);
const travel = Math.max(minimumTravel, startMargin + project(b, 1) - project(a, -1));
let remaining = travel;
const started = performance.now();
for (let checks = 1; checks <= maxIterations; checks++) {
if (performance.now() - started > maxMilliseconds) return { status: 'needs-review', reason: 'time-budget', travel, remaining, checks };
const { distance, blocker } = separation(moving, obstacles, axis.clone().multiplyScalar(remaining));
if (!Number.isFinite(distance)) return { status: 'needs-review', reason: 'invalid-distance', travel, remaining, checks };
if (distance <= numericTolerance * 1.05) return { status: 'blocked-or-touching', blocker, travel, remaining, checks };
if (remaining <= seatingTolerance) return { status: 'clear-to-seating', travel, checks, uncheckedFinalDistance: remaining };
// Leave numerical slack; reaching the seating point uses the same bound.
const advance = Math.min(0.8 * (distance - numericTolerance), remaining - seatingTolerance);
if (advance <= Number.EPSILON) return { status: 'needs-review', reason: 'stalled', travel, remaining, checks };
// Assign the exact endpoint when the advance reaches seating. Subtracting
// nearly equal floats can otherwise leave a sub-ulp gap and report stalled.
remaining = advance === remaining - seatingTolerance ? seatingTolerance : remaining - advance;
}
return { status: 'needs-review', reason: 'iteration-budget', travel, remaining, checks: maxIterations };
}
export function chooseAxis(moving, obstacles, options = {}) {
const candidates = (options.axes ?? VIEW_AXES).map(axis => ({ ...axis, ...checkAxis(moving, obstacles, axis.vector, options) }));
const selected = candidates.find(c => c.status === 'clear-to-seating' || c.status === 'foundation') ?? null;
return { selected, candidates };
}
// Check an actual, finite entry offset. Obstacles outside every swept AABB cannot
// touch that path. Internally still start outside the relevant obstacle bounds:
// this intentionally rejects/flags a potentially contained start, rather than
// interpreting a lack of surface crossings inside a closed solid as clearance.
export function checkFiniteAxis(moving, obstacles, vector, travel, options = {}) {
if (!Number.isFinite(travel) || travel <= 0) throw new Error('Invalid entry travel');
const axis = new Vector3(...vector).normalize();
if (!axis.lengthSq() || !axis.toArray().every(Number.isFinite)) throw new Error('Invalid insertion axis');
const offset = axis.clone().multiplyScalar(travel);
const sweeps = moving.map(m => m.box.clone().union(m.box.clone().translate(offset)).expandByScalar(0.000002));
const relevant = obstacles.filter(b => sweeps.some(s => s.intersectsBox(b.box)));
const checked = checkAxis(moving, relevant, axis.toArray(), { ...options, minimumTravel: travel });
// Consumers must use travel, not checkedFromTravel, for the finite animation.
return { ...checked, checkedFromTravel: checked.travel, travel, relevantObstacles: relevant.length };
}
+60
View File
@@ -0,0 +1,60 @@
// Read-only geometry for offline assembly checks. Render assets are never rewritten.
import { readFileSync } from 'node:fs';
import { 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 { validateEmbeddedGlb } from '../../js/experience-packages.js';
import { collider } from './assembly-axis-planner.mjs';
export function assemblyColliders(config, assets) {
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
const display = new Matrix4().makeRotationFromQuaternion(new Quaternion(...config.displayQuaternion));
const documents = new Map(), items = new Map();
return async function get(part) {
assert.equal(part.parentId, null, 'Only flat rigid assemblies are supported');
if (items.has(part.id)) return items.get(part.id);
if (!documents.has(part.file)) {
const bytes = readFileSync(join(assets, part.file));
const file = config.files.get(part.file);
assert.equal(bytes.length, file.bytes);
assert.equal(createHash('sha256').update(bytes).digest('hex'), file.sha256);
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
documents.set(part.file, await io.readBinary(bytes));
}
const doc = documents.get(part.file);
const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
assert.ok(scene, `Missing scene: ${part.file}`);
const placement = 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, 'Rigid geometry required');
const matrix = placement.clone().multiply(new Matrix4().fromArray(node.getWorldMatrix()));
for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
assert.equal(primitive.getMode(), 4);
assert.equal(primitive.listTargets().length, 0);
const source = primitive.getAttribute('POSITION');
assert.ok(source && !source.getNormalized());
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);
const positions = new Float32Array(count * 3);
let offset = 0;
for (const chunk of chunks) { positions.set(chunk, offset); offset += chunk.length; }
const geometry = new BufferGeometry().setAttribute('position', new BufferAttribute(positions, 3));
geometry.setIndex(new BufferAttribute(new Uint32Array(indices), 1));
const item = collider(part.id, geometry);
items.set(part.id, item);
return item;
};
}
+32
View File
@@ -0,0 +1,32 @@
// Read assembly names/rigid transforms only; never convert or alter render meshes.
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import { Matrix4, Vector3 } from 'three';
export function stepPlacements(path) {
const bytes = readFileSync(path);
const entities = new Map([...bytes.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, entity] of entities) if (/^PRODUCT_DEFINITION\s*\(/.test(entity)) {
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 occurrences = [];
for (const [id, entity] of entities) if (/^CONTEXT_DEPENDENT_SHAPE_REPRESENTATION\s*\(/.test(entity)) {
const [relation, definition] = refs(id), occurrence = refs(definition)[0];
const [parent, child] = refs(occurrence), [a, b] = refs(refs(relation).at(-1));
const matrix = axis(a).multiply(axis(b).invert());
for (const n of [12, 13, 14]) matrix.elements[n] /= 1000;
occurrences.push({ parent, child, name: names.get(child), matrix, occurrence });
}
const roots = [...names.keys()].filter(id => !occurrences.some(o => o.child === id));
assert.equal(roots.length, 1);
const top = occurrences.filter(o => o.parent === roots[0]);
return { rootName: names.get(roots[0]), top, occurrences, bytes };
}
+43
View File
@@ -0,0 +1,43 @@
import https from 'node:https';
import { modelAssetTarget } from '../js/model-assets.js';
const REQUEST_HEADERS = ['accept-encoding', 'range', 'if-range', 'if-none-match', 'if-modified-since'];
const RESPONSE_HEADERS = ['content-type', 'content-length', 'content-encoding', 'content-range', 'accept-ranges', 'cache-control', 'etag', 'last-modified', 'vary'];
export function proxyModelAsset(req, res) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.writeHead(405, { Allow: 'GET, HEAD' }).end();
return;
}
const target = modelAssetTarget(req.url);
if (!target) {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Unknown model asset');
return;
}
// 只转发读取 / 缓存相关请求头,绝不把网站的 Cookie、Authorization 带给 OSS。
const headers = Object.fromEntries(REQUEST_HEADERS.filter((key) => req.headers[key]).map((key) => [key, req.headers[key]]));
const upstream = https.request(target, { method: req.method, headers }, (up) => {
// 不跟随或透传重定向,保证资源始终来自允许的 bucket。
if (up.statusCode >= 300 && up.statusCode < 400 && up.statusCode !== 304) {
up.resume();
res.writeHead(502, { 'Cache-Control': 'no-store' }).end('Unexpected asset redirect');
return;
}
const out = Object.fromEntries(RESPONSE_HEADERS.filter((key) => up.headers[key] !== undefined).map((key) => [key, up.headers[key]]));
out['X-Content-Type-Options'] = 'nosniff';
out['Content-Security-Policy'] = "default-src 'none'; sandbox";
out['Cache-Control'] = up.statusCode < 400 ? (out['cache-control'] || 'public, max-age=86400') : 'no-store';
delete out['cache-control'];
res.writeHead(up.statusCode, out);
up.on('error', () => res.destroy());
up.pipe(res);
res.on('close', () => { if (!res.writableFinished) up.destroy(); });
});
upstream.setTimeout(60_000, () => upstream.destroy(new Error('Model asset timeout')));
upstream.on('error', () => {
if (res.headersSent) { res.destroy(); return; }
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }).end('Model asset unavailable');
});
res.on('close', () => { if (!res.writableFinished) upstream.destroy(); });
upstream.end();
}
+82
View File
@@ -0,0 +1,82 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { MODEL_ASSET_ROUTE, modelAssetTarget, modelAssetUrl, modelUrlResolver } from '../js/model-assets.js';
import { meshUrlCandidates } from '../js/urdf-paths.js';
const origin = 'https://linkerbot.oss-cn-beijing.aliyuncs.com';
const directory = '/vibemake_dev/urdf/ppsx17fhhtzq/version';
const base = `${origin}${directory}`;
test('LAN and localhost load URDF, meshes and textures from the same origin', () => {
for (const host of ['localhost', '127.0.0.1', '[::1]', '10.10.12.144', '192.168.1.6', '172.16.0.3', 'computer.local']) {
for (const asset of ['robot.urdf', 'meshes/leg.stl', 'meshes/arm.glb', 'textures/body.png', 'meshes/model.bin']) {
const remote = `${base}/${asset}`;
const local = modelAssetUrl(remote, host);
assert.equal(local, `${MODEL_ASSET_ROUTE}${directory}/${asset}`);
assert.equal(modelAssetTarget(local).href, remote);
}
}
});
test('deployed sites and unrelated resources keep their original addresses', () => {
for (const host of ['vibemake.robotquan.com', 'dev-vibemake.robotquan.com', '172.32.0.1', '10.10.12.144.example.com']) {
assert.equal(modelAssetUrl(`${base}/robot.urdf`, host), `${base}/robot.urdf`);
}
for (const url of ['/robots/local/robot.urdf', '/assets/models/microban-assembly.glb', 'blob:local', 'data:image/png;base64,test', 'https://example.com/robot.urdf']) {
assert.equal(modelAssetUrl(url, '10.10.12.144'), url);
}
});
test('file URIs emitted by URDFLoader resolve to the package root before proxying', () => {
const resolve = modelUrlResolver(base, '10.10.12.144');
for (const value of ['file:///meshes/leg.stl', `${base}/nested/file:///meshes/leg.stl`]) {
assert.equal(resolve(value), `${MODEL_ASSET_ROUTE}${directory}/meshes/leg.stl`);
}
assert.equal(resolve(`${base}/nested/../meshes/leg.stl`), `${MODEL_ASSET_ROUTE}${directory}/meshes/leg.stl`);
assert.equal(modelUrlResolver(base, 'vibemake.robotquan.com')('file:///meshes/leg.stl'), `${base}/meshes/leg.stl`);
});
test('mesh fallback candidates retain the LAN proxy after merging URDF path handling', () => {
const path = `${base}/robots/legacy_description/meshes/arm.stl`;
const candidates = meshUrlCandidates(base, path);
assert.equal(candidates[0], `${base}/meshes/arm.stl`);
for (const host of ['localhost', '192.168.1.6']) {
const resolve = modelUrlResolver(base, host);
assert.deepEqual(candidates.map((url) => modelAssetTarget(resolve(url)).href), candidates);
}
assert.equal(modelUrlResolver(base, 'dev-vibemake.robotquan.com')(candidates[0]), candidates[0]);
});
test('asset names and signed query strings survive a proxy round trip', () => {
const remote = `${base}/meshes/${encodeURIComponent('左腿 零件')}.stl?Expires=123&Signature=a%2Bb%3D`;
assert.equal(modelAssetTarget(modelAssetUrl(remote, 'localhost')).href, remote);
});
test('LAN preview proxies package data but never executable uploads', () => {
const root = `${origin}/vibemake_dev/experiences/project/version`;
for (const name of ['manifest.json', 'controller.json', 'models/part.glb', 'robot/model.xml', 'policies/walk.onnx', 'assets/beep.wav']) {
assert.equal(modelAssetTarget(modelAssetUrl(`${root}/${name}`, '192.168.1.6')).href, `${root}/${name}`);
}
for (const name of ['index.html', 'script.js', 'engine.wasm', 'training.py']) {
assert.equal(modelAssetUrl(`${root}/${name}`, 'localhost'), `${root}/${name}`);
}
});
test('proxy rejects other origins, credentials, active content and escaping paths', () => {
for (const url of [
`http://linkerbot.oss-cn-beijing.aliyuncs.com${directory}/robot.urdf`,
`https://linkerbot.oss-cn-beijing.aliyuncs.com.example.com${directory}/robot.urdf`,
`https://user:password@linkerbot.oss-cn-beijing.aliyuncs.com${directory}/robot.urdf`,
`${origin}/private/robot.urdf`, `${base}/index.html`, `${base}/script.js`,
]) assert.equal(modelAssetUrl(url, 'localhost'), url);
for (const path of [
`${MODEL_ASSET_ROUTE}/../private/robot.urdf`,
`${MODEL_ASSET_ROUTE}${directory}/%2e%2e%2f%2e%2e%2fsecret.stl`,
`${MODEL_ASSET_ROUTE}${directory}/%252e%252e/secret.stl`,
`${MODEL_ASSET_ROUTE}${directory}/bad%00.stl`,
`${MODEL_ASSET_ROUTE}${directory}/bad%5cfile.stl`,
`${MODEL_ASSET_ROUTE}//example.com/robot.urdf`,
`${MODEL_ASSET_ROUTE}/private/robot.urdf`,
'/api/robot.urdf',
]) assert.equal(modelAssetTarget(path), null, path);
});
+120
View File
@@ -0,0 +1,120 @@
// Offline BVH review of the combined numbered sequence. No runtime collision cost.
import { readFileSync, writeFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import { Vector3, Quaternion } from 'three';
import { validatePackage } from '../js/experience-packages.js';
import { assemblyColliders } from './lib/assembly-colliders.mjs';
import { checkFiniteAxis, VIEW_AXES } from './lib/assembly-axis-planner.mjs';
const folder = new URL('../deliverables/experience-packages/microduck-numbered-body/', import.meta.url);
const raw = JSON.parse(readFileSync(new URL('input.json', folder)));
const result = structuredClone(raw), notes = JSON.parse(readFileSync(new URL('input.notes.json', folder)));
const config = validatePackage(raw, 'assembly', 'http://localhost:8090/manifest.json');
const get = assemblyColliders(config, '/Users/jerry/Downloads/小鸭子-扳手装配/零件模型');
const byId = new Map(result.parts.map(p => [p.id,p]));
const normalized = new Map(config.parts.map(p => [p.id,p]));
const display = new Quaternion(...config.displayQuaternion), inverse = display.clone().invert();
const installed = [], records = [], started = Date.now();
const vec = a => new Vector3(...a);
const clean = a => a.map(v => Math.abs(v) < 1e-12 ? 0 : v);
function checkFiniteApproach(moving, obstacles, vector, travel, maxMilliseconds=4000) {
return checkFiniteAxis(moving,obstacles,vector,travel,{maxMilliseconds});
}
function candidates(step, parts) {
const out = [];
const add = (name, vector) => {
const v = vector.clone().normalize();
if (!out.some(a => vec(a.vector).distanceTo(v) < 1e-5)) out.push({ name, vector: clean(v.toArray()) });
};
const preferred = vec(parts[0].installOffset).applyQuaternion(display).normalize();
const localQ = display.clone().multiply(new Quaternion(...parts[0].quaternion));
const local = axis => vec(axis).applyQuaternion(localQ);
const right = /^right-2-/.test(step.id), n = Number(step.id.split('-').at(-1));
add('preferred', preferred);
// Explicit fit constraints: do not install bearings sideways or screws across their holes.
if (right && [1,2].includes(n)) return out;
if (right && [5,6,17,34,35,42].includes(n)) {
// Align to the latest right assembly rather than inheriting an old tilted bearing axis.
out.length = 0;
const axis = local([1,0,0]); if (axis.dot(preferred) < 0) axis.negate();
add('local-fit-normal', axis); add('opposite-fit-normal', axis.clone().negate());
return out;
}
if (right && [3,18,31,43].includes(n)) {
out.length = 0;
const axis = local([0,0,1]); if (axis.dot(preferred) < 0) axis.negate();
add('local-fit-normal', axis); add('opposite-fit-normal', axis.clone().negate());
return out;
}
if (!right && [8,9,10,22,43,44].includes(n)) {
add('opposite-fit-normal', preferred.clone().negate()); return out;
}
if (right && n === 7) {
// Above the foot, with a small outward lean; never enter through the sole.
for (const z of [0,.08,.15,.25,.4]) add(`above-outward-${z}`,vec([0,1,z]));
return out;
}
for (const axis of VIEW_AXES) {
add(`display-${axis.name}`,vec(axis.vector)); add(`local-${axis.name}`,local(axis.vector));
}
return out;
}
for (const [i,step] of result.steps.entries()) {
const parts = step.parts.map(id => byId.get(id));
const moving = await Promise.all(step.parts.map(id => get(normalized.get(id))));
const fastener = parts.every(p => /螺钉/.test(p.file));
const record = { index:i+1, id:step.id, label:step.label, files:parts.map(p=>p.file) };
if (i < 52) {
record.status = 'preserved-reviewed-left';
} else if (fastener) {
const axis = vec(parts[0].installOffset).applyQuaternion(display).normalize().toArray();
record.selected = { name:'fixed-screw-axis', vector:axis,
...checkFiniteApproach(moving,installed,axis,.020,2500) };
record.status = 'fixed-fastener-axis';
record.note = 'Approach checked only; screw rotation, tool sweep and final seating are not certified.';
} else {
record.candidates = candidates(step,parts).map(c => ({ ...c,
...checkFiniteApproach(moving,installed,c.vector,Math.hypot(...parts[0].installOffset)) }));
for(const c of record.candidates) if(c.status==='needs-review')
Object.assign(c,checkFiniteApproach(moving,installed,c.vector,c.travel,15000));
const isClear=c=>['clear-to-seating','foundation'].includes(c.status);
const clear = record.candidates.filter(isClear);
const measurable = record.candidates.filter(c => Number.isFinite(c.remaining));
// If no certified approach exists, select a mechanically allowed direction that
// reaches closest to seating before first contact. Explicitly retain the warning.
const best = clear[0] ?? measurable.sort((a,b) => a.remaining-b.remaining)[0] ?? record.candidates[0];
const first = record.candidates[0];
const selected = !clear.length && first.status==='blocked-or-touching'
&& first.remaining <= (best.remaining ?? Infinity)+.00025 ? first : best;
record.selected = selected;
record.status = isClear(selected) ? 'clear-approach' : 'closest-approach-contact-remains';
// Preserve a practical finite entry distance; distant parts outside this swept
// range were excluded, so never use the longer internal check starting range.
const offset = vec(selected.vector).multiplyScalar(selected.travel).applyQuaternion(inverse);
parts.forEach(p => { p.installOffset=clean(offset.toArray()); });
record.changed = parts.some(p => Math.hypot(...p.installOffset.map((v,k)=>v-raw.parts.find(q=>q.id===p.id).installOffset[k]))>1e-8);
notes.steps[i].reason = `${notes.steps[i].reason}。${record.status==='clear-approach'
? 'BVH 检查:到最终落位前 0.15 mm 的直线进入路径未发现接触'
: '已比较允许的进入轴向;末段仍有接触/交叠,未认证全程无碰撞'}。`;
}
record.offsets=parts.map(p=>p.installOffset); records.push(record); installed.push(...moving);
console.log(`${i+1}/${result.steps.length} ${step.label}: ${record.status}${record.selected?.remaining!==undefined ? ` firstContact=${(record.selected.remaining*1000).toFixed(2)}mm` : ''}`);
writeFileSync(new URL('axis-review.progress.json',folder),JSON.stringify({completed:i+1,total:result.steps.length,records},null,2));
}
assert.deepEqual(result.steps,raw.steps); assert.deepEqual(result.files,raw.files); assert.deepEqual(result.tools,raw.tools);
for (let i=0;i<result.parts.length;i++) {
const {installOffset:a,...p}=result.parts[i], {installOffset:b,...q}=raw.parts[i]; assert.deepEqual(p,q);
}
validatePackage(result,'assembly','http://localhost:8090/manifest.json');
const summary = records.reduce((o,r)=>(o[r.status]=(o[r.status]??0)+1,o),{});
writeFileSync(new URL('manifest.json',folder),JSON.stringify(result,null,2)+'\n');
writeFileSync(new URL('manifest.notes.json',folder),JSON.stringify(notes,null,2)+'\n');
writeFileSync(new URL('axis-review.json',folder),JSON.stringify({
library:'three-mesh-bvh@0.9.17', seconds:(Date.now()-started)/1000,summary,
method:'Conservative advancement of full GLB triangle surfaces; mechanically constrained candidate axes; all earlier steps are obstacles.',
seatingToleranceMeters:.00015,collisionCertified:false, skipped:['3-36','3-37'],
limitations:['Left 52 offsets preserved from previous review.','Contact remains in multiple source mating geometries; closest-approach selection is a visual optimization, not a proof of collision freedom.',
'No rotation path planning or flexible/contact assembly; screw/tool swept volumes not certified.','Trunk same-type screw numbering has no occurrence pose; original component hole groups reused.'],steps:records,
},null,2)+'\n');
console.log(JSON.stringify({summary,seconds:(Date.now()-started)/1000}));
+214
View File
@@ -0,0 +1,214 @@
"""Build current upload assets, preserving source data and validating every dependency."""
import copy, hashlib, json, shutil, struct, zipfile
from pathlib import Path
import xml.etree.ElementTree as ET
REPO = Path(__file__).resolve().parents[1]
SOURCE = Path('/Users/jerry/Downloads/vibemakersandbox 2')
PUBLIC = SOURCE / 'app/public'
OUT = Path('/Users/jerry/Downloads/三个机器人-后台上传-20261030')
LFS = {r['path']: r for r in json.loads(Path('/tmp/make-current-lfs.json').read_text())}
VERIFIED_FILES = {}
PROVENANCE = []
def sha(data):
return hashlib.sha256(data).hexdigest()
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
def copy_file(source, dest):
data = source.read_bytes()
if data.startswith(b'version https://git-lfs.github.com/spec/v1'):
pointer = dict(line.split(' ', 1) for line in data.decode().strip().splitlines())
expected_sha = pointer['oid'].removeprefix('sha256:')
expected_size = int(pointer['size'])
key = source.relative_to(PUBLIC).as_posix()
local = Path(LFS[key]['local']) if key in LFS else VERIFIED_FILES.get(str(source))
if local is None or not local.is_file():
local = VERIFIED_FILES.get(str(source))
assert local and local.is_file(), f'Missing real Git LFS resource: {key}'
data = local.read_bytes()
assert len(data) == expected_size and sha(data) == expected_sha, key
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(data)
assert sha(dest.read_bytes()) == sha(data)
PROVENANCE.append({'file': dest.relative_to(OUT).as_posix(), 'source': str(source),
'bytes': len(data), 'sha256': sha(data)})
def copy_tree(source, dest):
for p in sorted(source.rglob('*')):
if p.is_file() and not any(s.startswith('.') for s in p.relative_to(source).parts):
copy_file(p, dest / p.relative_to(source))
def inventory(folder):
return [{'path': p.relative_to(folder).as_posix(), 'bytes': p.stat().st_size,
'sha256': sha(p.read_bytes())} for p in sorted(folder.rglob('*')) if p.is_file()]
def validate_motion(folder, entries):
def require(name):
p = folder / name
assert p.resolve().is_relative_to(folder.resolve()), name
assert p.is_file(), name
return p
configs = []
for entry in entries:
config_path = require(entry)
d = json.loads(config_path.read_text())
base = config_path.parent
paths = [d['model']] + [a['path'] for a in d['assets']]
paths += [a['path'] for a in d['render'].get('body_visuals', [])]
paths += [s['controller']['policy'] for s in d['skills']
if s['controller']['type'] == 'onnx' and s.get('available', True)]
for s in d['skills']:
if not s.get('reference'):
continue
spec = json.loads((base / s['reference']).read_text())
blob = (base / spec['data']).read_bytes()
assert len(blob) == spec['frames'] * len(spec['joint_names']) * 2 * 4
assert spec['joint_names'] == d['joints']['groups'][s['owns']]
assert abs(spec['step_dt'] - d['sim']['timestep'] * d['sim']['decimation']) < 1e-9
paths += [s['reference'], spec['data']]
for name in paths:
require((base / name).relative_to(folder).as_posix())
xml_path = base / d['model']
xml = ET.parse(xml_path).getroot()
compiler = xml.find('compiler')
for elem in xml.iter():
file = elem.get('file')
if not file:
continue
prefix = ''
if compiler is not None:
prefix = compiler.get('meshdir' if elem.tag == 'mesh' else 'texturedir', '') if elem.tag in ('mesh', 'texture') else ''
# The original Microduck adapter mounts meshes/<name> as assets/<name>
# in MuJoCo VFS (runtime.js), without changing the source MJCF.
if d['adapter'] == 'microduck' and elem.tag == 'mesh' and prefix == 'assets':
prefix = 'meshes'
require((xml_path.parent / prefix / file).relative_to(folder).as_posix())
configs.append({'entry': entry, 'id': d['id'], 'skills': [s['id'] for s in d['skills']], 'resourceReferences': len(paths)})
for name in ('source-manifest.json', 'visual-source-manifest.json'):
p = folder / name
if p.exists():
d = json.loads(p.read_text())
for record in d['files'] + d.get('additionalNotices', []):
assert sha(require(record['file']).read_bytes()) == record['sha256'], record['file']
for record in inventory(folder):
p = folder / record['path']
b = p.read_bytes()
assert not b.startswith(b'version https://git-lfs.github.com/spec/v1'), p
if p.suffix.lower() == '.glb':
magic, version, size, chunk, typ = struct.unpack_from('<5I', b)
assert (magic, version, size, typ) == (0x46546c67, 2, len(b), 0x4e4f534a), p
doc = json.loads(b[20:20+chunk])
assert all(not a.get('uri') or a['uri'].startswith('data:') for a in doc.get('buffers', []) + doc.get('images', [])), p
return configs
OUT.mkdir(exist_ok=True)
duck = OUT/'01-小鸭子-Microduck'
ban = OUT/'02-人形机器人-Microban'
rp1 = OUT/'03-双足机器人-RP1'
for name,folder,parts,whole in [
('Microduck',duck,Path('/Users/jerry/Downloads/开发提交/鸭子最新glb'),Path('/Users/jerry/Downloads/鸭子_压缩.glb')),
('Microban',ban,Path('/Users/jerry/Downloads/开发提交/人形机器人-light-最终使用'),Path('/Users/jerry/Documents/人形.glb')),
('RP1',rp1,Path('/Users/jerry/Downloads/开发提交/RP1机器人glb'),Path('/Users/jerry/Documents/RP1.glb')),
]:
folder.mkdir(exist_ok=True)
copy_file(whole,folder/'01-整机模型'/f'{name}-整机.glb')
for p in parts.glob('*.glb'):copy_file(p,folder/'02-零件模型'/p.name)
# The new filenames are mapped by embedded node identity, not guessed by filename suffix.
manifest=json.loads((REPO/'deliverables/experience-packages/microduck-current/manifest.json').read_text())
newparts=[]
for p in sorted((duck/'02-零件模型').glob('*.glb')):
data=p.read_bytes();size=struct.unpack_from('<I',data,12)[0];doc=json.loads(data[20:20+size])
nodes=[n for n in doc['nodes'] if 'mesh' in n];assert len(nodes)==1,p.name
newparts.append({'file':p.name,'node':nodes[0]['name'],'bytes':len(data),'sha256':sha(data)})
# Local preview uses these exact supplied files, without re-encoding.
shutil.copytree(duck/'02-零件模型',REPO/'deliverables/current-robots/duck-parts',dirs_exist_ok=True)
by_node={p['node']:p for p in newparts};assert len(by_node)==243
for part in manifest['parts']:
node=part['file'].removesuffix('.glb');assert node in by_node,node
part['file']=by_node[node]['file']
for tool in manifest['tools']:
assert (duck/'02-零件模型'/tool['file']).is_file()
manifest['files']=[{'path':p['file'],'bytes':p['bytes'],'sha256':p['sha256']}for p in newparts]
assert len(manifest['steps'])==239 and len(manifest['parts'])==242
write_json(duck/'03-拼装步骤/小鸭子-239步装配.json',manifest)
copy_file(REPO/'deliverables/experience-packages/microduck-current/mapping.json',OUT/'开发核对/小鸭子-编号与模型差异.json')
write_json(OUT/'开发核对/小鸭子-原始零件文件校验.json',newparts)
(OUT/'开发核对/小鸭子-零件压缩与材质校验.json').unlink(missing_ok=True)
motion_roots={}
for name,folder in [('microduck',duck),('microban',ban),('rp1',rp1)]:
motion=REPO/'deliverables/current-robots'/name/'motion'
motion_roots[name]=motion
# copy_file records are relative to OUT: prepare inside upload folder first, then mirror for local preview.
stage=folder/'04-运动资源';stage.mkdir(exist_ok=True)
if name=='microduck':
for sub in ['robot','policies','assets','worlds','licenses']:copy_tree(PUBLIC/sub,stage/sub)
for srcname,target in [('microduck-legs','robot.json'),('microduck-rollers','variants/rollers.json')]:
d=json.loads((PUBLIC/'robots'/srcname/'robot.json').read_text());prefix=''if target=='robot.json'else'../'
d['model']=prefix+d['model'].removeprefix('../../')
for skill in d['skills']:
if skill['controller'].get('policy'):skill['controller']['policy']=prefix+skill['controller']['policy'].removeprefix('../../')
write_json(stage/target,d)
else:copy_tree(PUBLIC/'robots'/name,stage)
copy_file(SOURCE/'LICENSE',stage/'Sandbox-LICENSE')
for filename in ['NOTICE','UPSTREAM.md']:copy_file(REPO/'sandbox'/filename,stage/f'Sandbox-{filename}')
configs=validate_motion(stage,['robot.json','variants/rollers.json']if name=='microduck'else['robot.json'])
files=inventory(stage);size=sum(f['bytes']for f in files)
archive=folder/'04-仿真.zip'
(folder/'04-运动演示.zip').unlink(missing_ok=True)
with zipfile.ZipFile(archive,'w',zipfile.ZIP_DEFLATED,compresslevel=6)as z:
for f in files:z.write(stage/f['path'],f['path'])
with zipfile.ZipFile(archive)as z:assert z.testzip()is None
print(name,'motion',len(files),'files',round(size/1024/1024,1),'MiB', 'skills',configs[0]['skills'],flush=True)
shutil.copytree(stage,motion,dirs_exist_ok=True)
# ZIP is the only visible motion upload choice, so there is no duplicated directory to confuse uploaders.
shutil.rmtree(stage)
copy_file(SOURCE/f'docs/robots/{"microduck" if name=="microduck" else name}.md',OUT/f'开发核对/{name}-上游说明.md') if (SOURCE/f'docs/robots/{name}.md').exists()else None
instructions=f'''{name} 后台上传顺序
1. 整机模型:选择 01-整机模型 中的 GLB。
2. 零件模型:选择整个 02-零件模型 文件夹,保留文件名。
3. 拼装步骤:{'上传 03-拼装步骤/小鸭子-239步装配.json。' if name=='microduck' else '留空;此机器人没有安装步骤 JSON。若此前绑定过旧步骤,请清除旧步骤绑定。'}
4. 仿真:上传 04-仿真.zip。ZIP 解压根目录直接是 robot.json。
运动包包含模型、物理配置、控制配置、策略、动作数据及其依赖;不需要另传 JS、WASM 或网页。
随机几何体、碰撞/拖拽、光照、背景与网格调色由新版社区播放器提供;只上传 ZIP 不会更新旧前端。
先部署本次新版前端,再刷新项目详情验证。打开默认静止,方向键或动作按钮可直接开始;只有配置的动作才显示。
'''
if name=='microduck':instructions+='''
本次为最新完整 239 步:左腿 52、右腿 52、躯干 47、颈部 24、头部 64。
沿用已确认的双腿/已有躯干安装规则及扳手动画。242 个本次零件 + 1 个扳手,全部与新文件名匹配。
本次零件直接复制你提供的 GLB,字节、材质、颜色、贴图和文件名全部保持原样,不再额外压缩。
165 颗杯头螺丝的扳手朝向已修正为工作端对准螺丝头;原打入轴向及 239 步顺序保持不变。
整机用此前给出的最新“鸭子_压缩.glb”;零件用本次“鸭子最新glb”,最终安装坐标来自对应整机。
部分源模型配合接触/编号规格差异仍按上轮说明保留,未宣称全程无穿模。
'''
if name=='rp1':instructions+='''
本次 RP1 仿真使用上游新增的带原材质视觉件;63 个零件挂接到现有 25 个物理 body。
两个手部由上游工具按固定手型合并,原材质/贴图保留;未改变物理关节、训练策略。
动作包括行走、跳舞和挥手;没有踢球,不需要足球策略。
'''
(folder/'上传说明.txt').write_text(instructions)
(OUT/'先看这里.txt').write_text('''三个机器人 · 最新后台上传资料 · 2026-10-30
每个机器人分别进入自己的后台项目,按子目录里的“上传说明.txt”上传。
01-小鸭子-Microduck:整机 GLB、243 个零件/工具 GLB、239 步 JSON、运动 ZIP。
02-人形机器人-Microban:整机 GLB、20 个零件 GLB、运动 ZIP;拼装步骤留空。
03-双足机器人-RP1:整机 GLB、63 个零件 GLB、运动 ZIP;拼装步骤留空。
不要把这整个总文件夹压成一个包上传到仿真;分别用各机器人里的 04-仿真.zip。
零件需整批替换/绑定,避免旧零件混入。小鸭子 JSON 必须与本批 02 文件夹配套。
开发核对目录只供核对,不需要上传。
本次只准备文件和更新社区播放器,没有替你修改后台资源绑定。
''')
write_json(OUT/'开发核对/文件来源与SHA256.json',PROVENANCE)
print('READY',OUT)
+277
View File
@@ -0,0 +1,277 @@
// Reproducible assembly package from the user's numbered order and current whole GLB.
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import draco3d from 'draco3dgltf';
import { Vector3, Quaternion, Matrix4, BufferGeometry, BufferAttribute } from 'three';
import { collider, checkFiniteAxis, VIEW_AXES } from './lib/assembly-axis-planner.mjs';
import { validatePackage } from '../js/experience-packages.js';
const sourcePath='/Users/jerry/Downloads/鸭子_压缩.glb';
const orderPath='/Users/jerry/Downloads/鸭子顺序';
const output=new URL('../deliverables/experience-packages/microduck-current/',import.meta.url).pathname;
const refining=process.argv.includes('--refine');
const previousManifest=refining?JSON.parse(fs.readFileSync(path.join(output,'manifest.json'))):null;
const previousReview=refining?JSON.parse(fs.readFileSync(path.join(output,'axis-review.json'))):null;
fs.mkdirSync(output,{recursive:true});
const bytes=fs.readFileSync(sourcePath), source=JSON.parse(bytes.subarray(20,20+bytes.readUInt32LE(12)).toString());
const binOffset=20+bytes.readUInt32LE(12)+8;
const canonical=s=>s.trim().replace(/^镜向/,'').replace(/^BU /,'').replace(/\.\d+$/,'').replace(/^0914舵机装配1$/,'0914舵机装配');
const clean=a=>a.map(x=>Math.abs(x)<1e-11?0:x);
const vec=a=>new Vector3(...a);
const hash=b=>createHash('sha256').update(b).digest('hex');
const write=(name,value)=>fs.writeFileSync(path.join(output,name),JSON.stringify(value,null,2)+'\n');
const order=[];
function walk(dir){for(const f of fs.readdirSync(dir,{withFileTypes:true})){
const filename=path.join(dir,f.name);if(f.isDirectory()){walk(filename);continue;}
if(!/\.(step|stp|sldprt)$/i.test(f.name))continue;
const m=/^([1-5])-(\d+)-?(.*)\.(step|stp|sldprt)$/i.exec(f.name);assert.ok(m,f.name);
let group=+m[1],n=+m[2],label=m[3];
if(group===3&&f.name.includes('0914舵机')){n=+f.name[2];label='0914舵机装配';}
order.push({group,n,label:label.trim(),code:`${group}-${n}`,source:path.relative(orderPath,filename)});
}}
walk(orderPath);order.sort((a,b)=>a.group-b.group||a.n-b.n);
for(const g of [1,2,3,4,5])assert.deepEqual(order.filter(o=>o.group===g).map(o=>o.n),Array.from({length:[0,52,52,47,24,64][g]},(_,i)=>i+1));
const nodes=source.nodes.map((n,index)=>({index,name:n.name,key:canonical(n.name),position:n.translation??[0,0,0],quaternion:n.rotation??[0,0,0,1]}));
assert.equal(nodes.length,242);assert.ok(source.nodes.every(n=>!n.children?.length));
const old=JSON.parse(fs.readFileSync('/Users/jerry/Downloads/小鸭子-双腿及躯干-当前上传/小鸭子-双腿及躯干-149步装配.json'));
const oldQ=new Quaternion(...old.displayQuaternion),oldParts=new Map(old.parts.map(p=>[p.id,p]));
const oldSteps=new Map(old.steps.map(s=>[s.id.split('-').slice(-2).join('-'),s]));
const used=new Set(),mapping=new Map();
function assign(o,node,method){assert.ok(node,`No node ${o.code}`);assert.ok(!used.has(node.index),`Duplicate ${o.code}: ${node.index}`);used.add(node.index);mapping.set(o.code,{...o,node:node.index,name:node.name,method});}
function options(o){return nodes.filter(n=>!used.has(n.index)&&n.key===canonical(o.label));}
function target(o){const s=oldSteps.get(o.code);return s?vec(oldParts.get(s.parts[0]).position).applyQuaternion(oldQ):null;}
for(const o of order.filter(o=>o.group<=3)){
const t=target(o);if(!t)continue;
const matches=options(o).filter(n=>vec(n.position).distanceTo(t)<.0001);assert.ok(matches.length<=1,`Ambiguous ${o.code}`);
if(matches.length)assign(o,matches[0],'原步骤位置与新整机一致');
}
for(const o of order.filter(o=>o.group<=3&&!mapping.has(o.code)&&oldSteps.has(o.code))){
const t=target(o), choices=options(o).sort((a,b)=>vec(a.position).distanceTo(t)-vec(b.position).distanceTo(t));
if(!choices.length){console.log('UNMATCHED',o.code,o.label);continue;}
assign(o,choices[0],'同名零件按整机位置匹配');mapping.get(o.code).oldDistanceMm=vec(choices[0].position).distanceTo(t)*1000;
}
write('mapping-initial.json',{source:sourcePath,sourceSha256:hash(bytes),order,matches:[...mapping.values()],remaining:nodes.filter(n=>!used.has(n.index))});
// Current whole-model instances: keep their actual geometry/specification even where
// the numbered filename has a different screw length. Such differences are reported.
const manual={
'3-36':101,'3-37':102,
'4-1':6,'4-14':32,'4-15':127,'4-16':128,'4-17':31,'4-18':133,'4-19':134,
'4-20':7,'4-21':129,'4-22':130,'4-23':131,'4-24':132,
'5-1':33,'5-2':9,'5-21':55,'5-22':220,'5-23':221,'5-24':186,'5-25':187,
'5-26':48,'5-27':18,'5-28':8,'5-29':49,'5-30':65,'5-31':10,'5-32':233,
'5-33':56,'5-40':30,'5-45':21,'5-46':241,'5-47':85,'5-48':89,
'5-49':29,'5-50':83,'5-51':84,'5-52':87,'5-53':90,
'5-54':20,'5-55':86,'5-56':88,'5-57':91,'5-58':92,
'5-59':19,'5-60':34,'5-61':39,'5-62':194,'5-63':195,'5-64':222,
};
for(const [g,start,indices] of [[4,2,[205,206,207,208,209,211,226,227,228,229,230,231]],
[5,3,[199,200,201,202,203,204]],[5,9,[214,215,216,217,218,219,180,181,182,183,184,185]],
[5,34,[188,189,190,191,192,193]],[5,41,[135,136,137,138]]])
indices.forEach((v,i)=>{manual[`${g}-${start+i}`]=v;});
for(const o of order.filter(o=>!mapping.has(o.code)))assign(o,nodes[manual[o.code]],'新整机对应组件与紧固孔位');
assert.equal(mapping.size,239);
const extras=[{node:41,code:'3-44',reason:'整机附带的 trunk_shell_left,与外壳一起显示'},
{node:66,code:'5-49',reason:'整机摄像头与镜头支架一起安装'},
{node:225,code:'4-13',reason:'整机额外的 M2x8.047,保留原位置,与颈部最后一颗螺丝一起显示;清单未单列'}];
assert.deepEqual(nodes.filter(n=>!used.has(n.index)).map(n=>n.index),extras.map(e=>e.node).sort((a,b)=>a-b));
const mismatches=[...mapping.values()].filter(m=>nodes[m.node].key!==canonical(m.label));
write('mapping.json',{source:sourcePath,sourceSha256:hash(bytes),steps:order.map(o=>mapping.get(o.code)),extras,mismatches});
console.log('Mapped',mapping.size,'numbered steps;',extras.length,'whole-model extras;',mismatches.length,'label differences');
// Extract the original compressed mesh and embedded textures byte-for-byte.
// This does not decode/re-encode geometry, change materials, or resize textures.
function extract(index){
const node=source.nodes[index],out={asset:structuredClone(source.asset),scene:0,scenes:[{nodes:[0]}],
nodes:[{name:node.name,mesh:0}],meshes:[],materials:[],textures:[],images:[],samplers:[],accessors:[],bufferViews:[],buffers:[]},
maps=new Map(),chunks=[];let total=0;
const copy=(type,i,fn)=>{if(!maps.has(type))maps.set(type,new Map());const m=maps.get(type);
if(m.has(i))return m.get(i);const n=out[type].length;m.set(i,n);out[type].push(null);out[type][n]=fn(structuredClone(source[type][i]));return n;};
const view=i=>copy('bufferViews',i,v=>{
const chunk=bytes.subarray(binOffset+(v.byteOffset??0),binOffset+(v.byteOffset??0)+v.byteLength);
assert.equal(chunk.length,v.byteLength);const pad=(4-total%4)%4;if(pad){chunks.push(Buffer.alloc(pad));total+=pad;}
v.buffer=0;v.byteOffset=total;chunks.push(chunk);total+=chunk.length;return v;
});
const accessor=i=>copy('accessors',i,a=>{if(a.bufferView!==undefined)a.bufferView=view(a.bufferView);
if(a.sparse){a.sparse.indices.bufferView=view(a.sparse.indices.bufferView);a.sparse.values.bufferView=view(a.sparse.values.bufferView);}return a;});
const image=i=>copy('images',i,a=>{assert.ok(a.bufferView!==undefined&&!a.uri);a.bufferView=view(a.bufferView);return a;});
const texture=i=>copy('textures',i,t=>{if(t.source!==undefined)t.source=image(t.source);if(t.sampler!==undefined)t.sampler=copy('samplers',t.sampler,v=>v);assert.ok(!t.extensions);return t;});
const material=i=>copy('materials',i,m=>{function scan(v){for(const[k,x]of Object.entries(v))if(x&&typeof x==='object'){
if(/Texture$/.test(k)&&x.index!==undefined)x.index=texture(x.index);else scan(x);}}scan(m);return m;});
out.meshes.push(structuredClone(source.meshes[node.mesh]));
for(const p of out.meshes[0].primitives){for(const k of Object.keys(p.attributes))p.attributes[k]=accessor(p.attributes[k]);
if(p.indices!==undefined)p.indices=accessor(p.indices);if(p.material!==undefined)p.material=material(p.material);
if(p.extensions?.KHR_draco_mesh_compression)p.extensions.KHR_draco_mesh_compression.bufferView=view(p.extensions.KHR_draco_mesh_compression.bufferView);
assert.ok(!p.targets);
}
out.extensionsUsed=source.extensionsUsed;out.extensionsRequired=source.extensionsRequired;
out.buffers=[{byteLength:total}];let json=Buffer.from(JSON.stringify(out));json=Buffer.concat([json,Buffer.alloc((4-json.length%4)%4,32)]);
const bin=Buffer.concat([...chunks,Buffer.alloc((4-total%4)%4)]),h=Buffer.alloc(20),bh=Buffer.alloc(8);
h.writeUInt32LE(0x46546c67,0);h.writeUInt32LE(2,4);h.writeUInt32LE(28+json.length+bin.length,8);h.writeUInt32LE(json.length,12);h.writeUInt32LE(0x4e4f534a,16);
bh.writeUInt32LE(bin.length,0);bh.writeUInt32LE(0x004e4942,4);return Buffer.concat([h,json,bh,bin]);
}
const parts=nodes.map(n=>({id:`duck-${String(n.index).padStart(3,'0')}`,file:`${n.name}.glb`,parentId:null,
position:n.position,quaternion:new Quaternion(...n.quaternion).normalize().toArray(),scale:source.nodes[n.index].scale??[1,1,1],installOffset:[0,.04,0]}));
const files=[];
for(const p of parts){const b=extract(+p.id.slice(5));fs.writeFileSync(path.join(output,p.file),b);files.push({path:p.file,bytes:b.length,sha256:hash(b)});}
const tools=structuredClone(old.tools);
for(const tool of tools) tool.tipAxis=[0,0,-1];
for(const t of tools){const b=fs.readFileSync(path.join('/Users/jerry/Downloads/小鸭子-扳手装配/零件模型',t.file));fs.writeFileSync(path.join(output,t.file),b);files.push({path:t.file,bytes:b.length,sha256:hash(b)});}
const manifest={schemaVersion:1,kind:'assembly',title:'小鸭子 · 最新整机与完整编号顺序',unit:'meter',displayQuaternion:[0,0,0,1],files,parts,
steps:order.map(o=>({id:`step-${o.code}`,label:`${o.code} · ${o.label}`,parts:[parts[mapping.get(o.code).node].id,...extras.filter(e=>e.code===o.code).map(e=>parts[e.node].id)]})),tools};
validatePackage(manifest,'assembly','http://localhost:8090/manifest.json');
write('input.json',manifest);
console.log('Extracted',files.length,'files, total MiB',files.reduce((s,f)=>s+f.bytes,0)/1024**2);
// Decode only for analysis. Output GLBs remain byte-preserving extractions above.
const io=new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'draco3d.decoder':await draco3d.createDecoderModule()});
const doc=await io.readBinary(bytes),geometry=new Map(),facts=[];
for(const [i,n] of doc.getRoot().listNodes().entries()){
const arrays=[],indices=[];let count=0;
for(const p of n.getMesh().listPrimitives()){
const a=p.getAttribute('POSITION').getArray();arrays.push(a);for(const ix of p.getIndices().getArray())indices.push(ix+count);count+=a.length/3;
}
const positions=new Float32Array(count*3);let cursor=0;for(const a of arrays){positions.set(a,cursor);cursor+=a.length;}
const g=new BufferGeometry().setAttribute('position',new BufferAttribute(positions,3));g.setIndex(new BufferAttribute(new Uint32Array(indices),1));g.computeBoundingBox();
geometry.set(i,g);facts.push({node:i,name:n.getName(),min:g.boundingBox.min.toArray(),max:g.boundingBox.max.toArray(),vertices:count,triangles:indices.length/3});
}
write('geometry-facts.json',facts);console.log('Geometry decoded');
function principalAxes(g){
const a=g.attributes.position,mean=new Vector3(),p=new Vector3();for(let i=0;i<a.count;i++)mean.add(p.fromBufferAttribute(a,i));mean.divideScalar(a.count);
const c=Array.from({length:3},()=>[0,0,0]),v=[[1,0,0],[0,1,0],[0,0,1]];
for(let i=0;i<a.count;i++){const q=p.fromBufferAttribute(a,i).sub(mean).toArray();for(let r=0;r<3;r++)for(let s=0;s<3;s++)c[r][s]+=q[r]*q[s];}
for(let k=0;k<30;k++){
let r=0,s=1;for(const [i,j]of[[0,2],[1,2]])if(Math.abs(c[i][j])>Math.abs(c[r][s])){r=i;s=j;}
if(Math.abs(c[r][s])<1e-15)break;
const t=.5*Math.atan2(2*c[r][s],c[s][s]-c[r][r]),co=Math.cos(t),si=Math.sin(t),rr=c[r][r],ss=c[s][s],rs=c[r][s];
c[r][r]=co*co*rr-2*si*co*rs+si*si*ss;c[s][s]=si*si*rr+2*si*co*rs+co*co*ss;c[r][s]=c[s][r]=0;
for(let i=0;i<3;i++)if(i!==r&&i!==s){const ir=c[i][r],is=c[i][s];c[i][r]=c[r][i]=co*ir-si*is;c[i][s]=c[s][i]=si*ir+co*is;}
for(let i=0;i<3;i++){const ir=v[i][r],is=v[i][s];v[i][r]=co*ir-si*is;v[i][s]=si*ir+co*is;}
}
return [0,1,2].map(i=>({value:c[i][i],vector:new Vector3(v[0][i],v[1][i],v[2][i])})).sort((a,b)=>a.value-b.value);
}
function screwGeometry(g){
let axis=principalAxes(g)[2].vector;
// End caps provide exact axial normals, removing tessellation-induced PCA tilt.
const a=g.attributes.position,idx=g.index.array,groups=new Map(),v0=new Vector3(),v1=new Vector3(),v2=new Vector3(),cross=new Vector3();
for(let i=0;i<idx.length;i+=3){v0.fromBufferAttribute(a,idx[i]);v1.fromBufferAttribute(a,idx[i+1]).sub(v0);v2.fromBufferAttribute(a,idx[i+2]).sub(v0);
cross.crossVectors(v1,v2);const area=cross.length();if(area<1e-15)continue;cross.divideScalar(area);
if(Math.abs(cross.dot(axis))<.97)continue;if(cross.dot(axis)<0)cross.negate();
const key=cross.toArray().map(x=>Math.round(x*1000)).join(',');if(!groups.has(key))groups.set(key,{area:0,normal:new Vector3()});
const b=groups.get(key);b.area+=area;b.normal.addScaledVector(cross,area);
}
const dominant=[...groups.values()].sort((a,b)=>b.area-a.area)[0];assert.ok(dominant);axis=dominant.normal.normalize();
const project=axis=>{let min=Infinity,max=-Infinity;for(let i=0;i<a.count;i++){const d=v0.fromBufferAttribute(a,i).dot(axis);min=Math.min(min,d);max=Math.max(max,d);}return{min,max};};
let {min,max}=project(axis);
const center=g.boundingBox.getCenter(new Vector3()),radialCenter=center.clone().addScaledVector(axis,-center.dot(axis));
const width=(at)=>{let radius=0;for(let i=0;i<a.count;i++){v0.fromBufferAttribute(a,i);const d=v0.dot(axis);if(Math.abs(d-at)>.0006)continue;radius=Math.max(radius,v0.addScaledVector(axis,-d).distanceTo(radialCenter));}return radius;};
const lo=width(min),hi=width(max);if(lo>hi){axis.negate();({min,max}=project(axis));}
// Center the head cap in two perpendicular coordinates; no node-origin assumption.
const u=new Vector3().crossVectors(axis,Math.abs(axis.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0)).normalize(),v=new Vector3().crossVectors(axis,u);
let u0=Infinity,u1=-Infinity,vv0=Infinity,vv1=-Infinity;
for(let i=0;i<a.count;i++){v0.fromBufferAttribute(a,i);if(v0.dot(axis)<max-.0006)continue;const x=v0.dot(u),y=v0.dot(v);u0=Math.min(u0,x);u1=Math.max(u1,x);vv0=Math.min(vv0,y);vv1=Math.max(vv1,y);}
const socket=axis.clone().multiplyScalar(max-.00035).addScaledVector(u,(u0+u1)/2).addScaledVector(v,(vv0+vv1)/2);
return{outward:axis,socket,headRadii:[lo,hi],length:max-min};
}
const screwFacts=[];
for(const p of parts){
const i=+p.id.slice(5);if(!/螺钉/.test(nodes[i].name))continue;
const s=screwGeometry(geometry.get(i)),q=new Quaternion(...p.quaternion),outward=s.outward.clone().applyQuaternion(q).normalize();
p.installOffset=clean(outward.clone().multiplyScalar(.018).toArray());
if(/^标准杯头/.test(nodes[i].name)){
const inward=s.outward.clone().negate(),toolQ=new Quaternion().setFromUnitVectors(new Vector3(0,0,-1),inward)
.multiply(new Quaternion().setFromAxisAngle(new Vector3(0,0,1),Math.PI/6));
p.installation={type:'screw',toolId:tools[0].id,axis:clean(inward.toArray()),socketPosition:clean(s.socket.toArray()),toolQuaternion:toolQ.toArray(),
direction:'clockwise',turns:3,travel:.0012,approachDuration:.45,engageDuration:.3,tightenDuration:2.4,retractDuration:.35,toolClearance:.012};
}
screwFacts.push({node:i,name:nodes[i].name,outward:outward.toArray(),localOutward:s.outward.toArray(),socket:s.socket.toArray(),headRadii:s.headRadii,length:s.length});
}
write('screw-axes.json',screwFacts);
const worldGeometry=new Map();
function getCollider(i){if(!worldGeometry.has(i)){
const p=parts[i],g=geometry.get(i).clone().applyMatrix4(new Matrix4().compose(vec(p.position),new Quaternion(...p.quaternion),vec(p.scale)));
worldGeometry.set(i,collider(p.id,g));}return worldGeometry.get(i);}
const records=[],installed=[];
const idIndex=new Map(parts.map((p,i)=>[p.id,i]));
function candidates(o,indices){
const p=parts[indices[0]],out=[],add=(name,v)=>{v=v.clone().normalize();if(v.lengthSq()&&!out.some(c=>vec(c.vector).distanceTo(v)<1e-4))out.push({name,vector:clean(v.toArray())});};
const local=v=>vec(v).applyQuaternion(new Quaternion(...p.quaternion));
const prev=oldSteps.get(o.code);let preference=prev?vec(oldParts.get(prev.parts[0]).installOffset).applyQuaternion(oldQ):vec([0,1,0]);
if(o.group<=2&&[1,2].includes(o.n)){
if(refining&&o.n===2){const up=local([0,0,1]);if(up.y<0)up.negate();add('沿脚板法向从上往下',up);}
add('从上往下',vec([0,1,0]));return out;
}
if(o.group<=2&&o.n===7){
const foot=parts[mapping.get(`${o.group}-2`).node],up=vec([0,0,1]).applyQuaternion(new Quaternion(...foot.quaternion));if(up.y<0)up.negate();
add('沿脚板法向从上往下',up);add('从上往下',vec([0,1,0]));
for(const z of refining?[.08,.15,.25,.4,.6,.8]:[.15])for(const x of refining?[-.2,0,.2]:[0])add(`上方进入 ${x},${z}`,up.clone().add(vec([x,0,o.group===1?-z:z])));
return out;
}
if(/^(w_61702|深沟球轴承)/.test(o.label)){
const normal=principalAxes(geometry.get(indices[0]))[0].vector.applyQuaternion(new Quaternion(...p.quaternion));if(normal.dot(preference)<0)normal.negate();
add('沿轴承孔轴线',normal);add('反向沿轴承孔轴线',normal.clone().negate());return out;
}
if(o.group===4&&[14,17].includes(o.n)){add('从支架外侧插入',vec([0,0,o.n===14?1:-1]));return out;}
if(o.group===5&&[45,46,49,60].includes(o.n))preference=vec([1,0,0]);
if(o.group===5&&o.n===61)preference=vec([0,1,0]);
add('优先安装方向',preference);
for(const a of VIEW_AXES)add(a.label,vec(a.vector));
// Local fit normals also cover the slightly tilted leg and head components.
if(o.group<=2||o.group===5)for(const a of VIEW_AXES)add(`零件局部 ${a.name}`,local(a.vector));
if(refining&&[...previousReview.records].find(r=>r.code===o.code)?.selected.firstContact>.004)
for(const x of [-1,0,1])for(const y of [-1,0,1])for(const z of [-1,0,1])if(x||y||z)add(`斜向 ${x},${y},${z}`,vec([x,y,z]));
return out;
}
function sampledPath(moving,obstacles,vector,travel){
const v=vec(vector),sweeps=moving.map(m=>m.box.clone().union(m.box.clone().translate(v.clone().multiplyScalar(travel))));
const relevant=obstacles.filter(b=>sweeps.some(s=>s.intersectsBox(b.box))),matrix=new Matrix4();
let firstContact=0,hits=0,checks=0;const states=[],spacing=refining?.0005:.001;
for(let d=travel;d>.00015;d-=spacing){const offset=v.clone().multiplyScalar(d);matrix.makeTranslation(...offset.toArray());let hit=false;
for(const a of moving){const box=a.box.clone().translate(offset);for(const b of relevant){if(box.intersectsBox(b.box)&&b.bvh.intersectsGeometry(a.geometry,matrix)){hit=true;break;}}if(hit)break;}
checks++;states.push({d,hit});if(hit){hits++;if(!firstContact)firstContact=d;}
}
if(refining){
// Choose a visible entry window within the available space, never launch a
// bearing from the opposite leg. Report residual terminal contact explicitly.
const ascending=[...states].reverse();let window=null;
for(let a=0;a<ascending.length;){if(ascending[a].hit){a++;continue;}let b=a;
while(b+1<ascending.length&&!ascending[b+1].hit)b++;
const available=ascending[b].d-spacing;
if(available-ascending[a].d>=.004){window={travel:available,firstContact:a?ascending[a-1].d:0};break;}a=b+1;
}
if(window)return{...window,hits,checks,fullTravel:travel,sampleSpacing:spacing};
}
return{firstContact,hits,checks,sampleSpacing:spacing};
}
for(const [i,o]of order.entries()){
const step=manifest.steps[i],indices=step.parts.map(id=>idIndex.get(id)),moving=indices.map(getCollider),p=parts[indices[0]],fastener=/螺钉/.test(o.label);
const record={code:o.code,label:step.label,nodes:indices};
if(fastener){
if(refining){Object.assign(record,previousReview.records[i]);for(const ix of indices)parts[ix].installOffset=previousManifest.parts[ix].installOffset;}
else {
// Each screw keeps its own measured axis, including a grouped extra instance.
record.kind='screw';record.selected={name:'沿螺丝自身轴线',vector:vec(p.installOffset).normalize().toArray(),travel:.018};
record.check=checkFiniteAxis([moving[0]],installed,record.selected.vector,.018,{maxMilliseconds:900,maxIterations:160});
}
}else{
const travel=o.group<=2&&[1,2,7].includes(o.n)?.055:.045;
record.candidates=candidates(o,indices).map(c=>({...c,travel,...sampledPath(moving,installed,c.vector,travel)}));
record.candidates.sort((a,b)=>a.firstContact-b.firstContact||a.hits-b.hits);
const selected=record.candidates[0];record.kind='component';record.selected=selected;
record.check=checkFiniteAxis(moving,installed,selected.vector,selected.travel,{maxMilliseconds:2500,maxIterations:250});
for(const ix of indices)parts[ix].installOffset=clean(vec(selected.vector).multiplyScalar(selected.travel).toArray());
}
record.offsets=indices.map(ix=>parts[ix].installOffset);records.push(record);installed.push(...moving);
write('axis-review.progress.json',{completed:i+1,total:order.length,records});
console.log(`${i+1}/239 ${o.code} ${record.selected.name}: ${record.check.status} contact=${((record.check.remaining??0)*1000).toFixed(2)}mm`);
}
validatePackage(manifest,'assembly','http://localhost:8090/manifest.json');
write('manifest.json',manifest);
write('manifest.notes.json',{steps:records.map(r=>({reason:`${r.selected.name};装入距离 ${Math.round(r.selected.travel*1000)} mm。${['foundation','clear-to-seating'].includes(r.check.status)?'平移路径检查通过(保留最后 0.15 mm 装配接触区)。':'末段存在接触或尚未验证,见说明。'}`}))});
write('axis-review.json',{sourceSha256:hash(bytes),method:'Triangle BVH: candidate screening at 1 mm, then conservative advancement; fixed screw axes and bearing fit axes.',
collisionCertified:false,seatingToleranceMeters:.00015,limitations:['终点配合接触、螺丝旋转与扳手扫掠不在本次平移路径认证范围内。','同规格紧固件在同一组内沿原整机孔位依次安装;单件顺序文件没有独立实例坐标。'],records});
console.log('DONE',output);
+111
View File
@@ -0,0 +1,111 @@
// 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));
+155
View File
@@ -0,0 +1,155 @@
// Numbered CAD supplies order/placements; the existing GLBs and materials stay intact.
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 'three';
import { stepPlacements } from './lib/step-placements.mjs';
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
const previous = '/Users/jerry/Downloads/小鸭子-扳手装配';
const assets = join(previous, '零件模型');
const leftSource = '/Users/jerry/Downloads/小鸭子-52步装配-当前上传/小鸭子-左腿-52步装配.json';
const rightInput = '/Users/jerry/Downloads/2-0腿装配(R)stp';
const trunkInput = '/Users/jerry/Downloads/躯干顺序(stp)';
const preview = new URL('../deliverables/experience-packages/microduck-numbered-body/', import.meta.url).pathname;
const original = JSON.parse(readFileSync(join(previous, '鸭子-拼装步骤-带扳手.json')));
const alignment = JSON.parse(readFileSync(new URL('../deliverables/experience-packages/microduck-parts-assembly/alignment-report.json', import.meta.url)));
const raw = JSON.parse(readFileSync(leftSource));
const byId = new Map(original.parts.map(p => [p.id, p]));
const id = n => `duck-part-${String(n).padStart(3, '0')}`;
const canonical = name => name.replace(/^镜向/, '').replace(/^0914舵机装配1$/, '0914舵机装配');
const matrix = p => new Matrix4().compose(new Vector3(...p.position), new Quaternion(...p.quaternion), new Vector3(...p.scale));
const display = new Quaternion(...raw.displayQuaternion);
const clean = a => a.map(n => Math.abs(n) < 1e-12 ? 0 : n);
const notes = JSON.parse(readFileSync(new URL('../deliverables/experience-packages/microduck-left-numbered/directions-52.notes.json', import.meta.url))).steps;
const records = [], rightParts = [], rightSteps = [];
const cad = stepPlacements(join(rightInput, '2-0-腿装配 (R).STEP'));
const numbered = cad.top.map(o => {
const m = /^2-(\d+)-(.+)$/.exec(o.name); assert.ok(m, o.name);
return { ...o, n: +m[1], label: m[2] };
}).sort((a, b) => a.n - b.n);
assert.deepEqual(numbered.map(o => o.n), Array.from({ length: 52 }, (_, i) => i + 1));
// Independent STEP filenames confirm the list, including mirrored names in the total assembly.
for (const o of numbered) assert.ok(readdirSync(rightInput).some(f =>
f.startsWith(`2-${o.n}-`) && canonical(f.replace(/^2-\d+-/, '').replace(/\.step$/i, '')) === canonical(o.label)), o.name);
const groups = new Map();
for (const a of alignment.parts.filter(p => p.group === '腿装配 (R)')) {
const key = a.path[2];
if (!groups.has(key)) groups.set(key, { key, label: canonical(key.split('@')[0]), parts: [] });
groups.get(key).parts.push(byId.get(a.id));
}
const used = new Set(), matched = new Map();
const candidates = o => [...groups.values()].filter(g => !used.has(g.key) && g.label === canonical(o.label));
const distance = (o, g) => new Vector3().setFromMatrixPosition(o.matrix).distanceTo(new Vector3(...g.parts[0].position));
// Reserve exact matches first so moved screws cannot steal another step's instance.
for (const o of numbered) {
const near = candidates(o).filter(g => distance(o, g) < 0.0001);
assert.ok(near.length <= 1, `Ambiguous exact match: ${o.name}`);
if (near.length) { used.add(near[0].key); matched.set(o.n, near[0]); }
}
for (const o of numbered.filter(o => !matched.has(o.n))) {
const options = candidates(o).sort((a, b) => /螺钉/.test(o.label)
? a.parts[0].file.localeCompare(b.parts[0].file, 'en', { numeric: true }) : distance(o, a) - distance(o, b));
assert.ok(options.length, `No matching GLB: ${o.name}`);
if (!/螺钉/.test(o.label)) {
assert.ok(distance(o, options[0]) < 0.005, `Unexplained changed component: ${o.name}`);
assert.ok(options.length === 1 || distance(o, options[1]) > distance(o, options[0]) + 0.001);
}
used.add(options[0].key); matched.set(o.n, options[0]);
}
function screwOffset(p) {
return clean(new Vector3(...(p.installation?.axis ?? [0, 0, -1])).negate().normalize()
.multiplyScalar(0.020).applyQuaternion(new Quaternion(...p.quaternion)).toArray());
}
for (const o of numbered) {
const g = matched.get(o.n), selected = structuredClone(g.parts);
const delta = o.matrix.clone().multiply(matrix(g.parts[0]).invert());
for (const p of selected) {
const position = new Vector3(), q = new Quaternion(), scale = new Vector3();
delta.clone().multiply(matrix(p)).decompose(position, q, scale);
assert.ok(scale.toArray().every(v => Math.abs(v - 1) < 1e-8));
p.position = clean(position.toArray()); p.quaternion = clean(q.normalize().toArray());
}
// Mirror the previously revised left-leg approach as a starting preference only.
// The optimizer checks the actual right GLBs and all previously installed parts.
const leftPart = raw.parts.find(p => p.id === raw.steps[o.n - 1].parts[0]);
const offset = [...leftPart.installOffset]; offset[2] *= -1;
selected.forEach(p => { p.installOffset = /螺钉/.test(o.label) ? screwOffset(p) : offset; });
const step = { id: `right-2-${o.n}`, label: `2-${o.n} · ${o.label}`, parts: selected.map(p => p.id) };
rightParts.push(...selected); rightSteps.push(step);
records.push({ code: `2-${o.n}`, files: selected.map(p => p.file), ids: step.parts,
placement: '本次右腿编号总装矩阵', displacementMm: distance(o, g) * 1000,
previousPositions: g.parts.map(p => p.position), positions: selected.map(p => p.position) });
notes.push({ label: step.label, reason: /螺钉/.test(o.label)
? '沿螺丝自身轴线进入,保留已有工具动画'
: '采用本次右腿总装位置;以左腿修订方向的镜像作为轴向优化初始值' });
}
assert.equal(rightParts.length, 72);
// Trunk files encode order, not instance placement. Reuse original whole-robot poses.
// Repeated fasteners moved into the numbered legs need NEW instances here, with their
// original hip locations; reuse their unchanged GLB rather than moving the leg screw.
const trunkMap = new Map([
[1,[14]], [2,[17,18,19]], [3,[36]], [4,[37]], [5,[20,21,22]], [6,[39]], [7,[40]],
[8,[1,2,3,4,5]], [9,[6,7,8,9,10]], [10,[283]],
[11,[241]], [12,[287]], [13,[288]], [14,[289]], [15,[290]], [16,[291]],
[17,[284]], [18,[285]], [19,[282]], [20,[286]], [21,[292]], [22,[114]],
[23,[121]], [24,[122]], [25,[123]], [26,[124]], [27,[125]], [28,[126]],
[29,[119]], [30,[120]], [31,[113]], [32,[117]], [33,[118]],
[34,[13]], [35,[12]],
// 3-36 / 3-37 intentionally omitted: user confirmed skipping these two unknown poses.
[38,[43]], [39,[24]], [40,[44]], [41,[45]], [42,[46]],
[43,[15]], [44,[16]], [45,[41]], [46,[35]], [47,[38]],
]);
const expectedLabels = new Map([...trunkMap].map(([n, ids]) => [n,
[2,5].includes(n) ? '0914舵机装配' : [8,9].includes(n) ? 'w_61702-2rs1'
: byId.get(id(ids[0])).file.replace(/(?:\.\d+)?\.glb$/, '')]));
const trunkFiles = readdirSync(trunkInput).filter(f => /\.step$/i.test(f));
assert.equal(trunkFiles.length, 47);
const trunkParts = [], trunkSteps = [];
const bodyPreferred = new Map([
[1,[-1,0,0]], [2,[-1,0,0]], [5,[-1,0,0]],
[8,[1,0,0]], [9,[1,0,0]], [10,[-1,0,0]], [22,[-1,0,0]],
[34,[0,-1,0]], [35,[0,-1,0]], [38,[0,1,0]], [43,[0,0,1]], [44,[0,0,-1]],
]);
for (const [n, ids] of trunkMap) {
const label = expectedLabels.get(n), source = `3-${n}${label}.step`;
assert.ok(trunkFiles.includes(source), `Missing numbered source: ${source}`);
const selected = ids.map((num, i) => ({ ...structuredClone(byId.get(id(num))), id: `trunk-3-${n}-part-${i+1}` }));
const screw = selected.every(p => /螺钉/.test(p.file));
assert.ok(screw || bodyPreferred.has(n));
for (const p of selected) p.installOffset = screw ? screwOffset(p)
: new Vector3(...bodyPreferred.get(n)).multiplyScalar(0.055).toArray();
const step = { id: `trunk-3-${n}`, label: `3-${n} · ${label}`, parts: selected.map(p => p.id) };
trunkParts.push(...selected); trunkSteps.push(step);
records.push({ code: `3-${n}`, source, files: selected.map(p => p.file), ids: step.parts,
originalIds: ids.map(id), placement: '原整机对应部件/配套孔位;重复同规格件按组件分组顺序', positions: selected.map(p => p.position) });
notes.push({ label: step.label, reason: screw ? '原整机孔位,沿螺丝自身轴线进入;同规格紧固件复用 GLB、实例独立'
: '保持原整机最终位置;按前面已经安装的左右腿与躯干零件优化进入方向' });
}
assert.equal(trunkSteps.length, 45); assert.equal(trunkParts.length, 57);
const parts = [...raw.parts, ...rightParts, ...trunkParts];
const steps = [...raw.steps, ...rightSteps, ...trunkSteps];
const files = new Set([...parts.map(p => p.file), ...raw.tools.map(t => t.file)]);
const manifest = { ...raw, title: 'Microduck · 左腿、右腿、躯干编号装配(149步)',
files: original.files.filter(f => files.has(f.path)), parts, steps };
assert.equal(steps.length, 149); assert.equal(parts.length, 201);
assert.equal(new Set(parts.map(p => p.id)).size, parts.length);
validatePackage(manifest, 'assembly', 'http://localhost:8090/manifest.json');
mkdirSync(preview, { recursive: true });
for (const f of manifest.files) {
const bytes = readFileSync(join(assets, f.path));
assert.equal(bytes.length, f.bytes);
assert.equal(createHash('sha256').update(bytes).digest('hex'), f.sha256);
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
copyFileSync(join(assets, f.path), join(preview, f.path), constants.COPYFILE_FICLONE);
}
const save = (name, data) => writeFileSync(join(preview, name), JSON.stringify(data, null, 2)+'\n');
save('input.json', manifest);
save('input.notes.json', { steps: notes });
save('mapping.json', { sources: { leftSource, rightInput, trunkInput }, steps: records,
skipped: ['3-36', '3-37'], skipReason: '无唯一安装位置;用户确认先跳过,保留其他编号' });
console.log(JSON.stringify({ preview, steps: steps.length, parts: parts.length, files: files.size,
rightChangedPositions: records.filter(r => r.displacementMm > .1).map(r => [r.code,r.displacementMm]), skipped:['3-36','3-37'] }, null, 2));
+64
View File
@@ -0,0 +1,64 @@
import { cpSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { resolve, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { expectedController } from '../sandbox/src/game/package-config.js';
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
const ROOT = fileURLToPath(new URL('..', import.meta.url));
const OUT = join(ROOT, 'deliverables/experience-packages');
mkdirSync(OUT, { recursive: true });
const json = (file, data) => writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]);
const filesFor = (dir) => walk(dir).filter((p) => !p.endsWith('.DS_Store')).sort().map((p) => {
const bytes = readFileSync(p);
return { path: relative(dir, p), bytes: bytes.length, sha256: hash(bytes) };
});
function prepare(name) {
const dir = join(OUT, name);
rmSync(dir, { recursive: true, force: true });
mkdirSync(dir, { recursive: true });
return dir;
}
function finish(name, dir, manifest, readme) {
validatePackage(manifest, manifest.kind, `https://assets.example.com/${name}/manifest.json`);
json(join(dir, 'manifest.json'), manifest);
writeFileSync(join(dir, 'README.txt'), readme);
const zip = join(OUT, `${name}.zip`);
rmSync(zip, { force: true });
execFileSync('zip', ['-q', '-r', zip, '.'], { cwd: dir });
execFileSync('unzip', ['-tq', zip]);
console.log(`${name}.zip ${(readFileSync(zip).length / 1048576).toFixed(2)} MB SHA256 ${hash(readFileSync(zip))}`);
}
const assembly = prepare('microban-assembly');
mkdirSync(join(assembly, 'models'));
cpSync(join(ROOT, 'assets/models/microban-assembly.glb'), join(assembly, 'models/robot.glb'));
const glb = readFileSync(join(assembly, 'models/robot.glb'));
validateEmbeddedGlb(glb.buffer.slice(glb.byteOffset, glb.byteOffset + glb.byteLength));
finish('microban-assembly', assembly, {
schemaVersion: 1, kind: 'assembly', title: 'Microban', unit: 'meter',
displayQuaternion: [-Math.SQRT1_2, 0, 0, Math.SQRT1_2],
files: filesFor(assembly),
parts: [{ id: 'robot', file: 'models/robot.glb', position: [0, 0, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1] }],
steps: [],
}, `Microban 装配展示包\n\n上传整个 ZIP,由后端解压并保持目录结构。\n将解压后的 manifest.json HTTP(S) 地址写入项目 assemblyManifestUrl。不要返回 ZIP 下载地址。\nmodels/robot.glb 与用户提供的原始文件完全一致,保留原材质。\n当前包是完整模型预览,没有真实装配工序;不会凭空生成安装步骤。\n\n未来多零件:每个 GLB 列在 files 中;parts 中每个实例拥有唯一 id、file、parentId、position、quaternion、scale。\n位置是相对父节点的米制坐标;四元数顺序 x,y,z,w;默认父节点为总装根节点。\n同一 file 可被多个实例复用,例如螺丝;不要对每个 GLB 单独居中或归一化。\nsteps 依次给出 id、label、parts(本步新增零件 id)。必须覆盖全部零件,各安装一次,父零件先安装或同一步安装。\ninstallOffset 是每个零件开始安装时相对最终位置的偏移;前端平移到准确安装位置。\n这是预先编排的装配展示,不是 CAD 约束求解或自动识别装配关系。\n\n每个 GLB 必须自包含贴图和缓冲区;目前支持静态、未压缩 GLB 2.0。\n单个 GLB 最大 50 MB,全部资源总计最大 200 MB,零件实例最多 1000 个。此上限不是手机性能保证。\n包内附带的 SHA256/大小需要后端核验;上传资源目录保持不可变,每次更新使用新目录。\n`);
const walking = prepare('microduck-walking');
for (const name of ['robot', 'policies', 'assets']) cpSync(join(ROOT, 'sandbox/public', name), join(walking, name), { recursive: true });
for (const name of ['LICENSE', 'NOTICE', 'UPSTREAM.md']) cpSync(join(ROOT, 'sandbox', name), join(walking, name));
json(join(walking, 'controller.json'), expectedController());
finish('microduck-walking', walking, {
schemaVersion: 1, kind: 'walking', title: 'Microduck', robotId: 'microduck-alpha',
runtimeProfile: 'microduck-alpha-v1', controller: 'controller.json', autoWalk: false,
files: filesFor(walking),
}, `Microduck 行走演示资源包\n\n上传整个 ZIP,由后端解压并保持目录结构。\n将解压后的 manifest.json HTTP(S) 地址写入项目 walkingManifestUrl。不要返回 ZIP 下载地址。\n\n本包属于 Microduck,不能当作 Microban 的策略。仅用于验证现有 Microduck 运行器的动态资源加载。\n可临时挂到测试项目联调;正式发布时请绑定实际对应的机器人项目。\n包含原机器人网格、物理 XML、运动学 JSON、ONNX 策略、音效和原许可证。原资产未修改。\n不含 Python 训练环境、node_modules、页面脚本或 WASM。\n平台前端必须部署 npm run build:walking 生成的 /play/microduck/ 运行器;运行器是网站的一部分,不从 ZIP 执行代码。\n\n运行约定:microduck-alpha-v1,14 个动作、61 维观测、13 维指令、0.005 秒物理步长,每 4 步推理一次(50 Hz)。\ncontroller.json 固化了关节顺序、默认姿态和控制语义,前端会检查,不匹配会拒绝启动。\n替换 ONNX 需要相同机器人、动力学、关节顺序、观测和动作语义,并在算法端重新验证。\n不是任意机器人/任意 ONNX 的通用播放器;其他机器人要新增运行器适配。\n打开默认不自动行走,保留球、方向控制、暂停、重置及移动端性能策略。\n\n后端校验路径、资源完整性、大小、SHA256,并在隔离环境验证物理模型和策略。\n提供 JSON/XML/GLB/ONNX/音效的正确 Content-Type 和跨域读取配置;使用 HTTPS 与不可变版本路径。\n`);
json(join(OUT, 'backend-fields.example.json'), {
assemblyManifestUrl: '/deliverables/experience-packages/microban-assembly/manifest.json',
walkingManifestUrl: '/deliverables/experience-packages/microduck-walking/manifest.json',
});
console.log(`输出目录:${resolve(OUT)}`);
cpSync(join(ROOT, 'docs/experience-packages.txt'), join(OUT, '后端接入说明.txt'));
+222
View File
@@ -0,0 +1,222 @@
"""Prepare three upload folders from the supplied Sandbox snapshot and verified LFS blobs."""
import copy
import argparse
import hashlib
import json
from pathlib import Path
import shutil
import struct
import xml.etree.ElementTree as ET
import zipfile
REPO = Path(__file__).resolve().parents[1]
SOURCE = Path('/Users/jerry/Downloads/vibemakersandbox')
PUBLIC = SOURCE / 'app/public'
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--out', type=Path, default=Path('/Users/jerry/Downloads/三个机器人-当前上传'))
parser.add_argument('--resume', action='store_true')
args = parser.parse_args()
OUT = args.out
PREVIOUS = Path('/Users/jerry/Downloads/机器人后台上传测试-20261029')
LATEST_DUCK = Path('/Users/jerry/Downloads/小鸭子-双腿及躯干-当前上传/小鸭子-双腿及躯干-149步装配.json')
LFS_INDEX = Path('/tmp/make-latest-lfs.json')
LFS = {r['path']: r for r in json.loads(LFS_INDEX.read_text())} if LFS_INDEX.exists() else {}
VERIFIED = Path('/Users/jerry/Downloads/三个机器人-最新上传资料-20261029')
VERIFIED_INDEX = VERIFIED / '文件来源与SHA256.json'
VERIFIED_FILES = {r['source']: VERIFIED / r['file'] for r in json.loads(VERIFIED_INDEX.read_text())} if VERIFIED_INDEX.exists() else {}
PROVENANCE = []
def sha(data):
return hashlib.sha256(data).hexdigest()
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
def copy_file(source, dest):
data = source.read_bytes()
if data.startswith(b'version https://git-lfs.github.com/spec/v1'):
pointer = dict(line.split(' ', 1) for line in data.decode().strip().splitlines())
expected_sha = pointer['oid'].removeprefix('sha256:')
expected_size = int(pointer['size'])
key = source.relative_to(PUBLIC).as_posix()
local = Path(LFS[key]['local']) if key in LFS else VERIFIED_FILES.get(str(source))
if local is None or not local.is_file():
local = VERIFIED_FILES.get(str(source))
assert local and local.is_file(), f'Missing real Git LFS resource: {key}'
data = local.read_bytes()
assert len(data) == expected_size and sha(data) == expected_sha, key
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(data)
assert sha(dest.read_bytes()) == sha(data)
PROVENANCE.append({'file': dest.relative_to(OUT).as_posix(), 'source': str(source),
'bytes': len(data), 'sha256': sha(data)})
def copy_tree(source, dest):
for p in sorted(source.rglob('*')):
if p.is_file() and not any(s.startswith('.') for s in p.relative_to(source).parts):
copy_file(p, dest / p.relative_to(source))
def inventory(folder):
return [{'path': p.relative_to(folder).as_posix(), 'bytes': p.stat().st_size,
'sha256': sha(p.read_bytes())} for p in sorted(folder.rglob('*')) if p.is_file()]
def validate_motion(folder, entries):
def require(name):
p = folder / name
assert p.resolve().is_relative_to(folder.resolve()), name
assert p.is_file(), name
return p
configs = []
for entry in entries:
config_path = require(entry)
d = json.loads(config_path.read_text())
base = config_path.parent
paths = [d['model']] + [a['path'] for a in d['assets']]
paths += [a['path'] for a in d['render'].get('body_visuals', [])]
paths += [s['controller']['policy'] for s in d['skills']
if s['controller']['type'] == 'onnx' and s.get('available', True)]
for s in d['skills']:
if not s.get('reference'):
continue
spec = json.loads((base / s['reference']).read_text())
blob = (base / spec['data']).read_bytes()
assert len(blob) == spec['frames'] * len(spec['joint_names']) * 2 * 4
assert spec['joint_names'] == d['joints']['groups'][s['owns']]
assert abs(spec['step_dt'] - d['sim']['timestep'] * d['sim']['decimation']) < 1e-9
paths += [s['reference'], spec['data']]
for name in paths:
require((base / name).relative_to(folder).as_posix())
xml_path = base / d['model']
xml = ET.parse(xml_path).getroot()
compiler = xml.find('compiler')
for elem in xml.iter():
file = elem.get('file')
if not file:
continue
prefix = ''
if compiler is not None:
prefix = compiler.get('meshdir' if elem.tag == 'mesh' else 'texturedir', '') if elem.tag in ('mesh', 'texture') else ''
# The original Microduck adapter mounts meshes/<name> as assets/<name>
# in MuJoCo VFS (runtime.js), without changing the source MJCF.
if d['adapter'] == 'microduck' and elem.tag == 'mesh' and prefix == 'assets':
prefix = 'meshes'
require((xml_path.parent / prefix / file).relative_to(folder).as_posix())
configs.append({'entry': entry, 'id': d['id'], 'skills': [s['id'] for s in d['skills']], 'resourceReferences': len(paths)})
for name in ('source-manifest.json', 'visual-source-manifest.json'):
p = folder / name
if p.exists():
d = json.loads(p.read_text())
for record in d['files'] + d.get('additionalNotices', []):
assert sha(require(record['file']).read_bytes()) == record['sha256'], record['file']
for record in inventory(folder):
p = folder / record['path']
b = p.read_bytes()
assert not b.startswith(b'version https://git-lfs.github.com/spec/v1'), p
if p.suffix.lower() == '.glb':
magic, version, size, chunk, typ = struct.unpack_from('<5I', b)
assert (magic, version, size, typ) == (0x46546c67, 2, len(b), 0x4e4f534a), p
doc = json.loads(b[20:20+chunk])
assert all(not a.get('uri') or a['uri'].startswith('data:') for a in doc.get('buffers', []) + doc.get('images', [])), p
return configs
resume = args.resume
assert not resume or not (OUT / '整理结果.json').exists(), 'Completed delivery must not be overwritten'
OUT.mkdir(exist_ok=resume) # Resume only an unfinished delivery created by this script.
duck = OUT / '01-小鸭子-Microduck'
ban = OUT / '02-双足机器人-Microban'
rp1 = OUT / '03-双足机器人-RP1'
for folder in (duck, ban, rp1):
folder.mkdir(exist_ok=resume)
# Preserve previously supplied display/assembly assets independently of simulation assets.
copy_tree(PREVIOUS / '01-Microduck小鸭子/01-整机模型', duck / '01-整机模型')
duck_assembly = Path('/Users/jerry/Downloads/小鸭子-扳手装配')
copy_tree(duck_assembly / '零件模型', duck / '02-零件模型')
copy_file(LATEST_DUCK, duck / '03-拼装步骤' / LATEST_DUCK.name)
latest_duck = json.loads(LATEST_DUCK.read_text())
assert len(latest_duck['steps']) == 149 and len(latest_duck['parts']) == 201
assert not {'trunk-3-36', 'trunk-3-37'} & {s['id'] for s in latest_duck['steps']}
copy_file(REPO / 'deliverables/experience-packages/microduck-numbered-body/validation.json', duck / '99-来源与核对/149步装配校验.json')
copy_file(REPO / 'deliverables/experience-packages/microduck-numbered-body/axis-review.json', duck / '99-来源与核对/149步轴向记录.json')
assert json.loads((duck / '99-来源与核对/149步装配校验.json').read_text())['sha256'] == sha(LATEST_DUCK.read_bytes())
for name in ('01-整机模型', '02-零件模型', '03-拼装步骤'):
copy_tree(PREVIOUS / '02-Microban双足机器人' / name, ban / name)
duck_motion = duck / '04-机器人运动演示'
for name in ('robot', 'policies', 'assets', 'worlds', 'licenses'):
copy_tree(PUBLIC / name, duck_motion / name)
# One root robot.json for admin discovery. Only path strings are rebased.
# Keep roller configuration under a distinct name; runtime adapter support is documented.
for source_name, target in [('microduck-legs', 'robot.json'), ('microduck-rollers', 'variants/rollers.json')]:
src = PUBLIC / 'robots' / source_name / 'robot.json'
d = json.loads(src.read_text())
original = copy.deepcopy(d)
prefix = '' if target == 'robot.json' else '../'
d['model'] = prefix + d['model'].removeprefix('../../')
for skill in d['skills']:
if skill['controller'].get('policy'):
skill['controller']['policy'] = prefix + skill['controller']['policy'].removeprefix('../../')
write_json(duck_motion / target, d)
copy_file(src, duck / f'99-来源与核对/原配置/{source_name}.json')
check = copy.deepcopy(d)
check['model'] = original['model']
for s, old in zip(check['skills'], original['skills']):
if old['controller'].get('policy'):
s['controller']['policy'] = old['controller']['policy']
assert check == original, 'Only resource path rebasing is allowed'
for name, folder in [('microban', ban), ('rp1', rp1)]:
motion = folder / '04-机器人运动演示'
copy_tree(PUBLIC / 'robots' / name, motion)
copy_tree(PUBLIC / 'worlds', motion / 'worlds')
copy_file(SOURCE / f'docs/robots/{name}.md', folder / f'99-来源与核对/{name}-原项目说明.md')
for folder in (duck, ban, rp1):
copy_file(SOURCE / 'README.md', folder / '99-来源与核对/Sandbox-README.md')
copy_file(SOURCE / 'LICENSE', folder / '99-来源与核对/Sandbox-代码LICENSE')
copy_file(REPO / 'sandbox/UPSTREAM.md', duck / '99-来源与核对/小鸭子-已有来源说明.md')
copy_file(REPO / 'sandbox/NOTICE', duck / '99-来源与核对/小鸭子-已有NOTICE')
common = '''\n运动上传:选择整个“04-机器人运动演示”目录;如果后台是 ZIP 入口,选择同级“04-机器人运动演示.zip”。二选一,不要两份同时上传。\n资源清单根目录应直接出现 robot.json,不能额外套一层机器人文件夹。保留目录和文件名。\n99-来源与核对只供开发者核对,不上传为装配步骤/运动资源。\n\n本批仅整理文件,未修改前台或后台。最新 Sandbox 与社区当前播放器的支持范围不同;文件完整不等于已完成前台运行验证。先上传测试项目,播放器适配完成后再验证动作。\n'''
(duck / '00-上传说明.txt').write_text('''Microduck 小鸭子\n\n1. 整机模型(可选):01-整机模型/Microduck-整机.glb。\n 这是上轮由运动网格、运动学姿态及原 classic 配色生成的展示版,原样保留;不是本次重新生成的 GLB,也不是下方用户零件的合并导出。\n2. 零件模型:选择整个 02-零件模型(292 个原零件 + 1 个内六角扳手)。\n3. 拼装步骤:只选 03-拼装步骤/小鸭子-双腿及躯干-149步装配.json。\n 这是本次最新修订版:左腿 52 步 → 右腿 52 步 → 躯干 45 步,共 149 步、201 个零件实例;按确认跳过 3-36、3-37,后续编号不变。\n 本次编号范围不含头部/颈部,装配整体视图只展示双腿与躯干;整机模型与运动包仍是完整小鸭子。\n 已匹配现有 GLB,保留扳手动画,并执行轴向与进入距离优化。仍有部分干涉,不能视为全程无穿模认证。\n 02 目录保留完整 292 个原零件及扳手,149 步引用其中 187 个零件 GLB 加 1 个工具;同规格螺丝可复用文件形成独立实例。\n4. 机器人运动演示:选择 04 目录或同级 ZIP。\n\n新版运动包:9 个 ONNX,含行走、坐起/站起、翻滚、左右踢球、俯身拾取、恢复站立、轮滑、轮滑蹲伏;同时保留两套物理配置、运动映射、道具与声音素材。\n主配置 robot.json 对应腿式,轮滑配置 variants/rollers.json。为适配上传入口,仅修改两份配置中的资源相对路径;物理参数、策略和模型字节未改。\n\n兼容状态:当前社区仍是旧 microduck-alpha-v1 运行器。新版 microduck adapter、双模式和轮滑不能只换 ZIP 就运行;需同步新版适配器,并将其固定的模型/策略/素材请求改成使用后台返回的文件 URL。variants/rollers.json 是本包的轮滑入口;此路径安排已在开发说明记录。\n缺足球模型文件不代表漏传:原工程的足球由运行器创建,踢球策略已包含。\n''' + common)
(ban / '00-上传说明.txt').write_text('''Microban 双足机器人\n\n1. 整机模型:01-整机模型/机器人.glb(用户原文件)。\n2. 零件模型:选择整个 02-零件模型,保留里面的 parts/,275 个 GLB。不要只选内层 parts,因为步骤引用带 parts/ 前缀。\n3. 拼装步骤:03-拼装步骤/Microban-拼装步骤.json(此前的全机装配流程)。\n4. 机器人运动演示:选择 04 目录或同级 ZIP。\n\n新版运动:1 个行走 ONNX + 配置里的头部摆动;25 个物理网格、20 个 body_visuals GLB 外观。无踢球、无轮滑,不要求上传足球。\n运动外观来自最新 Sandbox 的 visuals/;它与 01/02 的用户整机/装配 GLB 是两套资料,均按来源原样保存。\n\n兼容状态:当前社区需要同步新版 SchemaValidator、BodyVisuals 加载/资源 URL 解析及新字段支持。否则旧播放器可能报配置不支持或不能显示新外观。\n''' + common)
(rp1 / '00-上传说明.txt').write_text('''RP1 双足机器人\n\n本次可上传:04-机器人运动演示 目录或同级 ZIP。\n最新源代码没有可用于社区整机上传的完整 GLB、独立装配 GLB 或安装步骤 JSON,所以没有伪造 01/02/03;后台这些项留空。STL 是运动物理模型依赖,不要上传到“零件 GLB”字段。\n\n新版运动:model.xml + 25 个 STL + 3 个 ONNX(walk/dance/wave)。\n舞蹈和挥手还分别依赖 motions/*.json 与对应的 *.f32 参考动作数据,不能漏传。\n舞蹈配置 duration=10 秒;虽然参考数据更长,本包沿用原工程已启用的 10 秒片段,不自行扩大播放范围。挥手为 4.36 秒。\n没有足球或踢球,不要求也不附加踢球策略。\n\n兼容状态:当前社区需要新版历史观测、episodic 动作、JointMotionReference、动作切换和按关节 PD/力矩限制支持。旧播放器不能只靠上传 ZIP 播放这些功能。模型/策略/动作数据均未重训练、修改或重新导出。\n''' + common)
summary = []
for folder, entries in [(duck, ['robot.json', 'variants/rollers.json']), (ban, ['robot.json']), (rp1, ['robot.json'])]:
motion = folder / '04-机器人运动演示'
configs = validate_motion(motion, entries)
files = inventory(motion)
archive = folder / '04-机器人运动演示.zip'
with zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as z:
for f in files:
z.write(motion / f['path'], f['path'])
with zipfile.ZipFile(archive) as z:
assert z.testzip() is None
assert sorted(z.namelist()) == sorted(f['path'] for f in files)
for f in files:
assert sha(z.read(f['path'])) == f['sha256']
record = {'folder': folder.name, 'configs': configs, 'files': len(files),
'uncompressedBytes': sum(f['bytes'] for f in files), 'zipBytes': archive.stat().st_size}
write_json(folder / '99-来源与核对/运动文件校验.json', {
'sourceDirectory': str(SOURCE), 'checked': ['resource paths', 'MJCF mesh dependencies', 'source hashes',
'motion reference dimensions and joint order', 'embedded GLB', 'no Git LFS pointers', 'ZIP CRC and SHA256'],
'browserPlaybackTested': False, 'configs': configs, 'files': files})
summary.append(record)
print(json.dumps(record, ensure_ascii=False), flush=True)
write_json(OUT / '文件来源与SHA256.json', PROVENANCE)
write_json(OUT / '整理结果.json', summary)
(OUT / '00-先看这里.txt').write_text('''三个机器人 · 当前上传资料 · 2026-10-29\n\n01-小鸭子-Microduck:整机展示版、292 个用户零件和扳手、最新双腿及躯干 149 步装配(跳过 3-36、3-37)、新版双模式运动包。\n02-双足机器人-Microban:原整机、275 个零件、全机装配 JSON、新版带 GLB 外观的行走包。\n03-双足机器人-RP1:新版行走/舞蹈/挥手运动包;源工程没有整机 GLB 和装配步骤,这两项留空。\n\n本目录为这次重新整理的当前上传资料。小鸭子 03 目录只放最新 149 步 JSON,不包含旧 91 步或 52 步文件,避免选错。\n每个机器人分别上传到对应项目,不要混传。具体选哪个文件/目录,阅读每个目录的 00-上传说明.txt。\n运动文件夹与 ZIP 内容相同,后台选一种入口即可。所有 Git LFS 占位文件已补齐成真实资源并核对哈希。\n\n本次整理了最新完整资源,但没有更新社区播放器,也未完成三套新版包的浏览器运行联调。小鸭子双模式、Microban 的 body_visuals、RP1 的动作参考和历史观测需要前台同步适配;不要把“资源校验通过”理解为“上传后即可正常播放”。\n原 GLB/ONNX/MJCF/STL/F32 字节按来源保留,未统一染色、重写材质或重新训练。小鸭子 robot.json 仅作上传根目录路径整理,原配置另存以便核对。\n文件来源与SHA256.json、整理结果.json 供核对,不上传到资源字段。\n''')
(OUT / '前台适配交接.txt').write_text('''最新运动包与当前社区播放器的对接点\n\n源代码:/Users/jerry/Downloads/vibemakersandbox/app/src\n社区项目:/Users/jerry/vibemake-site\n1. 保持按接口资源清单读取,不按项目名或本地 demo 路径代替。每个运动目录仅有一个 basename=robot.json,作为主入口。\n2. Microduck:主入口 robot.json,轮滑入口 variants/rollers.json。源工程 app/public/robots/microduck-legs/robot.json 和 microduck-rollers/robot.json 的 model、controller.policy 相对路径已重新定位,其余字段不变。适配器目前固定请求这两个旧路径,需要改为上述入口和后台资源映射;仅更换文件名不能兼容旧运行器。\n3. Microduck 还需将 ./robot/mjlab、./policies、./assets 的固定请求映射到本包根目录;腿式和轮滑分别使用各自 MJCF/kinematics,勿让多个 primary 同时控制同一关节。\n4. Microban:递归收集 render.body_visuals[].path;调用新版 BodyVisuals,保留 position/quaternion 和原 GLB 材质。\n5. RP1:完整支持 observations.history/term-major、逐关节 actuation、episodic skills、参考动作和 blend/reset;收集 skills[].controller.policy、skills[].reference,以及 motions JSON 的 data 路径。data 相对于 robot.json 包根目录,不能再拼一层 motions/。\n6. 使用最新 robot/world schema、动作编排和依赖解析,动作按钮按 skills/availability 生成;无踢球不创建足球。头部摆动来自 oscillator 配置,无需 ONNX。\n7. worlds/arena/world.json 与 worlds/flat/world.json 已随每个包提供,保持原工程按机器人尺寸缩放边界的规则。\n8. 保留手机/低性能设备的按需渲染、后台暂停、像素比预算、资源释放,切换动作后检查暂停/重置和默认不自动行走。\n\n已做资源/路径/哈希检查;未把未完成的运行联调标为通过。来源说明保留在每个包的 SOURCE.md/LICENSES/ 和 99-来源与核对。\n''')
print('COMPLETE:', OUT)
+59
View File
@@ -0,0 +1,59 @@
// Add declarative tightening instructions to the existing, aligned duck package.
// This one-off asset preparation knows the supplied fastener names; the player does not.
import { readFileSync, writeFileSync, mkdirSync, copyFileSync, constants } from 'node:fs';
import { join } from 'node:path';
import { createHash } from 'node:crypto';
import assert from 'node:assert/strict';
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
const root = new URL('..', import.meta.url).pathname;
const source = join(root, 'deliverables/experience-packages/microduck-parts-assembly');
const out = join(root, 'deliverables/experience-packages/microduck-screw-assembly');
const upload = '/Users/jerry/Downloads/小鸭子-扳手装配';
const toolSource = '/Users/jerry/Downloads/内六角扳手.glb';
const toolName = '内六角扳手.glb';
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
const original = JSON.parse(readFileSync(join(source, 'manifest.json'), 'utf8'));
const manifest = structuredClone(original);
const toolBytes = readFileSync(toolSource);
validateEmbeddedGlb(toolBytes.buffer.slice(toolBytes.byteOffset, toolBytes.byteOffset + toolBytes.length));
manifest.title = 'Microduck · 内六角扳手装配';
manifest.files.push({ path: toolName, bytes: toolBytes.length, sha256: hash(toolBytes) });
manifest.tools = [{ id: 'hex-key-1-5', file: toolName,
// Measured long-end cap center including the GLB node translation (meters).
tipPosition: [0.005250010406598449, -0.000000003587008764, 0.03276707977056503] }];
let screwCount = 0;
for (const part of manifest.parts) {
if (!/^标准杯头内六角螺钉_M2x(?:4|5|6|8)(?:\.\d+)?\.glb$/.test(part.file)) continue;
part.installation = {
type: 'screw', toolId: 'hex-key-1-5',
axis: [0, 0, -1], socketPosition: [0, 0, -0.0009],
// Hex key flats rotated 30° to match this screw's six-sided socket.
toolQuaternion: [0, 0, Math.sin(Math.PI / 12), Math.cos(Math.PI / 12)],
direction: 'clockwise', turns: 3, travel: 0.0012,
approachDuration: 0.45, engageDuration: 0.3, tightenDuration: 2.4,
retractDuration: 0.35, toolClearance: 0.012,
};
screwCount++;
}
assert.equal(screwCount, 144);
assert.deepEqual(manifest.parts.map(({ installation, ...part }) => part), original.parts);
assert.deepEqual(manifest.steps, original.steps);
validatePackage(manifest, 'assembly', 'http://localhost:8090/manifest.json');
for (const dir of [out, join(upload, '零件模型')]) mkdirSync(dir, { recursive: true });
for (const file of manifest.files) {
const sourceFile = file.path === toolName ? toolSource : join(source, file.path);
assert.equal(hash(readFileSync(sourceFile)), file.sha256, `原文件校验失败:${file.path}`);
for (const dir of [out, join(upload, '零件模型')]) {
const destination = join(dir, file.path);
copyFileSync(sourceFile, destination, constants.COPYFILE_FICLONE);
assert.equal(hash(readFileSync(destination)), file.sha256, `复制校验失败:${file.path}`);
}
}
const json = JSON.stringify(manifest, null, 2) + '\n';
writeFileSync(join(out, 'manifest.json'), json);
writeFileSync(join(upload, '鸭子-拼装步骤-带扳手.json'), json);
copyFileSync(join(root, 'docs/assembly-screw-animation.md'), join(upload, '螺丝动画配置说明.md'));
writeFileSync(join(upload, '上传说明.txt'), `小鸭子 · 内六角扳手装配\n\n1. 后台“零件模型”选择本文件夹下的“零件模型”整个目录(293 个 GLB)。\n 包含原来的 292 个零件和 1 个扳手。不要只传扳手覆盖整批绑定。\n2. “拼装步骤”上传“鸭子-拼装步骤-带扳手.json”。\n3. 社区使用本次更新后的前端,点击 AI 装配 → 逐步装配 → 播放装配。\n 扳手只在螺丝安装时出现;查看整体不显示工具。\n\n所有 GLB 均原样复制,材质、颜色、几何体没有重写。\n原 292 个零件的最终位置、方向以及 91 个步骤不变。\n144 颗标准杯头内六角螺钉按 JSON 逐颗拧紧,其余零件保持平移安装。\n每颗默认顺时针 3 圈、拧入 1.2 mm、旋转 2.4 秒,可在 JSON 的 installation 中修改。\n顺时针指从工具一侧看向螺丝孔。模型局部 -Z 是这批螺丝的插入方向。\n这是装配展示动画,未做工具碰撞、实际紧固工艺或扭矩验证。\n\n详细配置:项目 docs/assembly-screw-animation.md\n本地效果:http://localhost:8090/examples/screw-assembly.html\n`);
console.log(JSON.stringify({ out, upload, screws: screwCount, parts: manifest.parts.length,
files: manifest.files.length, steps: manifest.steps.length, toolBytes: toolBytes.length }, null, 2));
+120
View File
@@ -0,0 +1,120 @@
// Prepare independent folders for the current admin folder-upload API.
// Source assets are copied byte-for-byte; the duck whole-model export is explicit.
import { cpSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { NodeIO, Document } from '@gltf-transform/core';
import { BufferGeometry, BufferAttribute, Quaternion, Vector3 } from '../sandbox/node_modules/three/build/three.module.js';
import { toCreasedNormals } from '../sandbox/node_modules/three/examples/jsm/utils/BufferGeometryUtils.js';
import { VARIANTS, DEFAULT_VARIANT, materialHookFor } from '../sandbox/src/game/variants.js';
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
import { validateController } from '../sandbox/src/game/package-config.js';
import { resourceIndex, validateRobotResources } from '../js/project-resources.js';
const root = fileURLToPath(new URL('..', import.meta.url));
const out = resolve(process.argv[2] || '/Users/jerry/Downloads/机器人后台上传测试-20261029');
const banSource = '/Users/jerry/Downloads/Microban-后台上传资料-20261028';
const duckSource = join(root, 'deliverables/experience-packages/microduck-walking');
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
const json = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
const readJson = (path) => JSON.parse(readFileSync(path));
const walk = (dir) => readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith('.')).flatMap((e) => e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]).sort();
const inventory = (dir) => walk(dir).map((path) => { const bytes = readFileSync(path); return { path: relative(dir, path), bytes: bytes.length, sha256: hash(bytes) }; });
const copy = (src, dest) => cpSync(src, dest, { recursive: true, filter: (path) => !path.endsWith('.DS_Store') });
const verify = (dir, files) => {
for (const f of files) {
const bytes = readFileSync(join(dir, f.path));
if (bytes.length !== f.bytes || hash(bytes) !== f.sha256) throw new Error(`Integrity mismatch: ${f.path}`);
}
};
// microduck.glb is a geometry library. Reconstruct the assembled view using the
// same kinematics, joint pose, normals and classic materials as the duck player.
async function exportDuckWhole(destination) {
const io = new NodeIO(), source = await io.read(join(duckSource, 'robot/mjlab/microduck.glb'));
const k = readJson(join(duckSource, 'robot/mjlab/kinematics.json'));
const controller = readJson(join(duckSource, 'controller.json'));
const defaults = new Map(controller.jointNames.map((name, i) => [name, controller.defaultPose[i]]));
const doc = new Document(), buffer = doc.createBuffer(), scene = doc.createScene('Microduck assembled');
doc.getRoot().setDefaultScene(scene);
const rootNode = doc.createNode('MJCF Z-up to glTF Y-up').setRotation([-Math.SQRT1_2, 0, 0, Math.SQRT1_2]);
scene.addChild(rootNode);
const geoms = new Map(), materialFor = materialHookFor(VARIANTS[DEFAULT_VARIANT]);
for (const node of source.getRoot().listNodes()) {
if (!node.getMesh()) continue;
const original = node.getMesh().listPrimitives()[0];
const geometry = new BufferGeometry();
geometry.setAttribute('position', new BufferAttribute(original.getAttribute('POSITION').getArray().slice(), 3));
if (original.getIndices()) geometry.setIndex(new BufferAttribute(original.getIndices().getArray().slice(), 1));
geometry.scale(1000, 1000, 1000);
const display = toCreasedNormals(geometry, Math.PI / 5); display.scale(1e-3, 1e-3, 1e-3);
const name = node.getExtras().meshFile || node.getName();
geoms.set(name, {
positions: doc.createAccessor().setType('VEC3').setArray(display.attributes.position.array).setBuffer(buffer),
normals: doc.createAccessor().setType('VEC3').setArray(display.attributes.normal.array).setBuffer(buffer),
});
display.dispose(); geometry.dispose();
}
const bodies = new Map(), materials = new Map(), meshes = new Map(), seen = new Set();
for (const b of k.bodies) {
const q = new Quaternion(b.quat[1], b.quat[2], b.quat[3], b.quat[0]);
if (b.joint && (!b.joint.type || b.joint.type === 'hinge') && defaults.has(b.joint.name)) {
q.multiply(new Quaternion().setFromAxisAngle(new Vector3(...b.joint.axis).normalize(), defaults.get(b.joint.name)));
}
bodies.set(b.name, doc.createNode(b.name).setTranslation(b.pos).setRotation(q.toArray()));
}
for (const b of k.bodies) {
const parent = bodies.get(b.name);
(bodies.get(b.parent) || rootNode).addChild(parent);
for (const geom of b.geoms) {
if ((geom.type && geom.type !== 'mesh') || !geom.mesh) continue;
const key = `${b.name}|${geom.mesh}|${geom.pos}|${geom.quat}`;
if (seen.has(key)) continue; seen.add(key);
const geometry = geoms.get(geom.mesh);
if (!geometry) throw new Error(`Missing duck geometry: ${geom.mesh}`);
const spec = materialFor(geom.mesh), matKey = JSON.stringify(spec);
if (!materials.has(matKey)) materials.set(matKey, doc.createMaterial().setBaseColorFactor([...spec.color, spec.opacity ?? 1]).setRoughnessFactor(spec.roughness ?? 0.5).setMetallicFactor(spec.metalness ?? 0));
const meshKey = geom.mesh + matKey;
if (!meshes.has(meshKey)) meshes.set(meshKey, doc.createMesh(geom.mesh).addPrimitive(doc.createPrimitive().setAttribute('POSITION', geometry.positions).setAttribute('NORMAL', geometry.normals).setMaterial(materials.get(matKey))));
const q = geom.quat || [1, 0, 0, 0];
parent.addChild(doc.createNode(geom.mesh).setMesh(meshes.get(meshKey)).setTranslation(geom.pos || [0, 0, 0]).setRotation([q[1], q[2], q[3], q[0]]));
}
}
const bytes = await io.writeBinary(doc);
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
writeFileSync(destination, bytes);
return { meshInstances: seen.size, materials: materials.size, bytes: bytes.length, sha256: hash(bytes), provenance: 'Derived from original kinematics + controller default pose + original classic material configuration; original motion assets unchanged.' };
}
mkdirSync(out); // Refuse to overwrite a previous delivery.
const duck = join(out, '01-Microduck小鸭子'), ban = join(out, '02-Microban双足机器人');
mkdirSync(duck); mkdirSync(ban);
const duckMotion = join(duck, '04-机器人运动演示');
copy(duckSource, duckMotion);
// README is not part of the signed manifest; replace outdated ZIP-only instructions.
writeFileSync(join(duckMotion, 'README.txt'), 'Microduck 原版运动资源。请在后台“机器人运动演示”选择本文件夹,保留所有相对路径。入口 manifest.json;控制配置 controller.json。无需重命名为 robot.json,也不要把内层 robot 文件夹单独上传。配套本站 microduck-alpha-v1 运行器。\n');
const duckManifest = readJson(join(duckMotion, 'manifest.json'));
validatePackage(duckManifest, 'walking', 'https://assets.example/manifest.json');
validateController(readJson(join(duckMotion, 'controller.json')));
verify(duckMotion, duckManifest.files);
mkdirSync(join(duck, '01-整机模型'));
const duckWhole = await exportDuckWhole(join(duck, '01-整机模型/Microduck-整机.glb'));
for (const name of ['01-整机模型', '02-零件模型', '03-拼装步骤']) copy(join(banSource, name), join(ban, name));
const banMotion = join(ban, '04-机器人运动演示');
copy(join(banSource, '05-运动文件明细'), banMotion);
const assembly = readJson(join(ban, '03-拼装步骤/Microban-拼装步骤.json'));
validatePackage(assembly, 'assembly', 'https://assets.example/steps.json');
verify(join(ban, '02-零件模型'), assembly.files);
verify(banMotion, inventory(join(banSource, '05-运动文件明细')));
if (hash(readFileSync(join(ban, '01-整机模型/机器人.glb'))) !== hash(readFileSync('/Users/jerry/Downloads/机器人.glb'))) throw new Error('Whole GLB differs from user original');
const banFiles = inventory(banMotion);
const packet = validateRobotResources(readJson(join(banMotion, 'robot.json')), 'robot.json', resourceIndex(banFiles.map((f) => ({ relativePath: f.path, sizeBytes: f.bytes, url: `https://assets.example/${f.path}` }))));
writeFileSync(join(duck, '00-上传说明.txt'), `Microduck 小鸭子 · 后台上传测试\n\n1. “整机模型” → 选择 01-整机模型/Microduck-整机.glb(可选,想测试详情整机展示时上传)。\n2. “零件模型”“拼装步骤” → 本次留空。现有小鸭子资料只有运动学结构,没有已确认的安装顺序与方向;不拿 Microban 零件或流程冒充。\n3. “机器人运动演示” → 选择整个 04-机器人运动演示 文件夹(本次运动测试必传,包含 ${inventory(duckMotion).length} 个文件)。\n\n选对文件夹后,后台清单应以 manifest.json、controller.json、robot/、policies/、assets/ 开头,不能多套一层 04-机器人运动演示/。不要只上传 robot/ 或某个 ONNX,不要压缩后传给“选择文件夹”。\n\n整机 GLB 是由原小鸭子网格、原运动学坐标、原默认姿态与原 classic 配色导出的展示模型。原 microduck.glb 本身只是零件网格库且没有内嵌材质,不能直接当整机。导出沿用小鸭子原场景的材质参数;原运动文件全部保留不变。\n\n运动入口使用原有 microduck-alpha-v1 运行器。该运行器当前启动会加载 7 个配套策略,包括左右踢球和恢复动作,所以本包保留全部;这是这套小鸭子实现的依赖,不是其他机器人的上传要求。前端保留足球与原版交互,打开默认暂停。\n\n测试:发布项目 → 打开详情 → 检查整机 → 行走演示 → 应有小鸭子和球 → 自动行走/方向控制/暂停/重置 → 关闭再打开应仍为暂停。手机竖屏再验一次。\n`);
writeFileSync(join(ban, '00-上传说明.txt'), `Microban 双足机器人 · 后台上传测试\n\n1. “整机模型” → 选择 01-整机模型/机器人.glb。\n2. “零件模型” → 选择整个 02-零件模型 文件夹(里面有 parts 子文件夹,共 ${assembly.files.length} 个 GLB)。不要选择内层 parts;步骤引用的是 parts/文件名.glb。\n3. “拼装步骤 / 高级导入 JSON” → 选择 03-拼装步骤/Microban-拼装步骤.json。\n4. “机器人运动演示” → 选择整个 04-机器人运动演示 文件夹(${banFiles.length} 个文件)。\n\n四个区域分别选择,不要把本机器人总文件夹一次性选成运动目录。第 4 步的后台清单应直接有 robot.json、model.xml、assets/、policies/walk.onnx。\n\n本轮测试完整上传以上四项;仅测试运动时只需第 4 项,整机/零件/装配不是运动的依赖。Microban 只需要配套的一份行走 ONNX,头部摆动是 robot.json 声明的叠加动作,不需要足球策略。\n\n整机和 275 个零件保持用户原 GLB 字节、材质和颜色。拼装 JSON 沿用此前按原位置整理的展示流程,安装方向是预编排的展示方向,并非已验证的实际机械安装工艺。运动模型来自另一套 MJCF/STL 仿真工程,配色由其物理模型定义,与整机 GLB 不同,不会用整机 GLB 自动替换仿真几何。\n\n测试:发布项目 → 查看整机 → AI 装配应有 275 个零件且可逐步安装 → 行走演示应有 Microban、无足球、可切换头部摆动 → 自动行走/方向控制/暂停/重置 → 关闭再打开仍暂停。\n`);
writeFileSync(join(out, '00-先看这里.txt'), `机器人后台上传测试 · 2026-10-29\n\n请建立或选择两个独立项目,分别使用下面两个文件夹。\n01-Microduck小鸭子:整机展示 + 原版运动演示,带球;本次没有装配步骤。\n02-Microban双足机器人:原材质整机 + 275 个原材质零件 + 拼装 JSON + 行走/头部动作,无足球。\n\n每个文件夹的 00-上传说明.txt 写清了后台每个区域要选哪个文件/文件夹。当前后台接口按文件夹逐文件上传,已经整理成可直接选择的文件夹,不需要你手工制作 ZIP。原有 ZIP 入口若仍使用,先压缩运动文件夹的“内容”,解压后入口应在根目录。\n\n两套前台统一使用小鸭子的深色背景、暖色网格、方向键、自动行走/继续/暂停/重置样式。外观风格属于前台运行器,上传包仍只提供模型/配置/策略。两套运行器兼容不同资料格式,统一样式不意味着它们的动作能力相同。\n\n后台完成绑定后,社区详情读取 modelGlbUrl、modelPartsFiles、assemblyJsonUrl、walkingResourcesFiles。不会按项目名字自动替换本地演示数据。缺少装配资源时隐藏装配按钮;缺少运动资源时隐藏运动按钮。\n\n前台需使用此次更新后的 8090 服务;线上需要部署新的前端构建。检查记录保存在每个文件夹的 99-核对记录.json,不需要上传该文件。\n`);
for (const [dir, details] of [[duck, { wholeExport: duckWhole, motionFiles: inventory(duckMotion).length, manifestFilesVerified: duckManifest.files.length, assemblyAvailable: false }], [ban, { originalWholeUnchanged: true, partFilesVerified: assembly.files.length, assemblySteps: assembly.steps.length, motionFiles: banFiles.length, requiredRuntimeResources: packet.resources.length, capabilities: packet.capabilities }]]) {
json(join(dir, '99-核对记录.json'), { generatedAt: new Date().toISOString(), ...details, files: inventory(dir) });
}
console.log(JSON.stringify({ output: out, duck: { whole: duckWhole, motionFiles: inventory(duckMotion).length }, microban: { parts: assembly.files.length, steps: assembly.steps.length, motionFiles: banFiles.length } }, null, 2));
+109
View File
@@ -0,0 +1,109 @@
// 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}));
+33
View File
@@ -0,0 +1,33 @@
// Compress the supplied part geometry; retain embedded image bytes and PBR values.
import fs from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import { draco } from '@gltf-transform/functions';
import draco3d from 'draco3dgltf';
const source='/Users/jerry/Downloads/开发提交/鸭子最新glb';
const target=new URL('../deliverables/current-robots/duck-parts/', import.meta.url).pathname;
await fs.mkdir(target,{recursive:true});
const io=new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({
'draco3d.encoder':await draco3d.createEncoderModule(), 'draco3d.decoder':await draco3d.createDecoderModule(),
});
const hash=b=>crypto.createHash('sha256').update(b).digest('hex');
function materials(doc){return doc.getRoot().listMaterials().map(m=>({
name:m.getName(),base:m.getBaseColorFactor(),metal:m.getMetallicFactor(),rough:m.getRoughnessFactor(),emission:m.getEmissiveFactor(),normal:m.getNormalScale(),occlusion:m.getOcclusionStrength(),alpha:m.getAlphaMode(),cutoff:m.getAlphaCutoff(),double:m.getDoubleSided(),
textures:['getBaseColorTexture','getNormalTexture','getOcclusionTexture','getEmissiveTexture','getMetallicRoughnessTexture'].map(fn=>m[fn]() ? hash(m[fn]().getImage()) : null)
}));}
const mapping=[];
for(const name of (await fs.readdir(source)).filter(n=>n.endsWith('.glb')).sort()){
const src=path.join(source,name), dst=path.join(target,name); const doc=await io.read(src);
const before=materials(doc), nodes=doc.getRoot().listNodes().filter(n=>n.getMesh());
assert.equal(nodes.length,1, name);
await doc.transform(draco({method:'edgebreaker',quantizePosition:16,quantizeNormal:12,quantizeTexcoord:14,encodeSpeed:5,decodeSpeed:5}));
await io.write(dst,doc);
const check=await io.read(dst);assert.deepEqual(materials(check),before,name+' materials');
const data=await fs.readFile(dst);
mapping.push({file:name,node:nodes[0].getName(),bytes:data.length,sha256:hash(data),sourceSha256:hash(await fs.readFile(src))});
}
await fs.writeFile(new URL('../deliverables/current-robots/duck-parts.json',import.meta.url),JSON.stringify(mapping,null,2));
console.log(JSON.stringify({parts:mapping.length,bytes:mapping.reduce((sum,x)=>sum+x.bytes,0),materials:'unchanged',textures:'byte-identical'}));
+22
View File
@@ -0,0 +1,22 @@
import fs from 'node:fs/promises';
import path from 'node:path';
const root = new URL('../deliverables/current-robots/',import.meta.url).pathname;
const uploads='/Users/jerry/Downloads/三个机器人-后台上传-20261030';
const names={microduck:'01-小鸭子-Microduck',microban:'02-人形机器人-Microban',rp1:'03-双足机器人-RP1'};
const projects={};
async function list(dir,base=dir){let rows=[];for(const e of await fs.readdir(dir,{withFileTypes:true})){
const file=path.join(dir,e.name);if(e.isDirectory())rows.push(...await list(file,base));else {const stat=await fs.stat(file);rows.push({relativePath:path.relative(base,file),url:'http://localhost:8090'+file.slice(root.indexOf('/deliverables'))+'?v='+stat.size+'-'+Math.floor(stat.mtimeMs),sizeBytes:stat.size});}}return rows;}
for(const [id,folder]of Object.entries(names)){
const target=path.join(root,id);await fs.mkdir(target,{recursive:true});
const whole=path.join(uploads,folder,'01-整机模型',(await fs.readdir(path.join(uploads,folder,'01-整机模型')))[0]);
try{await fs.symlink(whole,path.join(target,'whole.glb'));}catch(e){if(e.code!=='EEXIST')throw e;}
const wholeStat=await fs.stat(whole);
const p={name:id,modelGlbUrl:`/deliverables/current-robots/${id}/whole.glb?v=${wholeStat.size}-${Math.floor(wholeStat.mtimeMs)}`,walkingResourcesBaseUrl:`/deliverables/current-robots/${id}/motion/`,walkingResourcesFiles:await list(path.join(target,'motion'))};
if(id==='microduck'){
await fs.copyFile(path.join(uploads,folder,'03-拼装步骤/小鸭子-239步装配.json'),path.join(target,'assembly.json'));
p.assemblyJsonUrl=`/deliverables/current-robots/${id}/assembly.json`;
p.modelPartsFiles=await list(path.join(root,'duck-parts'));
}
projects[id]=p;
}
await fs.writeFile(path.join(root,'preview.json'),JSON.stringify(projects,null,2));console.log(Object.fromEntries(Object.entries(projects).map(([id,p])=>[id,p.walkingResourcesFiles.length])));
+155
View File
@@ -0,0 +1,155 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { resourceIndex, bindAssemblyFiles, loadProjectAssembly, loadProjectWalking, validateRobotResources, hasProjectWalking, assemblySource } from '../js/project-resources.js';
import { modelAssetUrl, modelAssetTarget } from '../js/model-assets.js';
const robot = JSON.parse(readFileSync(new URL('../docs/model-examples/microban.robot.json', import.meta.url)));
const filesFor = (prefix = '') => resourceIndex(['robot.json', robot.model, ...robot.assets.map((a) => a.path), 'policies/walk.onnx'].map((p) => ({ relativePath: prefix + p, sizeBytes: 100, url: 'https://cdn.example/' + prefix + p })));
test('duck folder uses exact API file URLs and rejects incomplete inventories before boot', async () => {
const paths = ['controller.json', 'robot/mjlab/robot_allcollisions.xml', 'robot/mjlab/kinematics.json', 'robot/mjlab/microduck.glb',
'policies/BEST_alpha_walking.onnx', 'policies/BEST_alpha_sitstand.onnx', 'policies/roulade.onnx', 'policies/ball_kick_left.onnx',
'policies/ball_kick_right.onnx', 'policies/alpha_ground_pick.onnx', 'policies/BEST_alpha_stand.onnx'];
const manifest = { schemaVersion: 1, kind: 'walking', runtimeProfile: 'microduck-alpha-v1', robotId: 'microduck-alpha', autoWalk: false,
controller: 'controller.json', files: paths.map((path) => ({ path, bytes: 100, sha256: 'a'.repeat(64) })) };
const project = { walkingResourcesFiles: [
{ relativePath: 'duck/manifest.json', sizeBytes: 123, url: 'https://cdn.example/manifest.json' },
...manifest.files.map((f, i) => ({ relativePath: 'duck/' + f.path, sizeBytes: f.bytes, url: `https://cdn.example/objects/${i}` })),
] };
const original = globalThis.fetch;
globalThis.fetch = async () => new Response(JSON.stringify(manifest));
try {
const result = await loadProjectWalking(project);
assert.equal(result.format, 'legacy');
assert.equal(result.resources[0].url, 'https://cdn.example/objects/0');
project.walkingResourcesFiles.pop();
await assert.rejects(loadProjectWalking(project), /缺少文件/);
} finally { globalThis.fetch = original; }
});
test('generic walking accepts one policy and a built-in head overlay without ball policies', () => {
const packet = validateRobotResources(robot, 'robot.json', filesFor());
assert.deepEqual(packet.capabilities.map((c) => c.skillId), ['walk', 'head']);
assert.equal(packet.resources.filter((f) => f.path.endsWith('.onnx')).length, 1);
assert.ok(!packet.resources.some((f) => /kick|ball/.test(f.path)));
});
test('nested Robot Package preserves paths and rejects missing required walking files', () => {
assert.equal(validateRobotResources(robot, 'robot/robot.json', filesFor('robot/')).entryPath, 'robot/robot.json');
const files = filesFor(); files.delete('policies/walk.onnx');
assert.throws(() => validateRobotResources(robot, 'robot.json', files), /walk.onnx/);
});
test('optional unsupported or incomplete actions do not block walking or leave stale controls', () => {
const config = structuredClone(robot);
config.skills.push({ id: 'missing', kind: 'episodic', controller: { type: 'onnx', policy: 'missing.onnx' } },
{ id: 'scripted', kind: 'episodic', controller: { type: 'python' } },
{ id: 'disabled', kind: 'episodic', available: false, controller: { type: 'onnx', policy: 'disabled.onnx' } });
config.input.bindings.push(...['missing', 'scripted', 'disabled'].map((id) => ({ action: `skill:${id}`, key: 'KeyT' })));
const packet = validateRobotResources(config, 'robot.json', filesFor());
assert.deepEqual(packet.config.skills.map((s) => s.id), ['walk', 'head']);
assert.deepEqual(packet.warnings.map((w) => w.skillId), ['missing', 'scripted']);
assert.ok(!packet.config.input.bindings.some((b) => /^skill:/.test(b.action)));
assert.equal(config.skills.length, 5); // Do not mutate the uploaded configuration.
});
test('RP1 episodic policies retain nested reference data and exact backend URLs', () => {
const config = JSON.parse(readFileSync(new URL('../sandbox/test/fixtures/rp1/robot.json', import.meta.url)));
const paths = new Set(['robot.json', config.model, ...config.assets.map((a) => a.path)]);
for (const skill of config.skills) {
paths.add(skill.controller.policy);
if (skill.reference) {
paths.add(skill.reference);
const ref = JSON.parse(readFileSync(new URL('../sandbox/test/fixtures/rp1/' + skill.reference, import.meta.url)));
paths.add(ref.data);
}
}
const files = resourceIndex([...paths].map((p, i) => ({ relativePath: 'rp1/' + p, sizeBytes: 100, url: `https://cdn.example/objects/${i}` })));
const packet = validateRobotResources(config, 'rp1/robot.json', files);
assert.deepEqual(packet.config.skills.map((s) => s.id), ['walk', 'dance', 'wave']);
assert.equal(packet.warnings.length, 0);
assert.equal(packet.resources.filter((f) => f.path.endsWith('.f32')).length, 2);
for (const file of packet.resources) assert.equal(file.url, files.get(file.path).url);
});
test('bound resource inventory rejects traversal, active URLs, duplicates and invalid sizes', () => {
const file = { relativePath: 'parts/a.glb', sizeBytes: 10, url: 'https://cdn.example/a.glb' };
for (const patch of [{ relativePath: '../a.glb' }, { url: 'javascript:alert(1)' }, { sizeBytes: -1 }, { sizeBytes: Infinity }]) assert.throws(() => resourceIndex([{ ...file, ...patch }]));
assert.throws(() => resourceIndex([file, file]));
});
test('large uploaded assemblies are not blocked by a total-size cap', () => {
const files = resourceIndex(['body.glb', 'parts.glb'].map(relativePath => ({ relativePath,
sizeBytes: 210 * 1024 * 1024, url: 'https://cdn.example/' + relativePath })));
assert.equal(files.size, 2);
});
test('assembly resolves exact API URLs across different upload batches and rejects a mismatched part', async () => {
const raw = { schemaVersion: 1, kind: 'assembly', unit: 'meter', files: [{ path: 'parts/a.glb', bytes: 100, sha256: 'a'.repeat(64) }], parts: [{ id: 'a', file: 'parts/a.glb' }], steps: [{ id: 'one', parts: ['a'] }] };
const project = { assemblyJsonUrl: 'https://cdn.example/json/batch/steps.json', modelPartsFiles: [{ relativePath: 'parts/a.glb', sizeBytes: 100, url: 'https://cdn.example/parts/other/parts/a.glb' }] };
const original = globalThis.fetch;
globalThis.fetch = async () => new Response(JSON.stringify(raw));
try {
const result = await loadProjectAssembly(project);
assert.equal(result.files.get('parts/a.glb').url, project.modelPartsFiles[0].url);
await assert.rejects(loadProjectAssembly({ ...project, modelPartsFiles: [{ ...project.modelPartsFiles[0], sizeBytes: 101 }] }), /版本与步骤不一致/);
const stripped = await loadProjectAssembly({ ...project, modelPartsFiles: [{ ...project.modelPartsFiles[0], relativePath: 'a.glb' }] });
assert.equal(stripped.files.get('parts/a.glb').url, project.modelPartsFiles[0].url);
assert.equal(stripped.files.get('parts/a.glb').sha256, raw.files[0].sha256);
assert.equal(stripped.parts[0].file, 'parts/a.glb');
await assert.rejects(loadProjectAssembly({ ...project, modelPartsFiles: [{ ...project.modelPartsFiles[0], relativePath: 'other.glb' }] }), /目录不匹配/);
} finally { globalThis.fetch = original; }
});
test('assembly folder roots may be added, removed or renamed without flattening subdirectories', () => {
const index = (paths) => resourceIndex(paths.map((relativePath) => ({ relativePath, sizeBytes: 100, url: 'https://cdn.example/' + relativePath })));
const expected = index(['parts/left/a.glb', 'parts/right/a.glb', 'parts/body.glb']);
for (const root of ['', 'upload/', 'upload/parts/']) {
const actual = index(['left/a.glb', 'right/a.glb', 'body.glb'].map((p) => root + p));
const resolved = bindAssemblyFiles(expected, actual);
assert.equal(resolved.get('parts/left/a.glb'), actual.get(root + 'left/a.glb'));
assert.equal(resolved.get('parts/right/a.glb'), actual.get(root + 'right/a.glb'));
}
assert.throws(() => bindAssemblyFiles(expected, index(['a.glb', 'body.glb'])), /目录不匹配/);
assert.throws(() => bindAssemblyFiles(expected, index(['left/a.glb', 'elsewhere/right/a.glb', 'body.glb'])), /目录不匹配/);
assert.throws(() => bindAssemblyFiles(expected, index(['left/A.glb', 'right/a.glb', 'body.glb'])), /目录不匹配/);
assert.throws(() => bindAssemblyFiles(expected, index(['left/a.glb', 'right/a.glb'])), /目录不匹配/);
});
test('uploaded tool and screw use their own bound URLs and retain declarative docking data', async () => {
const raw = { schemaVersion: 1, kind: 'assembly', unit: 'meter',
files: ['螺丝.glb', '扳手.glb'].map(path => ({ path, bytes: 100, sha256: 'a'.repeat(64) })),
tools: [{ id: 'hex', file: '扳手.glb', tipPosition: [0.01, 0, 0.03] }],
parts: [{ id: 'screw', file: '螺丝.glb', installation: { type: 'screw', toolId: 'hex', axis: [0, 0, -1],
socketPosition: [0, 0, -0.001], direction: 'clockwise', turns: 3, travel: 0.0012 } }],
steps: [{ id: 'one', parts: ['screw'] }] };
const project = { assemblyJsonUrl: 'https://cdn.example/steps.json', modelPartsFiles: raw.files.map((file, i) => ({
relativePath: '零件模型/' + file.path, sizeBytes: file.bytes, url: `https://cdn.example/batch-${i}/file.glb`,
})) };
const original = globalThis.fetch;
globalThis.fetch = async () => new Response(JSON.stringify(raw));
try {
const pkg = await loadProjectAssembly(project);
assert.equal(pkg.parts[0].installation.type, 'screw');
assert.deepEqual(pkg.tools[0].tipPosition, [0.01, 0, 0.03]);
assert.equal(pkg.files.get('扳手.glb').url, project.modelPartsFiles[1].url);
assert.equal(pkg.parts.length, 1); // The tool is an asset, never an installed robot part.
project.modelPartsFiles.pop();
await assert.rejects(loadProjectAssembly(project), /目录不匹配/);
} finally { globalThis.fetch = original; }
});
test('assembly root matching rejects ambiguous copies and wrong versions; exact paths take priority', () => {
const entry = (relativePath, sizeBytes = 100) => ({ relativePath, sizeBytes, url: 'https://cdn.example/' + relativePath });
const expected = resourceIndex([entry('parts/a.glb'), entry('parts/b.glb')]);
const copies = [entry('copy1/a.glb'), entry('copy1/b.glb'), entry('copy2/a.glb'), entry('copy2/b.glb')];
assert.throws(() => bindAssemblyFiles(expected, resourceIndex(copies)), /多套文件/);
assert.throws(() => bindAssemblyFiles(expected, resourceIndex([entry('a.glb'), entry('b.glb', 101)])), /版本与步骤不一致/);
const exact = resourceIndex([...copies, entry('parts/a.glb'), entry('parts/b.glb')]);
assert.equal(bindAssemblyFiles(expected, exact).get('parts/a.glb'), exact.get('parts/a.glb'));
});
test('new API bindings independently control entries and project-resources works through the local proxy', () => {
assert.equal(hasProjectWalking({}), false);
assert.equal(assemblySource({}), null);
assert.equal(hasProjectWalking({ walkingResourcesBaseUrl: 'https://cdn.example/walk/', walkingResourcesFiles: [{ relativePath: 'robot.json' }] }), true);
const url = 'https://linkerbot.oss-cn-beijing.aliyuncs.com/vibemake_dev/project-resources/test/walking-resources/batch/policies/walk.onnx';
const proxy = modelAssetUrl(url, '192.168.1.9');
assert.match(proxy, /^\/__model_assets\//);
assert.equal(modelAssetTarget(proxy).href, url);
assert.equal(modelAssetTarget(proxy.replace('walk.onnx', 'code.js')), null);
assert.equal(modelAssetTarget(proxy.replace('walk.onnx', 'dance.f32')).href, url.replace('walk.onnx', 'dance.f32'));
});
+94
View File
@@ -0,0 +1,94 @@
// Visual refinement inside the finite available entry space. Sampled checks are
// explicitly NOT continuous collision certification, nor tool/reachability checks.
import { readFileSync,writeFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import { Vector3,Quaternion,Matrix4 } from 'three';
import { validatePackage } from '../js/experience-packages.js';
import { assemblyColliders } from './lib/assembly-colliders.mjs';
import { checkFiniteAxis } from './lib/assembly-axis-planner.mjs';
const folder=new URL('../deliverables/experience-packages/microduck-numbered-body/',import.meta.url);
const raw=JSON.parse(readFileSync(new URL('manifest.json',folder))),next=structuredClone(raw);
const review=JSON.parse(readFileSync(new URL('axis-review.json',folder)));
const notes=JSON.parse(readFileSync(new URL('manifest.notes.json',folder)));
const config=validatePackage(raw,'assembly','http://localhost:8090/manifest.json');
const get=assemblyColliders(config,'/Users/jerry/Downloads/小鸭子-扳手装配/零件模型');
const map=new Map(config.parts.map(p=>[p.id,p])),nextMap=new Map(next.parts.map(p=>[p.id,p]));
const inverse=new Quaternion(...config.displayQuaternion).invert();
const installed=[],changes=[];
for(const [i,step]of config.steps.entries()){
const moving=await Promise.all(step.parts.map(id=>get(map.get(id))));
const record=review.steps[i];
if(i>=52&&record.candidates){
const candidates=record.candidates.map(c=>({name:c.name,vector:c.vector,travel:c.travel}));
// A yaw fork or circuit board can also enter diagonally; neither is a closed
// bearing requiring an axial press fit. Keep bearing/screw constraints intact.
if(['trunk-3-10','trunk-3-22','trunk-3-38'].includes(step.id)){
for(const x of [-1,0,1])for(const y of [-1,0,1])for(const z of [-1,0,1]){
if(!(x||y||z))continue;
const vector=new Vector3(x,y,z).normalize().toArray();
if(!candidates.some(c=>new Vector3(...c.vector).distanceTo(new Vector3(...vector))<1e-5))
candidates.push({name:`diagonal-${x}-${y}-${z}`,vector,travel:.055});
}
}
const windows=[];
for(const candidate of candidates){
const count=Math.ceil(candidate.travel/.0005),spacing=candidate.travel/count;
const offset=new Vector3(),translation=new Matrix4(),states=[];
for(let n=0;n<=count;n++){
offset.fromArray(candidate.vector).multiplyScalar(n*spacing);
translation.makeTranslation(...offset.toArray());
let blocker=null;
for(const m of moving){
const box=m.box.clone().translate(offset);
const hit=installed.find(b=>b.box.intersectsBox(box)&&b.bvh.intersectsGeometry(m.geometry,translation));
if(hit){blocker=hit.id;break;}
}
states.push(blocker);
}
// Prefer the clear interval nearest the seat, instead of flying through an
// opposite limb to get there. Require a visible >=4 mm interval.
for(let a=0;a<states.length;){
if(states[a]){a++;continue;}
let b=a;while(b+1<states.length&&!states[b+1])b++;
const travel=b===count?candidate.travel:Math.max(0,(b-1)*spacing);
if(travel-a*spacing>=.004){
windows.push({...candidate,travel,firstSampledContact:Math.max(0,(a-1)*spacing),
nearestBlocker:a?states[a-1]:null,sampleSpacing:spacing,samples:states.length});
break;
}
a=b+1;
}
}
windows.sort((a,b)=>a.firstSampledContact-b.firstSampledContact);
const current=windows.find(c=>c.name===record.selected.name);
const best=windows[0];
// Avoid gratuitous changes for an insignificant submillimetre sampling difference.
const selected=current&&best&&current.firstSampledContact<=best.firstSampledContact+.00075?current:best;
record.finiteVisualReview={method:'0.5 mm or finer triangle-intersection samples, clear entry window >=4 mm',
collisionCertified:false,candidates:windows,selected:selected??null};
if(selected){
const offset=new Vector3(...selected.vector).multiplyScalar(selected.travel).applyQuaternion(inverse).toArray().map(v=>Math.abs(v)<1e-12?0:v);
const changed=step.parts.some(id=>offset.some((v,k)=>Math.abs(v-nextMap.get(id).installOffset[k])>1e-8));
if(changed){
for(const id of step.parts)nextMap.get(id).installOffset=[...offset];
record.finiteVisualReview.continuousRecheck=checkFiniteAxis(moving,installed,selected.vector,selected.travel,{maxMilliseconds:5000});
record.finalOffsets=step.parts.map(id=>nextMap.get(id).installOffset);
const note=`按实际进入空间再次筛选,装入距离 ${(selected.travel*1000).toFixed(1)} mm;有限采样未发现接触的行程到距终点约 ${(selected.firstSampledContact*1000).toFixed(1)} mm 处,仍不作为全程无碰撞认证。`;
notes.steps[i].reason=note;
changes.push({id:step.id,label:step.label,from:raw.parts.find(p=>p.id===step.parts[0]).installOffset,to:offset,selection:selected});
}
}
console.log(`${i+1}/${config.steps.length} ${step.label}: ${selected?.name??'no-free-entry-window'} ${selected?(selected.travel*1000).toFixed(1)+'mm':''}`);
}
installed.push(...moving);
}
assert.deepEqual(raw.steps,next.steps);assert.deepEqual(raw.files,next.files);assert.deepEqual(raw.tools,next.tools);
for(let i=0;i<raw.parts.length;i++){
const{installOffset:a,...p}=raw.parts[i],{installOffset:b,...q}=next.parts[i];assert.deepEqual(p,q);
}
validatePackage(next,'assembly','http://localhost:8090/manifest.json');
review.finiteVisualChanges=changes;
writeFileSync(new URL('manifest.json',folder),JSON.stringify(next,null,2)+'\n');
writeFileSync(new URL('manifest.notes.json',folder),JSON.stringify(notes,null,2)+'\n');
writeFileSync(new URL('axis-review.json',folder),JSON.stringify(review,null,2)+'\n');
console.log(JSON.stringify({changed:changes.map(c=>({id:c.id,travelMm:c.selection.travel*1000,contactMm:c.selection.firstSampledContact*1000}))}));
+108
View File
@@ -0,0 +1,108 @@
// One-time migration for the 2026-10-30 export. Keep screw axes, sockets,
// installed transforms, order, filenames and integrity hashes unchanged.
import fs from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { Quaternion, Vector3, Group, Mesh, BufferGeometry, BufferAttribute, Matrix4 } from '../vendor/three/build/three.module.min.js';
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import draco3d from 'draco3dgltf';
import { inferToolTipAxis } from '../js/assembly-motion.js';
import { validatePackage } from '../js/experience-packages.js';
import { resourceIndex, bindAssemblyFiles } from '../js/project-resources.js';
const root = new URL('..', import.meta.url).pathname;
const output = '/Users/jerry/Downloads/小鸭子-螺丝方向修正版-20261030';
const bundle = '/Users/jerry/Downloads/三个机器人-后台上传-20261030/01-小鸭子-Microduck';
const readJSON = async p => JSON.parse(await fs.readFile(p, 'utf8'));
const writeJSON = (p, value) => fs.writeFile(p, JSON.stringify(value, null, 2) + '\n');
const current = path.join(root, 'deliverables/current-robots/microduck/assembly.json');
const original = await readJSON(current);
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'draco3d.decoder': await draco3d.createDecoderModule() });
const assets = path.join(root, 'deliverables/current-robots/duck-parts');
const toolDoc = await io.read(path.join(assets, original.tools[0].file));
const template = new Group();
for (const node of toolDoc.getRoot().listNodes()) {
for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
const geometry = new BufferGeometry().setAttribute('position', new BufferAttribute(primitive.getAttribute('POSITION').getArray(), 3));
if (primitive.getIndices()) geometry.setIndex(new BufferAttribute(primitive.getIndices().getArray(), 1));
const mesh = new Mesh(geometry);
mesh.applyMatrix4(new Matrix4().fromArray(node.getWorldMatrix()));
template.add(mesh);
}
}
const inferred = inferToolTipAxis(template, original.tools[0].tipPosition);
assert.ok(new Vector3(...inferred).distanceTo(new Vector3(0, 0, -1)) < 1e-4, `Unexpected tool tip axis: ${inferred}`);
const records = [];
for (const part of original.parts.filter(p => p.installation)) {
const motion = part.installation, axis = new Vector3(...motion.axis), outward = axis.clone().negate();
const doc = await io.read(path.join(assets, part.file));
const vertices = [];
for (const node of doc.getRoot().listNodes()) for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
const positions = primitive.getAttribute('POSITION'), matrix = new Matrix4().fromArray(node.getWorldMatrix());
for (let i = 0; i < positions.getCount(); i++) vertices.push(new Vector3().fromArray(positions.getArray(), i * 3).applyMatrix4(matrix));
}
const distances = vertices.map(v => v.dot(outward));
const min = Math.min(...distances), max = Math.max(...distances);
const u = new Vector3().crossVectors(outward, Math.abs(outward.x) < 0.8 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0)).normalize();
const v = new Vector3().crossVectors(outward, u);
const width = end => {
const cap = vertices.filter((_, i) => Math.abs(distances[i] - end) < 0.0006);
const us = cap.map(p => p.dot(u)), vs = cap.map(p => p.dot(v));
return Math.max(Math.max(...us) - Math.min(...us), Math.max(...vs) - Math.min(...vs));
};
const headWidth = width(max), tailWidth = width(min);
const offsetAlignment = outward.clone().applyQuaternion(new Quaternion(...part.quaternion)).dot(new Vector3(...part.installOffset).normalize());
const socketDepth = max - new Vector3(...motion.socketPosition).dot(outward);
assert.ok(headWidth > tailWidth * 1.2, `${part.id}: head end is not wider than tail`);
assert.ok(Math.abs(socketDepth - 0.00035) < 0.00002, `${part.id}: socket is not in head cap`);
assert.ok(offsetAlignment > 0.999, `${part.id}: insertion offset is not on the head side`);
records.push({ id: part.id, file: part.file, headWidth, tailWidth, socketDepth, offsetAlignment });
}
assert.equal(records.length, 165);
await fs.mkdir(path.join(output, '核对记录'), { recursive: true });
function repair(raw) {
const repaired = structuredClone(raw);
for (const tool of repaired.tools) tool.tipAxis = [0, 0, -1];
for (const part of repaired.parts.filter(p => p.installation)) {
part.installation.toolQuaternion = new Quaternion().setFromUnitVectors(new Vector3(0, 0, -1), new Vector3(...part.installation.axis))
.multiply(new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 6)).toArray();
}
const restored = structuredClone(repaired);
restored.tools = raw.tools;
restored.parts.forEach((p, i) => { if (p.installation) p.installation.toolQuaternion = raw.parts[i].installation.toolQuaternion; });
assert.deepEqual(restored, raw, 'Only tool direction/quaternion may change');
validatePackage(repaired, 'assembly', 'https://example.com/assembly.json');
return repaired;
}
for (const [name, file] of [
['canonical', path.join(root, 'deliverables/experience-packages/microduck-current/manifest.json')],
['preview', current],
['three-robots', path.join(bundle, '03-拼装步骤/小鸭子-239步装配.json')],
]) {
const raw = await readJSON(file), backup = path.join(output, '核对记录', name + '-before.json.bak');
try { await fs.writeFile(backup, JSON.stringify(raw, null, 2) + '\n', { flag: 'wx' }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
await writeJSON(file, repair(raw));
}
// The supplied original files are authoritative; never derive uploads from backend bindings.
const correctedLive = repair(original);
// The user supplied uncompressed files. Same instances/transforms,
// but byte lengths and hashes differ from our compressed upload alternative.
const sources = '/Users/jerry/Downloads/开发提交/鸭子最新glb';
const provenance = await readJSON(path.join(root, 'deliverables/current-robots/duck-parts.json'));
for (const file of correctedLive.files) {
const bytes = await fs.readFile(path.join(sources, file.path));
const hash = createHash('sha256').update(bytes).digest('hex');
assert.equal(hash, provenance.find(p => p.file === file.path).sourceSha256);
file.bytes = bytes.length;
file.sha256 = hash;
}
const validated = validatePackage(correctedLive, 'assembly', 'https://example.com/assembly.json');
assert.equal(bindAssemblyFiles(validated.files, resourceIndex(correctedLive.files.map(f => ({ relativePath: f.path, sizeBytes: f.bytes, url: 'https://example.com/' + encodeURIComponent(f.path) })))).size, 243);
await writeJSON(path.join(output, '小鸭子-完整装配步骤.json'), correctedLive);
await writeJSON(path.join(output, '核对记录/165颗螺丝轴向与端面核对.json'), { toolTipAxis: inferred, checked: records.length, records });
await fs.writeFile(path.join(output, '上传说明.txt'), `此文件根据你提供的“开发提交/鸭子最新glb”原始零件和整机整理,不以后台旧数据为准。\n最终整套上传资料请用:/Users/jerry/Downloads/三个机器人-后台上传-20261030/01-小鸭子-Microduck/\n\n本次只修正扳手工作轴和 165 颗杯头螺丝的工具旋转,同时更新为原始零件的文件清单与哈希。239 步顺序、原打入轴向、最终位置、材质颜色不变。\n“核对记录”不用上传。\n`);
console.log(JSON.stringify({ output, correctedScrews: records.length, inferredToolTipAxis: inferred, files: validated.files.size }));
+112
View File
@@ -0,0 +1,112 @@
// Explicit directions for every numbered step; no robot-specific rules in the player.
// These are visual assembly instructions, not a collision-free manufacturing plan.
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { createHash } from 'node:crypto';
import assert from 'node:assert/strict';
import { Vector3, Quaternion } from 'three';
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
const source = '/Users/jerry/Downloads/小鸭子-左腿编号装配-20261029/小鸭子-左腿-按编号装配-52步.json';
const assets = '/Users/jerry/Downloads/小鸭子-扳手装配/零件模型';
const output = '/Users/jerry/Downloads/小鸭子-52步装配-当前上传';
const preview = new URL('../deliverables/experience-packages/microduck-left-numbered/', import.meta.url);
const raw = JSON.parse(readFileSync(source, 'utf8'));
const next = structuredClone(raw);
const display = new Quaternion(...raw.displayQuaternion);
const inverseDisplay = display.clone().invert();
const byId = new Map(next.parts.map(p => [p.id, p]));
const vector = a => a.map(n => Math.abs(n) < 1e-12 ? 0 : n);
// "axis" points OUT of the assembled position (the start side), not toward it.
// Local axes follow the actual GLB pose, including the slight lean of the leg.
const rules = new Map([
[1, { frame: 'display', axis: [0, 1, 0], travel: 0.035, note: '鞋底作为基座,从上方落位' }],
[2, { frame: 'display', axis: [0, 1, 0], travel: 0.055, note: '脚板从鞋底上方下降' }],
[3, { frame: 'local', axis: [0, 0, 1], travel: 0.040, note: '踝部支架从脚板上方沿底座法线装入' }],
[5, { frame: 'local', axis: [1, 0, 0], travel: 0.030, note: '6700 轴承沿轴孔,从外露一侧装入' }],
[6, { frame: 'local', axis: [-1, 0, 0], travel: 0.040, note: '连杆从轴承外侧对孔装入' }],
[7, { frame: 'display', axis: [0, 1, -0.15], travel: 0.070, note: '底部舵机三件同步,从上方略向外斜着下降,避开连杆上端' }],
[17, { frame: 'local', axis: [1, 0, 0], travel: 0.030, note: '膝部轴承沿轴孔从未封闭一侧装入,五件同步' }],
[18, { frame: 'local', axis: [0, 0, 1], travel: 0.040, note: '上腿加强板沿板面法线对接轴承' }],
[19, { frame: 'local', axis: [1, 0, 0], travel: 0.045, note: '下侧上腿舵机从加强板外侧装入,三件同步' }],
[28, { frame: 'local', axis: [1, 0, 0], travel: 0.045, note: '上侧上腿舵机从加强板外侧装入,三件同步' }],
[31, { frame: 'local', axis: [0, 0, 1], travel: 0.045, note: '上腿外壳从舵机外侧沿壳面法线扣合' }],
[34, { frame: 'local', axis: [-1, 0, 0], travel: 0.030, note: '髋部轴承从尚未封闭的一面沿轴孔装入,避免穿过已装外壳' }],
[35, { frame: 'local', axis: [-1, 0, 0], travel: 0.040, note: '髋部支架从轴承外露一侧装入,避免穿过上腿外壳' }],
[42, { frame: 'local', axis: [-1, 0, 0], travel: 0.045, note: '横滚轴承从支架外露轴孔一侧装入,五件同步' }],
[43, { frame: 'local', axis: [0, 0, 1], travel: 0.045, note: '横滚轴承座沿轴孔装入,避免沿腿长方向穿过支架' }],
[44, { frame: 'local', axis: [1, 0, 0], travel: 0.050, note: '髋部舵机沿横滚轴从外侧装入,三件同步' }],
]);
const records = [];
assert.equal(next.steps.length, 52);
assert.equal(next.parts.length, 72);
for (const [index, step] of next.steps.entries()) {
const n = index + 1, parts = step.parts.map(id => byId.get(id));
assert.equal(step.id, `left-1-${n}`);
assert.ok(parts.every(p => p.parentId === null));
const screw = parts.every(p => /螺钉/.test(p.file));
const rule = rules.get(n);
assert.ok(screw !== Boolean(rule), `Step ${n} must have exactly one explicit rule`);
let direction, reason;
if (screw) {
// Socket-facing approach: every screw uses its own pose, never a shared world axis.
assert.equal(parts.length, 1);
const p = parts[0];
const axis = p.installation ? new Vector3(...p.installation.axis).negate() : new Vector3(0, 0, 1);
p.installOffset = vector(axis.normalize().multiplyScalar(0.020).applyQuaternion(new Quaternion(...p.quaternion)).toArray());
direction = new Vector3(...p.installOffset).applyQuaternion(display).normalize();
reason = '从螺丝头一侧沿自身轴线对孔进入;保留已有扳手与顺时针拧紧配置';
} else {
const offset = new Vector3(...rule.axis).normalize().multiplyScalar(rule.travel);
if (rule.frame === 'display') offset.applyQuaternion(inverseDisplay);
else offset.applyQuaternion(new Quaternion(...parts[0].quaternion));
parts.forEach(p => { p.installOffset = vector(offset.toArray()); });
direction = offset.clone().applyQuaternion(display).normalize();
reason = rule.note;
}
records.push({ step: n, label: step.label, files: parts.map(p => p.file),
startSideDisplay: vector(direction.toArray()), travelMm: Math.hypot(...parts[0].installOffset) * 1000, reason });
if (!screw) for (const p of parts) assert.deepEqual(p.installOffset, parts[0].installOffset);
}
// Only animated starting offsets change; exact assembled geometry and materials remain intact.
assert.deepEqual(next.steps, raw.steps);
assert.deepEqual(next.files, raw.files);
assert.deepEqual(next.tools, raw.tools);
for (const [i, p] of next.parts.entries()) {
const { installOffset: a, ...actual } = p;
const { installOffset: b, ...expected } = raw.parts[i];
assert.deepEqual(actual, expected);
assert.ok(a.every(Number.isFinite));
}
for (const n of [2, 7]) {
for (const id of next.steps[n - 1].parts) {
const v = new Vector3(...byId.get(id).installOffset).applyQuaternion(display);
assert.ok(Math.abs(v.x) < 1e-10 && v.y > 0);
// Foot is exactly vertical. Servo clears the upper link with an 8.5° outward lean.
assert.ok(n === 2 ? Math.abs(v.z) < 1e-10 : Math.abs(v.z / v.y + 0.15) < 1e-10);
}
}
validatePackage(next, 'assembly', 'http://localhost:8090/manifest.json');
for (const file of next.files) {
const bytes = readFileSync(join(assets, file.path));
assert.equal(bytes.length, file.bytes);
assert.equal(createHash('sha256').update(bytes).digest('hex'), file.sha256, file.path);
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
}
mkdirSync(output, { recursive: true });
const filename = '小鸭子-左腿-52步装配.json';
const json = JSON.stringify(next, null, 2) + '\n';
writeFileSync(join(output, filename), json);
writeFileSync(new URL('directions-52.json', preview), json);
// Keep review details in the project, out of the upload folder to avoid wrong-file uploads.
writeFileSync(new URL('directions-52.notes.json', preview), JSON.stringify({
source, scope: '52 visual steps / 72 GLB instances', collisionCertified: false,
note: 'Explicit per-step directions; final poses preserved. Contact/overlap at seating is not removed by changing the approach direction.', steps: records,
}, null, 2) + '\n');
writeFileSync(join(output, '上传说明.txt'), `只上传:${filename}\n\n后台小鸭子项目 → 拼装步骤 → 选择这一个 JSON,替换旧步骤。\n不用重传零件 GLB;原来的内六角扳手仍需在零件资源中。\n上传后刷新社区页面,关闭并重新打开 AI 装配。\n\n52 步均重新配置,覆盖 72 个 GLB 实例。\n1-1 至 1-52 顺序不变,最终位置、朝向、材质、颜色不变。\n第 2 步脚板垂直下降;第 7 步底部舵机从上方略向外斜着下降(8.5°),避免沿竖直线穿过连杆上端。\n轴承和侧板按对孔/外侧方向;螺丝沿自身轴线进入。\n舵机和轴承组件同一步里的零件保持同步移动。\n\n这是展示用装配方向修订。原模型在若干最终配合位置已有接触/交叠,本文件未修改最终几何,不能标为全程无碰撞的机械工艺验证。\n`);
console.log(JSON.stringify({ output: join(output, filename), steps: records.length, parts: next.parts.length,
changedOffsets: next.parts.filter((p,i) => JSON.stringify(p.installOffset) !== JSON.stringify(raw.parts[i].installOffset)).length,
ordinarySteps: rules.size, fastenerSteps: records.length-rules.size, filesVerified: next.files.length }, null, 2));
+9 -5
View File
@@ -5,9 +5,9 @@
// dev-vibemake.robotquan.com、localhost、127.0.0.1、局域网 IP → https://dev-vibemake-api.robotquan.com
// vibemake.robotquan.com 等正式域名 → https://vibemake-api.robotquan.com
//
// 本地:node scripts/server.mjs → http://localhost:8091
// 本地:node scripts/server.mjs → http://localhost:8090
// 线上浏览器直接请求后端域名(见 js/api.js 的 API_HOSTS),这里的域名判断只用于本地调试
// 环境变量:PORT 端口(默认 8091);API_TARGET 强制所有域名都转发到这个后端;API_DEV / API_PROD 改两个后端地址;
// 环境变量:PORT 端口(默认 8090);API_TARGET 强制所有域名都转发到这个后端;API_DEV / API_PROD 改两个后端地址;
// SITE_ROOT 页面文件目录(默认:在 scripts/ 里运行时是项目根目录,在 dist/ 里运行时是 dist 本身)
import http from 'node:http';
import https from 'node:https';
@@ -15,10 +15,12 @@ import zlib from 'node:zlib';
import { createReadStream, existsSync, statSync } from 'node:fs';
import { basename, dirname, extname, join, normalize, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { MODEL_ASSET_ROUTE } from '../js/model-assets.js';
import { proxyModelAsset } from './model-assets-proxy.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(process.env.SITE_ROOT || (basename(HERE) === 'scripts' ? join(HERE, '..') : HERE));
const PORT = Number(process.env.PORT || 8091);
const PORT = Number(process.env.PORT || 8090);
const API_DEV = process.env.API_DEV || 'https://dev-vibemake-api.robotquan.com';
const API_PROD = process.env.API_PROD || 'https://vibemake-api.robotquan.com';
@@ -71,12 +73,13 @@ const TYPES = {
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.md': 'text/markdown; charset=utf-8',
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml',
'.ico': 'image/x-icon', '.urdf': 'application/xml', '.xml': 'application/xml', '.stl': 'model/stl',
'.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json', '.urdf': 'application/xml', '.xml': 'application/xml', '.stl': 'model/stl',
'.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.obj': 'text/plain', '.dae': 'model/vnd.collada+xml',
'.wasm': 'application/wasm',
};
const COMPRESS = /\.(html|js|mjs|css|json|md|svg|urdf|xml|stl|obj|dae|gltf)$/i;
const LONG_CACHE = /\.(stl|dae|obj|glb|gltf|urdf|png|jpe?g|webp|svg|ico)$/i;
const HIDDEN = /(^|\/)(\.|server\.mjs$|package\.json$|scripts\/|docs\/|README\.md$|DEPLOY\.md$|nginx\.conf)/;
const HIDDEN = /(^|\/)(\.|server\.mjs$|package\.json$|scripts\/|sandbox\/|docs\/|README\.md$|DEPLOY\.md$|nginx\.conf)/;
function sendFile(req, res, file) {
let st;
@@ -131,6 +134,7 @@ function serveStatic(req, res) {
http.createServer((req, res) => {
if (req.url === '/api' || req.url.startsWith('/api/')) proxy(req, res);
else if (req.url.startsWith(`${MODEL_ASSET_ROUTE}/`)) proxyModelAsset(req, res);
else if (req.method === 'GET' || req.method === 'HEAD') serveStatic(req, res);
else res.writeHead(405).end();
}).listen(PORT, () => {
@@ -0,0 +1,83 @@
// Validate freshly prepared upload assets with the supplied latest Sandbox schema
// and the community assembly schema. This does not imply browser simulation tests.
import {readFile,writeFile,readdir,mkdtemp,rm} from 'node:fs/promises';
import {join,resolve,dirname} from 'node:path';
import {tmpdir} from 'node:os';
import {createRequire} from 'node:module';
import {createHash} from 'node:crypto';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
import {validatePackage as validateAssembly,validateEmbeddedGlb} from '../js/experience-packages.js';
import {resourceIndex, validateRobotResources, bindAssemblyFiles} from '../js/project-resources.js';
const repo=new URL('..',import.meta.url).pathname;
const root=resolve(process.argv[2]??'/Users/jerry/Downloads/三个机器人-后台上传-20261030');
const source=join(repo,'sandbox/src/platform');
const temp=await mkdtemp(join(tmpdir(),'make-upload-validators-'));
const readJSON=async path=>JSON.parse(await readFile(path,'utf8'));
const hash=b=>createHash('sha256').update(b).digest('hex');
const arrayBuffer=b=>b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength);
try{
const compiled=await build({stdin:{contents:`
export {validatePackage as validateRobot,validateWorld} from ${JSON.stringify(source+'/loader/SchemaValidator.js')};
export {JointMotionReference} from ${JSON.stringify(source+'/policy/JointMotionReference.js')};
export {validateBodyGlb} from ${JSON.stringify(source+'/render/BodyVisuals.js')};
export {resolveWorldId} from ${JSON.stringify(source+'/worlds/arena.js')};
`,resolveDir:repo},bundle:true,platform:'node',format:'cjs',write:false,
nodePaths:[join(repo,'sandbox/node_modules'),join(repo,'node_modules')],define:{'import.meta.env.BASE_URL':'"/"'},logLevel:'silent'});
const bundled=join(temp,'validators.cjs');await writeFile(bundled,compiled.outputFiles[0].contents);
const {validateRobot,validateWorld,JointMotionReference,validateBodyGlb,resolveWorldId}=createRequire(import.meta.url)(bundled);
const results=[];
for(const name of ['01-小鸭子-Microduck','02-人形机器人-Microban','03-双足机器人-RP1']){
const folder=join(root,name),id=name.endsWith('Microduck')?'microduck':name.endsWith('Microban')?'microban':'rp1',motion=join(repo,'deliverables/current-robots',id,'motion'),result={folder:name,motion:[]};
const project=(await readJSON(join(repo,'deliverables/current-robots/preview.json')))[id];
const resources=resourceIndex(project.walkingResourcesFiles);
const bound=validateRobotResources(await readJSON(join(motion,'robot.json')),'robot.json',resources);
assert.equal(bound.warnings?.length??0,0);
for(const filename of await readdir(join(folder,'01-整机模型')))if(filename.endsWith('.glb'))validateEmbeddedGlb(arrayBuffer(await readFile(join(folder,'01-整机模型',filename))));
const entries=name.startsWith('01')?['robot.json','variants/rollers.json']:['robot.json'];
for(const entry of entries){
const file=join(motion,entry),config=validateRobot(await readJSON(file));
const ref=[];
for(const skill of config.skills.filter(s=>s.reference)){
const spec=await readJSON(resolve(dirname(file),skill.reference));
const data=await readFile(resolve(dirname(file),spec.data));
const reader=new JointMotionReference(spec,arrayBuffer(data),config.joints.groups[skill.owns],config.sim.timestep*config.sim.decimation);
ref.push({skill:skill.id,frames:reader.frames});
}
for(const visual of config.render.body_visuals??[])validateBodyGlb(arrayBuffer(await readFile(resolve(dirname(file),visual.path))));
validateWorld(await readJSON(config.adapter==='microduck'?join(motion,'worlds',resolveWorldId(config),'world.json'):join(repo,'sandbox/robot-preview/world.json')));
result.motion.push({entry,id:config.id,skills:config.skills.map(s=>s.id),bodyVisuals:config.render.body_visuals?.length??0,references:ref});
}
if(name.startsWith('01')){
const stepsFolder=join(folder,'03-拼装步骤'),files=(await readdir(stepsFolder)).filter(f=>f.endsWith('.json'));
assert.equal(files.length,1,'Only one current assembly file should be offered');
const data=await readFile(join(stepsFolder,files[0]));
const config=validateAssembly(JSON.parse(data),'assembly','https://assets.example/manifest.json');
for(const record of config.files.values()){
const bytes=await readFile(join(folder,'02-零件模型',record.path));
assert.equal(bytes.length,record.bytes);assert.equal(hash(bytes),record.sha256,record.path);
validateEmbeddedGlb(arrayBuffer(bytes));
}
for(const filename of await readdir(join(folder,'01-整机模型'))){
if(filename.endsWith('.glb'))validateEmbeddedGlb(arrayBuffer(await readFile(join(folder,'01-整机模型',filename))));
}
result.assembly={file:files[0],steps:config.steps.length,instances:config.parts.length,referencedFiles:config.files.size,sha256:hash(data)};
if(name.startsWith('01')){
const latest=await readJSON(join(repo,'deliverables/experience-packages/microduck-current/manifest.json'));
const delivered=JSON.parse(data);
assert.deepEqual(delivered.steps,latest.steps,'Assembly order and previously confirmed axes must stay unchanged');
assert.deepEqual(delivered.tools,latest.tools,'Screw tool animation must stay unchanged');
assert.deepEqual(delivered.parts.map(({file,...p})=>p),latest.parts.map(({file,...p})=>p),'Final transforms must stay unchanged');
assert.equal(config.steps.length,239);assert.equal(config.parts.length,242);assert.equal(config.files.size,243);
assert.ok(config.tools.some(t=>t.file==='内六角扳手.glb'));
assert.equal(bindAssemblyFiles(config.files,resourceIndex(project.modelPartsFiles)).size,243);
result.assembly.collisionCertified=false;
}
}else result.assembly=null;
results.push(result);console.log(JSON.stringify(result));
}
const report={checkedAt:new Date().toISOString(),browserPlaybackTested:false,
scope:'Latest source schemas, world schemas, GLB files/material bytes, assembly references/SHA256, motion reference values/joint order/control clock',results};
await writeFile(join(root,'开发核对/前端Schema与装配校验.json'),JSON.stringify(report,null,2)+'\n');
}finally{await rm(temp,{recursive:true,force:true});}
@@ -0,0 +1,74 @@
// Validate freshly prepared upload assets with the supplied latest Sandbox schema
// and the community assembly schema. This does not imply browser simulation tests.
import {readFile,writeFile,readdir,mkdtemp,rm} from 'node:fs/promises';
import {join,resolve,dirname} from 'node:path';
import {tmpdir} from 'node:os';
import {createRequire} from 'node:module';
import {createHash} from 'node:crypto';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
import {validatePackage as validateAssembly,validateEmbeddedGlb} from '../js/experience-packages.js';
const repo=new URL('..',import.meta.url).pathname;
const root=resolve(process.argv[2]??'/Users/jerry/Downloads/三个机器人-当前上传');
const source='/Users/jerry/Downloads/vibemakersandbox/app/src/platform';
const temp=await mkdtemp(join(tmpdir(),'make-upload-validators-'));
const readJSON=async path=>JSON.parse(await readFile(path,'utf8'));
const hash=b=>createHash('sha256').update(b).digest('hex');
const arrayBuffer=b=>b.buffer.slice(b.byteOffset,b.byteOffset+b.byteLength);
try{
const compiled=await build({stdin:{contents:`
export {validatePackage as validateRobot,validateWorld} from ${JSON.stringify(source+'/loader/SchemaValidator.js')};
export {JointMotionReference} from ${JSON.stringify(source+'/policy/JointMotionReference.js')};
export {validateBodyGlb} from ${JSON.stringify(source+'/render/BodyVisuals.js')};
export {resolveWorldId} from ${JSON.stringify(source+'/worlds/arena.js')};
`,resolveDir:repo},bundle:true,platform:'node',format:'cjs',write:false,
nodePaths:[join(repo,'sandbox/node_modules'),join(repo,'node_modules')],define:{'import.meta.env.BASE_URL':'"/"'},logLevel:'silent'});
const bundled=join(temp,'validators.cjs');await writeFile(bundled,compiled.outputFiles[0].contents);
const {validateRobot,validateWorld,JointMotionReference,validateBodyGlb,resolveWorldId}=createRequire(import.meta.url)(bundled);
const results=[];
for(const name of ['01-小鸭子-Microduck','02-双足机器人-Microban','03-双足机器人-RP1']){
const folder=join(root,name),motion=join(folder,'04-机器人运动演示'),result={folder:name,motion:[]};
const entries=name.startsWith('01')?['robot.json','variants/rollers.json']:['robot.json'];
for(const entry of entries){
const file=join(motion,entry),config=validateRobot(await readJSON(file));
const ref=[];
for(const skill of config.skills.filter(s=>s.reference)){
const spec=await readJSON(resolve(dirname(file),skill.reference));
const data=await readFile(resolve(dirname(file),spec.data));
const reader=new JointMotionReference(spec,arrayBuffer(data),config.joints.groups[skill.owns],config.sim.timestep*config.sim.decimation);
ref.push({skill:skill.id,frames:reader.frames});
}
for(const visual of config.render.body_visuals??[])validateBodyGlb(arrayBuffer(await readFile(resolve(dirname(file),visual.path))));
validateWorld(await readJSON(join(motion,'worlds',resolveWorldId(config),'world.json')));
result.motion.push({entry,id:config.id,skills:config.skills.map(s=>s.id),bodyVisuals:config.render.body_visuals?.length??0,references:ref});
}
if(!name.startsWith('03')){
const stepsFolder=join(folder,'03-拼装步骤'),files=(await readdir(stepsFolder)).filter(f=>f.endsWith('.json'));
assert.equal(files.length,1,'Only one current assembly file should be offered');
const data=await readFile(join(stepsFolder,files[0]));
const config=validateAssembly(JSON.parse(data),'assembly','https://assets.example/manifest.json');
for(const record of config.files.values()){
const bytes=await readFile(join(folder,'02-零件模型',record.path));
assert.equal(bytes.length,record.bytes);assert.equal(hash(bytes),record.sha256,record.path);
validateEmbeddedGlb(arrayBuffer(bytes));
}
for(const filename of await readdir(join(folder,'01-整机模型'))){
if(filename.endsWith('.glb'))validateEmbeddedGlb(arrayBuffer(await readFile(join(folder,'01-整机模型',filename))));
}
result.assembly={file:files[0],steps:config.steps.length,instances:config.parts.length,referencedFiles:config.files.size,sha256:hash(data)};
if(name.startsWith('01')){
const latest=await readFile('/Users/jerry/Downloads/小鸭子-双腿及躯干-当前上传/小鸭子-双腿及躯干-149步装配.json');
assert.equal(hash(data),hash(latest),'Duck must match the current 149-step delivery byte for byte');
assert.equal(config.steps.length,149);assert.equal(config.parts.length,201);
assert.ok(config.tools.some(t=>t.file==='内六角扳手.glb'));
assert.ok(!config.steps.some(s=>['trunk-3-36','trunk-3-37'].includes(s.id)));
result.assembly.skipped=['3-36','3-37'];result.assembly.collisionCertified=false;
}
}else result.assembly=null;
results.push(result);console.log(JSON.stringify(result));
}
const report={checkedAt:new Date().toISOString(),browserPlaybackTested:false,
scope:'Latest source schemas, world schemas, GLB files/material bytes, assembly references/SHA256, motion reference values/joint order/control clock',results};
await writeFile(join(root,'最新Schema与装配校验.json'),JSON.stringify(report,null,2)+'\n');
}finally{await rm(temp,{recursive:true,force:true});}
@@ -0,0 +1,47 @@
// Independent integrity check against the supplied compressed whole model.
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { validatePackage,validateEmbeddedGlb } from '../js/experience-packages.js';
const root=new URL('../deliverables/experience-packages/microduck-current/',import.meta.url).pathname;
const digest=b=>createHash('sha256').update(b).digest('hex');
function glb(filename){const bytes=fs.readFileSync(filename),length=bytes.readUInt32LE(12);validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.length));return{bytes,json:JSON.parse(bytes.subarray(20,20+length)),bin:20+length+8};}
function buffer(g,i){const v=g.json.bufferViews[i];return g.bytes.subarray(g.bin+(v.byteOffset??0),g.bin+(v.byteOffset??0)+v.byteLength);}
function material(g,i){if(i===undefined)return null;const m=structuredClone(g.json.materials[i]);function visit(v){for(const[k,x]of Object.entries(v))if(x&&typeof x==='object'){
if(/Texture$/.test(k)&&x.index!==undefined){const t=structuredClone(g.json.textures[x.index]),im=g.json.images[t.source];
t.source={...im,bufferView:digest(buffer(g,im.bufferView))};if(t.sampler!==undefined)t.sampler=g.json.samplers[t.sampler];x.index=t;
}else visit(x);}}visit(m);return m;}
const source=glb('/Users/jerry/Downloads/鸭子_压缩.glb'),m=JSON.parse(fs.readFileSync(path.join(root,'manifest.json'))),map=JSON.parse(fs.readFileSync(path.join(root,'mapping.json')));
const config=validatePackage(m,'assembly','http://localhost:8090/manifest.json');
assert.equal(digest(source.bytes),map.sourceSha256);assert.equal(m.steps.length,239);assert.equal(m.parts.length,242);assert.deepEqual(m.displayQuaternion,[0,0,0,1]);
const actualOrder=m.steps.map(s=>s.id.replace('step-',''));assert.deepEqual(actualOrder,map.steps.map(s=>s.code));
assert.equal(new Set(m.steps.flatMap(s=>s.parts)).size,242);
let primitives=0,textures=0;
for(const file of m.files){const f=path.join(root,file.path),b=fs.readFileSync(f);assert.equal(b.length,file.bytes);assert.equal(digest(b),file.sha256);}
for(const [i,p]of m.parts.entries()){
const n=source.json.nodes[i],g=glb(path.join(root,p.file));assert.equal(g.json.nodes.length,1);assert.equal(g.json.nodes[0].name,n.name);
assert.equal(g.json.nodes[0].translation,undefined);assert.equal(g.json.nodes[0].rotation,undefined);assert.equal(g.json.nodes[0].scale,undefined);
assert.deepEqual(p.position,n.translation??[0,0,0]);assert.deepEqual(p.scale,n.scale??[1,1,1]);
const q=n.rotation??[0,0,0,1],norm=Math.hypot(...q);assert.ok(p.quaternion.every((x,k)=>Math.abs(x-q[k]/norm)<1e-12));
const a=source.json.meshes[n.mesh].primitives,b=g.json.meshes[0].primitives;assert.equal(a.length,b.length);
for(let k=0;k<a.length;k++){
assert.deepEqual(material(g,b[k].material),material(source,a[k].material));
assert.deepEqual(buffer(g,b[k].extensions.KHR_draco_mesh_compression.bufferView),buffer(source,a[k].extensions.KHR_draco_mesh_compression.bufferView));
assert.deepEqual(b[k].extensions.KHR_draco_mesh_compression.attributes,a[k].extensions.KHR_draco_mesh_compression.attributes);
for(const sem of Object.keys(a[k].attributes)){
const aa=structuredClone(source.json.accessors[a[k].attributes[sem]]),bb=structuredClone(g.json.accessors[b[k].attributes[sem]]);
delete aa.bufferView;delete bb.bufferView;assert.deepEqual(bb,aa);
}
primitives++;
}
textures+=g.json.images.length;
assert.ok(p.installOffset.every(Number.isFinite));assert.ok(Math.hypot(...p.installOffset)<=.1);
if(p.installation){assert.ok(Math.abs(Math.hypot(...p.installation.axis)-1)<1e-8);assert.ok(p.installation.socketPosition.every(Number.isFinite));}
}
const r=JSON.parse(fs.readFileSync(path.join(root,'axis-review.json')));assert.equal(r.records.length,239);
const stats=r.records.reduce((a,x)=>(a[x.check.status]=(a[x.check.status]??0)+1,a),{});
const summary={sourceSha256:map.sourceSha256,steps:239,parts:242,files:m.files.length,bytes:config.totalBytes,primitives,embeddedTextureReferences:textures,
originalCompressedGeometry:'byte-identical',originalMaterialsAndTextureBytes:'identical',originalFinalPoses:'identical except quaternion normalization',
checkedSteps:r.records.length,translationChecks:stats,collisionCertified:false,specificationDifferences:map.mismatches.length};
fs.writeFileSync(path.join(root,'validation.json'),JSON.stringify(summary,null,2)+'\n');console.log(JSON.stringify(summary,null,2));