Files
vibemake/scripts/package-upload-retest.mjs
T
Jerry 1c837766cd feat: integrate robot assembly and simulation with resilient loading
Add backend-driven assembly and simulation experiences, MAKE branding, mobile rendering budgets and desktop-only CAD/PCB routes. Improve logo loading progress, document image recovery and URDF request handling; include dev packaging and regression coverage.
2026-10-30 18:38:39 +08:00

121 lines
14 KiB
JavaScript

// 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));