141 lines
9.8 KiB
JavaScript
141 lines
9.8 KiB
JavaScript
// Refresh a re-exported duck package without losing the confirmed step order,
|
||
// insertion directions or screw sockets. Fail if the geometry no longer fits.
|
||
import fs from 'node:fs/promises';
|
||
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 } from 'three';
|
||
import { validatePackage, validateEmbeddedGlb } from '../js/experience-packages.js';
|
||
import { resourceIndex, bindAssemblyFiles } from '../js/project-resources.js';
|
||
|
||
const [source, previous, destination] = process.argv.slice(2);
|
||
assert.ok(source && previous && destination, 'Usage: node scripts/refresh-duck-upload.mjs SOURCE_DIR PREVIOUS_JSON OUTPUT_DIR');
|
||
const partsDir = path.join(source, 'glb零件');
|
||
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
|
||
const readGlb = async filename => {
|
||
const bytes = await fs.readFile(filename);
|
||
validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
|
||
const length = bytes.readUInt32LE(12);
|
||
return { bytes, json: JSON.parse(bytes.subarray(20, 20 + length)), bin: 28 + length };
|
||
};
|
||
const chunk = (g, index) => {
|
||
const v = g.json.bufferViews[index];
|
||
return g.bytes.subarray(g.bin + (v.byteOffset ?? 0), g.bin + (v.byteOffset ?? 0) + v.byteLength);
|
||
};
|
||
const matrix = n => new Matrix4().compose(new Vector3(...(n.translation ?? [0, 0, 0])),
|
||
new Quaternion(...(n.rotation ?? [0, 0, 0, 1])).normalize(), new Vector3(...(n.scale ?? [1, 1, 1])));
|
||
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({
|
||
'draco3d.decoder': await draco3d.createDecoderModule(),
|
||
});
|
||
const vertices = doc => {
|
||
const result = [];
|
||
for (const node of doc.getRoot().listNodes()) for (const p of node.getMesh()?.listPrimitives() ?? []) {
|
||
const a = p.getAttribute('POSITION'), m = new Matrix4().fromArray(node.getWorldMatrix());
|
||
for (let i = 0; i < a.getCount(); i++) result.push(new Vector3().fromArray(a.getArray(), i * 3).applyMatrix4(m));
|
||
}
|
||
return result;
|
||
};
|
||
const old = JSON.parse(await fs.readFile(previous, 'utf8'));
|
||
validatePackage(old, 'assembly', 'https://example.com/assembly.json');
|
||
const out = structuredClone(old);
|
||
const whole = await readGlb(path.join(source, 'Microduck.glb'));
|
||
assert.equal(whole.json.nodes.length, out.parts.length);
|
||
assert.ok(whole.json.nodes.every(n => !n.children?.length && n.mesh !== undefined));
|
||
const byName = new Map(whole.json.nodes.map(n => [n.name, n]));
|
||
assert.equal(byName.size, out.parts.length);
|
||
const actualFiles = (await fs.readdir(partsDir)).filter(f => /\.glb$/i.test(f)).sort();
|
||
assert.deepEqual(actualFiles, out.files.map(f => f.path).sort(), 'New/removed part files require explicit step mapping');
|
||
const files = new Map(), records = [], used = new Set(), screwChecks = [];
|
||
let wholeDoc;
|
||
for (const file of out.files) {
|
||
const glb = await readGlb(path.join(partsDir, file.path));
|
||
files.set(file.path, glb);
|
||
file.bytes = glb.bytes.length;
|
||
file.sha256 = digest(glb.bytes);
|
||
}
|
||
for (const p of out.parts) {
|
||
const glb = files.get(p.file);
|
||
assert.equal(glb.json.nodes.length, 1, p.file);
|
||
const local = glb.json.nodes[0], n = byName.get(local.name);
|
||
assert.ok(n && !used.has(n.name), `Whole-model instance missing/duplicated: ${p.file}`);
|
||
used.add(n.name);
|
||
assert.ok(matrix(local).equals(new Matrix4()), `New part has a baked scene transform: ${p.file}`);
|
||
const pose = new Matrix4().compose(new Vector3(...p.position), new Quaternion(...p.quaternion), new Vector3(...p.scale));
|
||
const delta = Math.max(...pose.elements.map((v, i) => Math.abs(v - matrix(n).elements[i])));
|
||
// Blender re-exports float32 quaternions; tolerate their rounding only.
|
||
assert.ok(delta < 1e-6, `Final pose changed; replan this instance: ${p.file}`);
|
||
const a = whole.json.meshes[n.mesh].primitives, b = glb.json.meshes[local.mesh].primitives;
|
||
assert.equal(a.length, b.length, p.file);
|
||
let sameDraco = true;
|
||
for (let i = 0; i < a.length; i++) {
|
||
const aa = whole.json.accessors[a[i].attributes.POSITION], bb = glb.json.accessors[b[i].attributes.POSITION];
|
||
assert.deepEqual(bb, aa, `Part and whole geometry bounds differ: ${p.file}`);
|
||
sameDraco &&= chunk(whole, a[i].extensions.KHR_draco_mesh_compression.bufferView)
|
||
.equals(chunk(glb, b[i].extensions.KHR_draco_mesh_compression.bufferView));
|
||
}
|
||
// Some independently exported Draco streams differ in compression settings.
|
||
// Compare decoded coordinates too, instead of assuming equal bounds are enough.
|
||
if (!sameDraco) {
|
||
wholeDoc ??= await io.readBinary(whole.bytes);
|
||
const wn = wholeDoc.getRoot().listNodes().find(node => node.getName() === n.name);
|
||
const doc = await io.readBinary(glb.bytes), pn = doc.getRoot().listNodes()[0];
|
||
const sorted = primitive => {
|
||
const a = primitive.getAttribute('POSITION').getArray(), list = [];
|
||
for (let i = 0; i < a.length; i += 3) list.push([a[i], a[i + 1], a[i + 2]]);
|
||
return list.sort((a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]);
|
||
};
|
||
wn.getMesh().listPrimitives().forEach((primitive, i) => {
|
||
const wa = sorted(primitive), pa = sorted(pn.getMesh().listPrimitives()[i]);
|
||
assert.equal(pa.length, wa.length);
|
||
const maxError = Math.max(...wa.map((v, j) => Math.hypot(...v.map((x, k) => x - pa[j][k]))));
|
||
assert.ok(maxError < 0.000002, `${p.file}: decoded geometry differs by ${maxError} m`);
|
||
});
|
||
}
|
||
if (p.installation) {
|
||
const vs = vertices(await io.readBinary(glb.bytes)), motion = p.installation;
|
||
const outward = new Vector3(...motion.axis).negate(), u = new Vector3().crossVectors(outward,
|
||
Math.abs(outward.x) < .8 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0)).normalize();
|
||
const v = new Vector3().crossVectors(outward, u), distances = vs.map(p => p.dot(outward));
|
||
const min = Math.min(...distances), max = Math.max(...distances);
|
||
const width = end => {
|
||
const cap = vs.filter((_, i) => Math.abs(distances[i] - end) < .0006);
|
||
const us = cap.map(p => p.dot(u)), ws = cap.map(p => p.dot(v));
|
||
return Math.max(Math.max(...us) - Math.min(...us), Math.max(...ws) - Math.min(...ws));
|
||
};
|
||
const headWidth = width(max), tailWidth = width(min);
|
||
const socketDepth = max - new Vector3(...motion.socketPosition).dot(outward);
|
||
const alignment = outward.clone().applyQuaternion(new Quaternion(...p.quaternion)).dot(new Vector3(...p.installOffset).normalize());
|
||
assert.ok(headWidth > tailWidth * 1.2, `${p.file}: tool is not on wider head end`);
|
||
assert.ok(Math.abs(socketDepth - .00035) < .00002, `${p.file}: socket moved from head cap`);
|
||
assert.ok(alignment > .999, `${p.file}: approach is not from screw head`);
|
||
const tool = out.tools.find(t => t.id === motion.toolId);
|
||
assert.ok(new Vector3(...tool.tipAxis).applyQuaternion(new Quaternion(...motion.toolQuaternion))
|
||
.dot(new Vector3(...motion.axis)) > .999, `${p.file}: tool tip reversed`);
|
||
screwChecks.push({ file: p.file, headWidth, tailWidth, socketDepth, alignment });
|
||
}
|
||
records.push({ file: p.file, wholeNode: n.name, finalPoseMaxError: delta,
|
||
geometry: sameDraco ? 'identical-compressed-geometry' : 'decoded-coordinates-match' });
|
||
}
|
||
for (const tool of out.tools) assert.equal(files.get(tool.file) && digest(files.get(tool.file).bytes),
|
||
old.files.find(f => f.path === tool.file).sha256, `Tool changed; remeasure its tip: ${tool.file}`);
|
||
assert.deepEqual(out.parts, old.parts);
|
||
assert.deepEqual(out.steps, old.steps);
|
||
assert.deepEqual(out.tools, old.tools);
|
||
out.title = '小鸭子 · 最新零件配套装配(239 步,2026-11-03)';
|
||
const validated = validatePackage(out, 'assembly', 'https://example.com/assembly.json');
|
||
assert.equal(bindAssemblyFiles(validated.files, resourceIndex(out.files.map(f => ({
|
||
relativePath: f.path, sizeBytes: f.bytes, url: 'https://example.com/' + encodeURIComponent(f.path),
|
||
})))).size, out.files.length);
|
||
await fs.mkdir(path.join(destination, '核对记录'), { recursive: true });
|
||
await fs.writeFile(path.join(destination, '小鸭子-装配步骤-20261103.json'), JSON.stringify(out, null, 2) + '\n');
|
||
const summary = { source, sourceSha256: digest(whole.bytes), steps: out.steps.length, parts: out.parts.length,
|
||
tools: out.tools.length, bytes: validated.totalBytes, files: out.files.length, checkedScrews: screwChecks.length,
|
||
preserved: ['step order', 'installation offsets', 'screw head sockets', 'tool orientation', 'final poses'],
|
||
originalGlbFilesModified: false, fullCollisionCertification: false };
|
||
await fs.writeFile(path.join(destination, '核对记录/核对结果.json'), JSON.stringify({ ...summary, records, screwChecks }, null, 2) + '\n');
|
||
await fs.writeFile(path.join(destination, '上传说明.txt'), `本次仅用于你提供的 2.Microduck-开发提交。\n\n1. 整机模型:上传原目录的 Microduck.glb。\n2. 零件模型:上传原目录 glb零件 文件夹(243 个文件,含内六角扳手)。已上传这套最新零件的,不必重复上传。\n3. 拼装步骤:上传本目录的小鸭子-装配步骤-20261103.json,替换旧 JSON。\n4. 关闭前台装配弹窗并刷新页面,再打开装配。\n\n共 239 步、242 个整机零件、1 个扳手。\n沿用已确认的安装顺序、安装偏移、165 颗杯头螺丝的螺丝头对接点与扳手方向。\n这次说明中的合并件和额外螺丝,现有 239 步已经包含,不重复添加。\n整机中全部实例与这套零件逐一核对;不修改 GLB 材质、颜色或几何。\n旧 JSON 的文件大小和 SHA-256 与新导出文件不同,是“零件版本与步骤不一致”的原因。文件名相同也不能混用。\n核对记录不用上传;这次验证了文件匹配、终点姿态和螺丝头方向,没有重新进行全程机械碰撞认证。\n`);
|
||
console.log(JSON.stringify({ destination, ...summary }, null, 2));
|