Files
vibemake/js/experience-packages.js
T

273 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { modelAssetUrl } from './model-assets.js';
import { validateAssemblyGroups, groupedVisibleParts } from './assembly-groups.js';
export const PACKAGE_FIELDS = { assembly: 'assemblyManifestUrl', walking: 'walkingManifestUrl' };
export const WALKING_PROFILE = 'microduck-alpha-v1';
// Large assemblies include visibility snapshots so seeking never depends on
// previous playback. Keep this shared with the offline generator.
export const MAX_PACKAGE_JSON_BYTES = 16 * 1024 * 1024;
const fail = (message) => { throw new Error(message); };
export function packageUrl(project, kind, base = globalThis.location?.href) {
const value = project?.[PACKAGE_FIELDS[kind]];
if (typeof value !== 'string' || !value.trim()) return null;
try {
const url = new URL(value.trim(), base);
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password ? url.href : null;
} catch { return null; }
}
export function assetPath(path, { assembly = false } = {}) {
if (typeof path !== 'string' || !path || path.length > 512 || /[\\:%?\x00-\x1f]/.test(path) || (!assembly && path.includes('#'))
|| path.split('/').some((segment) => !segment || segment === '.' || segment === '..')) fail('资源路径必须是包内相对路径');
return path;
}
export function assetUrl(path, manifestUrl, options) {
const segments = assetPath(path, options).split('/');
return new URL(segments.map(encodeURIComponent).join('/'), new URL('.', manifestUrl)).href;
}
export async function fetchPackageJson(url, signal) {
if (/\.zip(?:[?#]|$)/i.test(url)) fail('请填写压缩包解压后的 manifest.json 地址,不能填写 ZIP 地址');
const response = await fetch(modelAssetUrl(url), { signal, credentials: 'omit' });
if (!response.ok) fail(`资源清单请求失败(HTTP ${response.status})`);
const bytes = await readLimited(response, MAX_PACKAGE_JSON_BYTES);
try { return JSON.parse(new TextDecoder().decode(bytes)); }
catch { fail('资源清单不是有效 JSON,请确认地址返回的是文件内容'); }
}
export async function readLimited(response, maxBytes = Infinity) {
const length = Number(response.headers.get('Content-Length'));
if (length > maxBytes) {
await response.body?.cancel();
fail('资源文件超过允许的大小');
}
if (!response.body) {
const bytes = new Uint8Array(await response.arrayBuffer());
if (bytes.length > maxBytes) fail('资源文件超过允许的大小');
return bytes;
}
const reader = response.body.getReader();
// Most individual GLBs have a known length. Fill one buffer directly rather
// than holding every network chunk plus a second full copy during decoding.
// For untrusted/large lengths use the streaming path without eager allocation.
let direct = Number.isSafeInteger(length) && length > 0 && length <= 64 * 1024 * 1024
&& !response.headers.get('Content-Encoding') ? new Uint8Array(length) : null;
const chunks = [];
let size = 0;
try {
for (;;) {
const { value, done } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > maxBytes) { await reader.cancel(); fail('资源文件超过允许的大小'); }
if (direct && size <= direct.length) direct.set(value, size - value.byteLength);
else {
if (direct) { chunks.push(direct.subarray(0, size - value.byteLength)); direct = null; }
chunks.push(value);
}
}
} finally { reader.releaseLock(); }
if (direct) return size === direct.length ? direct : direct.slice(0, size);
const bytes = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
return bytes;
}
const vector = (value, fallback, length, label) => {
const out = value ?? fallback;
if (!Array.isArray(out) || out.length !== length || !out.every(Number.isFinite)) fail(`${label} 格式错误`);
return [...out];
};
const quaternion = (value) => {
const q = vector(value, [0, 0, 0, 1], 4, '四元数');
if (Math.abs(Math.hypot(...q) - 1) > 0.001) fail('四元数必须归一化,顺序为 x、y、z、w');
return q;
};
const identifier = (value) => {
if (typeof value !== 'string' || !/^[a-zA-Z0-9_-]{1,100}$/.test(value)) fail('零件和步骤编号只能包含字母、数字、横线和下划线');
return value;
};
export function validatePackage(raw, kind, sourceUrl) {
if (!raw || raw.schemaVersion !== 1 || raw.kind !== kind) fail('资源包类型或 schemaVersion 不受支持');
const options = { assembly: kind === 'assembly' };
if (!Array.isArray(raw.files) || !raw.files.length) fail('资源文件清单为空');
if (kind === 'walking' && raw.files.length > 1000) fail('行走资源文件清单超过 1000 个');
const files = new Map();
let total = 0;
for (const file of raw.files) {
const path = assetPath(file.path, options);
if (files.has(path) || !Number.isSafeInteger(file.bytes) || file.bytes <= 0 || !/^[a-f0-9]{64}$/.test(file.sha256)) fail(`文件清单无效:${path}`);
total += file.bytes;
files.set(path, { ...file, url: assetUrl(path, sourceUrl, options) });
}
const pkg = { ...raw, sourceUrl, files, totalBytes: total };
const requireFile = (path) => {
assetPath(path, options);
if (!files.has(path)) fail(`清单缺少文件:${path}`);
return path;
};
if (kind === 'walking') {
if (raw.runtimeProfile !== WALKING_PROFILE || raw.robotId !== 'microduck-alpha') fail('此行走包需要尚未支持的机器人运行器');
if (raw.autoWalk !== false) fail('行走包必须设置 autoWalk: false');
pkg.controller = requireFile(raw.controller);
for (const path of ['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']) requireFile(path);
return pkg;
}
if (raw.unit !== 'meter') fail('装配包必须使用米作为统一单位');
if (!Array.isArray(raw.parts) || !raw.parts.length) fail('装配包需要至少一个零件');
pkg.displayQuaternion = quaternion(raw.displayQuaternion);
const glbFile = (path) => {
const file = requireFile(path);
if (!/\.glb$/i.test(file)) fail('装配资源必须是 GLB');
return file;
};
const bounded = (value, min, max, label) => {
if (!Number.isFinite(value) || value < min || value > max) fail(`${label} 必须在 ${min}–${max} 之间`);
return value;
};
const toolIds = new Set();
if (raw.tools !== undefined && (!Array.isArray(raw.tools) || raw.tools.length > 32)) fail('装配工具必须是数组,最多 32 个');
pkg.tools = (raw.tools ?? []).map((tool) => {
const id = identifier(tool.id);
if (toolIds.has(id)) fail(`重复的工具编号:${id}`);
toolIds.add(id);
const result = { id, file: glbFile(tool.file), tipPosition: vector(tool.tipPosition, undefined, 3, '工具端点') };
if (tool.tipAxis !== undefined) {
result.tipAxis = vector(tool.tipAxis, undefined, 3, '工具工作轴');
if (Math.abs(Math.hypot(...result.tipAxis) - 1) > 0.001) fail('工具工作轴必须是单位向量');
}
return result;
});
const installation = (value) => {
if (value === undefined) return undefined;
if (!value || value.type !== 'screw') fail('不支持的安装动画类型');
if (!toolIds.has(value.toolId)) fail(`螺丝引用了未定义的工具:${value.toolId}`);
const axis = vector(value.axis, undefined, 3, '螺丝插入轴');
if (Math.abs(Math.hypot(...axis) - 1) > 0.001) fail('螺丝插入轴必须是单位向量');
if (!['clockwise', 'counterclockwise'].includes(value.direction)) fail('螺丝旋转方向必须是 clockwise 或 counterclockwise');
if (!Number.isInteger(value.turns)) fail('旋转圈数必须是整数,以保持最终装配姿态');
return { type: 'screw', toolId: value.toolId, axis,
socketPosition: vector(value.socketPosition, undefined, 3, '螺丝工具对接点'),
toolQuaternion: quaternion(value.toolQuaternion), direction: value.direction,
...(value.toolScale === undefined ? {} : {toolScale:bounded(value.toolScale, 0.1, 10, '工具显示缩放')}),
turns: bounded(value.turns, 1, 20, '旋转圈数'),
travel: bounded(value.travel, 0.00001, 0.1, '拧入距离(米)'),
toolClearance: bounded(value.toolClearance ?? 0.012, 0.001, 0.2, '工具退出距离(米)'),
approachDuration: bounded(value.approachDuration ?? 0.45, 0.1, 5, '螺丝就位时间(秒)'),
engageDuration: bounded(value.engageDuration ?? 0.3, 0.1, 5, '工具插入时间(秒)'),
tightenDuration: bounded(value.tightenDuration ?? 2.4, 0.5, 20, '拧紧时间(秒)'),
retractDuration: bounded(value.retractDuration ?? 0.35, 0.1, 5, '工具退出时间(秒)') };
};
const byId = new Map();
pkg.parts = raw.parts.map((part) => {
const id = identifier(part.id);
if (byId.has(id)) fail(`重复的零件编号:${id}`);
const file = glbFile(part.file);
const scale = vector(part.scale, [1, 1, 1], 3, '缩放');
if (scale.some((v) => v <= 0)) fail('零件缩放必须大于零');
const out = { id, file, parentId: part.parentId ?? null, position: vector(part.position, [0, 0, 0], 3, '位置'),
quaternion: quaternion(part.quaternion), scale, installOffset: vector(part.installOffset, [0, 0.08, 0], 3, '安装偏移') };
if (part.installation !== undefined) out.installation = installation(part.installation);
if (part.focusDirection !== undefined) {
out.focusDirection = vector(part.focusDirection, undefined, 3, '安装观察方向');
if (Math.abs(Math.hypot(...out.focusDirection) - 1) > 0.001) fail('安装观察方向必须是单位向量');
}
byId.set(id, out);
return out;
});
// 父零件可写在后面,但禁止缺失父节点和循环引用。
for (const part of pkg.parts) {
const seen = new Set([part.id]);
for (let id = part.parentId; id !== null; id = byId.get(id).parentId) {
if (!byId.has(id) || seen.has(id)) fail(`零件层级无效:${part.id}`);
seen.add(id);
}
if (part.installation) for (let node = part; node; node = byId.get(node.parentId)) {
// Float32 GLB matrix decomposition can differ by a few ULPs per axis.
// Accept that rounding without changing the authored final transform.
if (Math.max(...node.scale) - Math.min(...node.scale) > Math.max(...node.scale) * 1e-6) fail('螺丝及其父零件须使用等比缩放,避免旋转时变形');
}
}
const installed = new Set();
const stepIds = new Set();
if (raw.steps !== undefined && !Array.isArray(raw.steps)) fail('装配步骤必须是数组');
pkg.steps = (raw.steps ?? []).map((step) => {
const id = identifier(step.id);
if (stepIds.has(id) || !Array.isArray(step.parts) || !step.parts.length) fail('装配步骤编号重复或未指定零件');
stepIds.add(id);
const stepParts = new Set(step.parts);
if (stepParts.size !== step.parts.length) fail('同一步骤内不能重复安装零件');
if (step.type !== undefined && !['install', 'join'].includes(step.type)) fail('不支持的装配步骤类型');
const joining = step.type === 'join';
for (const partId of stepParts) {
const part = byId.get(partId);
if (joining) {
if (!part || !installed.has(partId)) fail('合装步骤只能移动已完成的零件');
continue;
}
if (!part || installed.has(partId)) fail(`步骤引用了未知或重复安装的零件:${partId}`);
if (part.parentId && !installed.has(part.parentId) && !stepParts.has(part.parentId)) fail('必须先安装父零件');
installed.add(partId);
}
const result = { id, label: String(step.label || id).slice(0, 120), parts: [...stepParts] };
// An explicit display snapshot is independent of installation history.
// This lets a temporary subassembly hide earlier parts without reinstalling
// them when the next cumulative step restores the complete build.
if (step.visibleParts !== undefined) {
if (!Array.isArray(step.visibleParts) || !step.visibleParts.length
|| step.visibleParts.length > pkg.parts.length) fail('步骤显示零件清单无效');
const visible = new Set(step.visibleParts);
if (visible.size !== step.visibleParts.length) fail('步骤显示零件不能重复');
for (const partId of visible) {
if (!installed.has(partId)) fail(`步骤不能显示尚未安装的零件:${partId}`);
const parentId = byId.get(partId).parentId;
if (parentId && !visible.has(parentId)) fail('显示子零件时必须同时显示父零件');
}
if ([...stepParts].some(partId => !visible.has(partId))) fail('当前安装的零件必须显示');
result.visibleParts = [...visible];
}
if (step.groupId !== undefined) result.groupId = identifier(step.groupId);
if (joining) {
result.type = 'join';
result.installOffset = vector(step.installOffset, undefined, 3, '部件合装偏移');
if (step.pathStatus !== undefined) {
if (!['checked','presentation'].includes(step.pathStatus)) fail('合装路径状态无效');
result.pathStatus = step.pathStatus;
}
}
return result;
});
if (pkg.steps.length && installed.size !== pkg.parts.length) fail('步骤必须覆盖全部零件,每个零件安装一次');
validateAssemblyGroups(pkg);
return pkg;
}
export async function loadPackage(url, kind, signal) {
return validatePackage(await fetchPackageJson(url, signal), kind, url);
}
export function visibleAssemblyParts(pkg, stepIndex) {
if (stepIndex === null) return new Set(pkg.parts.map((part) => part.id));
if (!Number.isInteger(stepIndex) || stepIndex < 0 || stepIndex >= pkg.steps.length) fail('装配步骤超出范围');
if (pkg.steps[stepIndex].visibleParts) return new Set(pkg.steps[stepIndex].visibleParts);
if (pkg.playback === 'grouped-v1') return groupedVisibleParts(pkg, stepIndex);
return new Set(pkg.steps.slice(0, stepIndex + 1).flatMap((step) => step.parts));
}
// 装配 GLB 必须自包含;防止遗漏贴图或偷偷请求包外资源。
export function validateEmbeddedGlb(buffer) {
const view = new DataView(buffer);
if (buffer.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67 || view.getUint32(4, true) !== 2
|| view.getUint32(8, true) !== buffer.byteLength || view.getUint32(16, true) !== 0x4e4f534a) fail('无效的 GLB 2.0 文件');
const length = view.getUint32(12, true);
if (20 + length > buffer.byteLength) fail('GLB 内容不完整');
const json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 20, length)));
if ([...(json.buffers || []), ...(json.images || [])].some((item) => item.uri && !item.uri.startsWith('data:'))) fail('请把贴图和缓冲区嵌入 GLB 后重新上传');
}