-
正在加载装配模型准备模型与材质…
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
`;
document.body.append(dialog);
dialog.showModal();
@@ -56,51 +78,103 @@ export function openAssemblyPreview(project, { initialStep = null, focusPartId =
let preview;
let loading = false;
let config;
+ let timeline;
let stepIndex = null;
let playing = false;
let playTimer;
let activeScrew;
let exploded = false;
+ const labelTool = (target, label) => {
+ const button = typeof target === 'string' ? find(target) : target;
+ button.querySelector('span').textContent = label;
+ button.setAttribute('aria-label', label);
+ button.setAttribute('data-tooltip', label);
+ button.removeAttribute('title');
+ };
+ dialog.querySelectorAll('.assembly-tools button').forEach(button => {
+ labelTool(button, button.querySelector('span').textContent);
+ });
+ const hasMotion = () => !!preview?.cameraTransition || !!preview?.transitions?.length;
+ const syncPlaybackUI = () => {
+ const active = playing || (hasMotion() && !preview?.animationPaused);
+ const label = active ? '暂停装配' : hasMotion() ? '继续装配' : '播放装配';
+ find('[data-play-label]').textContent = label;
+ find('[data-play]').setAttribute('aria-label', label);
+ find('[data-play]').title = label;
+ find('[data-play]').setAttribute('aria-pressed', String(active));
+ };
const updateExplosionUI = (enabled) => {
exploded = enabled;
find('.assembly-viewport').classList.toggle('is-exploded', enabled);
find('.assembly-explosion').hidden = !enabled;
- find('[data-explode]').textContent = enabled ? '还原模型' : '爆炸图';
+ labelTool('[data-explode]', enabled ? '还原模型' : '爆炸图');
find('[data-explode]').setAttribute('aria-pressed', String(enabled));
};
const stopPlayback = () => {
playing = false;
clearTimeout(playTimer);
- find('[data-play]').textContent = preview?.transitions?.length ? '继续装配' : '播放装配';
- find('[data-play]').setAttribute('aria-pressed', 'false');
preview?.setAnimationPaused(true);
+ syncPlaybackUI();
};
const showStep = (index, animate = true) => {
stepIndex = index;
+ if (index === null) setToolsExpanded(false);
updateExplosionUI(false);
preview.setStep(index, animate);
- find('[data-play]').textContent = preview.transitions.length ? '暂停装配' : '播放装配';
- find('[data-play]').setAttribute('aria-pressed', String(preview.transitions.length > 0));
+ syncPlaybackUI();
find('.assembly-viewport').classList.toggle('is-stepping', index !== null);
find('.assembly-step').hidden = index === null;
find('[data-play]').hidden = index === null;
find('[data-replay]').hidden = index === null;
+ find('[data-closeup]').hidden = index === null || config.steps[index].type === 'join';
find('[data-rotate]').hidden = index !== null;
find('[data-explode]').hidden = index !== null || config.parts.length < 2;
- find('[data-steps]').textContent = index === null ? '逐步装配' : '查看整体';
+ labelTool('[data-steps]', index === null ? '逐步装配' : '查看整体');
+ find('[data-panel-title]').textContent = index === null ? '模型视图' : '装配进度';
+ find('[data-step-count]').textContent = index === null ? '' : `${String(index + 1).padStart(2, '0')} / ${config.steps.length}`;
+ const step = index === null ? null : config.steps[index];
+ find('[data-stage-label]').textContent = step
+ ? (config.groups?.find(group => group.id === step.groupId)?.label || (step.type === 'join' ? '总装 · 部件就位'
+ : step.label.includes('·') ? step.label.split('·')[0].trim() : '逐步安装'))
+ : '拖拽模型查看细节';
if (index !== null) {
preview.setAutoRotate(false);
find('[data-rotate]').setAttribute('aria-pressed', 'false');
+ labelTool('[data-rotate]', '自动旋转');
}
if (index !== null) {
find('[data-step-label]').textContent = `${index + 1} / ${config.steps.length} · ${config.steps[index].label}`;
find('[data-step-label]').title = find('[data-step-label]').textContent;
find('[data-seek]').value = String(index);
+ find('[data-seek]').style.setProperty('--assembly-progress-value', `${config.steps.length > 1 ? index / (config.steps.length - 1) * 100 : 100}%`);
find('[data-seek]').setAttribute('aria-valuetext', `第 ${index + 1} 步,共 ${config.steps.length} 步,${config.steps[index].label}`);
find('[data-prev]').disabled = index === 0;
find('[data-next]').disabled = index === config.steps.length - 1;
+ timeline.update(index, animate);
}
};
+ const setToolsExpanded = (expanded) => {
+ const wasExpanded = find('[data-tools-toggle]').getAttribute('aria-expanded') === 'true';
+ find('.assembly-viewport').classList.toggle('is-tools-expanded', expanded);
+ find('[data-tools-toggle]').setAttribute('aria-expanded', String(expanded));
+ if (wasExpanded && !expanded && find('.assembly-tools').contains(document.activeElement) && stepIndex !== null) find('[data-tools-toggle]').focus({ preventScroll: true });
+ };
+ find('[data-tools-toggle]').addEventListener('click', () => {
+ const expanded = find('[data-tools-toggle]').getAttribute('aria-expanded') !== 'true';
+ setToolsExpanded(expanded);
+ if (expanded) {
+ stopPlayback();
+ }
+ });
+ find('.assembly-tools').addEventListener('click', (event) => {
+ if (event.target.closest('button') && find('.assembly-viewport').classList.contains('is-tools-expanded')) setToolsExpanded(false);
+ });
+ dialog.addEventListener('pointerdown', (event) => {
+ if (!event.target.closest('.assembly-tools, [data-tools-toggle]')) setToolsExpanded(false);
+ });
+ dialog.addEventListener('cancel', (event) => {
+ if (find('.assembly-viewport').classList.contains('is-tools-expanded')) { event.preventDefault(); setToolsExpanded(false); }
+ });
find('[data-explode]').addEventListener('click', () => {
stopPlayback();
updateExplosionUI(!exploded);
@@ -117,36 +191,47 @@ export function openAssemblyPreview(project, { initialStep = null, focusPartId =
find('[data-seek]').addEventListener('input', (event) => { stopPlayback(); showStep(Number(event.target.value), false); });
find('[data-replay]').addEventListener('click', () => { stopPlayback(); showStep(stepIndex); });
find('[data-focus]').addEventListener('click', () => { if (activeScrew) preview.focusPart(activeScrew); });
- find('[data-play]').addEventListener('click', () => {
- if (playing || (preview.transitions.length && !preview.animationPaused)) { stopPlayback(); return; }
- if (stepIndex === config.steps.length - 1 && !preview.transitions.length) showStep(0, false);
+ find('[data-closeup]').addEventListener('click', () => preview?.setCloseup(!preview.closeupEnabled));
+ const startPlayback = () => {
+ if (!preview || stepIndex === null || !config.steps.length || controller.signal.aborted) return;
+ clearTimeout(playTimer);
+ if (stepIndex === config.steps.length - 1 && !hasMotion()) showStep(0, false);
playing = true;
preview.setAnimationPaused(false);
- find('[data-play]').textContent = '暂停装配';
- find('[data-play]').setAttribute('aria-pressed', 'true');
+ syncPlaybackUI();
+ let settledAt = null;
const advance = () => {
if (!playing || controller.signal.aborted) return;
if (document.hidden) { stopPlayback(); return; }
- // Wait for the visible transition, including on slower devices, before advancing.
- if (!preview.transitions.length) {
+ // Give every completed installation a visible hold, independent of frame rate.
+ if (hasMotion()) settledAt = null;
+ else if (settledAt === null) settledAt = performance.now();
+ else if (performance.now() - settledAt >= ASSEMBLY_PACE.stepHold * 1000) {
if (stepIndex === config.steps.length - 1) { stopPlayback(); return; }
showStep(stepIndex + 1);
+ settledAt = null;
}
- playTimer = setTimeout(advance, 700);
+ playTimer = setTimeout(advance, 100);
};
- playTimer = setTimeout(advance, 700);
+ playTimer = setTimeout(advance, 100);
+ };
+ find('[data-play]').addEventListener('click', () => {
+ if (playing || (hasMotion() && !preview.animationPaused)) { stopPlayback(); return; }
+ startPlayback();
});
const visibility = () => { if (document.hidden) stopPlayback(); };
document.addEventListener('visibilitychange', visibility);
const setEnabled = (enabled) => {
- dialog.querySelectorAll('.assembly-tools button, .assembly-step button, .assembly-step input, [data-explosion], [data-focus]')
+ dialog.querySelectorAll('.assembly-controls button, .assembly-controls input')
.forEach((control) => { control.disabled = !enabled; });
+ timeline?.setEnabled(enabled);
};
dialog.addEventListener('close', () => {
stopPlayback();
document.removeEventListener('visibilitychange', visibility);
controller.abort();
+ timeline?.dispose();
preview?.dispose();
document.body.style.overflow = previousOverflow;
dialog.remove();
@@ -165,8 +250,11 @@ export function openAssemblyPreview(project, { initialStep = null, focusPartId =
const enabled = button.getAttribute('aria-pressed') !== 'true';
preview?.setAutoRotate(enabled);
button.setAttribute('aria-pressed', String(enabled));
+ labelTool('[data-rotate]', enabled ? '停止旋转' : '自动旋转');
});
+ setupAssemblyControls(dialog, controller.signal);
+
async function load() {
if (loading || controller.signal.aborted) return;
loading = true;
@@ -176,6 +264,9 @@ export function openAssemblyPreview(project, { initialStep = null, focusPartId =
find('[data-retry]').hidden = true;
find('[data-progress]').textContent = '准备模型与材质…';
overlay.querySelector('strong').textContent = '正在加载装配模型';
+ labelTool('[data-closeup]', '特写');
+ find('[data-closeup]').setAttribute('aria-pressed', 'false');
+ find('[data-focus-label]').textContent = '查看特写 ↗';
setEnabled(false);
try {
find('[data-progress]').textContent = '读取装配清单…';
@@ -183,6 +274,11 @@ export function openAssemblyPreview(project, { initialStep = null, focusPartId =
config = pkg;
if (controller.signal.aborted) return;
preview = new AssemblyViewer(find('.assembly-scene'));
+ preview.onCloseupChange = (enabled) => {
+ labelTool('[data-closeup]', enabled ? '退出特写' : '特写');
+ find('[data-closeup]').setAttribute('aria-pressed', String(enabled));
+ find('[data-focus-label]').textContent = enabled ? '固定特写' : '查看特写 ↗';
+ };
preview.onContextLost = () => {
stopPlayback();
preview?.dispose();
@@ -207,6 +303,10 @@ export function openAssemblyPreview(project, { initialStep = null, focusPartId =
});
if (controller.signal.aborted) return;
preview.onAnimationEnd = () => { if (!playing) stopPlayback(); };
+ timeline?.dispose();
+ timeline = new AssemblyTimeline(find('.assembly-timeline'), config.steps, (index, animate = true) => {
+ stopPlayback(); showStep(index, animate);
+ }, stopPlayback);
overlay.hidden = true;
setEnabled(true);
find('[data-steps]').hidden = config.steps.length === 0;
@@ -218,8 +318,10 @@ export function openAssemblyPreview(project, { initialStep = null, focusPartId =
showStep(initialStep, false);
if (focusPartId) preview.focusPart(focusPartId);
showStep(initialStep);
+ if (autoPlay && !document.hidden) startPlayback();
}
} catch (err) {
+ stopPlayback();
preview?.dispose();
preview = null;
if (controller.signal.aborted) return;
diff --git a/js/document-images.js b/js/document-images.js
index 2e523ef..14b1040 100644
--- a/js/document-images.js
+++ b/js/document-images.js
@@ -1,16 +1,21 @@
// Resolve repository paths before inserting HTML, so the browser never requests
// a README image against /project/ and briefly displays a broken image.
-function resolveDocumentImage(src, { filePath = 'README.md', rawUrl } = {}) {
- if (!rawUrl || /^(https?:|data:|blob:|\/\/)/i.test(src)) return { url: src, svg: false };
+export function documentImageUrl(src, { filePath = 'README.md', rawUrl } = {}) {
+ if (!rawUrl || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(src)) return src;
try {
const url = new URL(src, `https://repository.invalid/${filePath}`);
const path = decodeURIComponent(url.pathname.slice(1));
- return { url: rawUrl(path) + url.hash, svg: /\.svg$/i.test(path) };
- } catch { return { url: src, svg: false }; }
+ return rawUrl(path) + url.hash;
+ } catch { return src; }
}
-export function documentImageUrl(src, options) {
- return resolveDocumentImage(src, options).url;
+export function repositoryImageType(src, options = {}) {
+ // Only our generated repository download URLs need MIME repair. External
+ // hosts keep native
![]()
loading (many deliberately do not allow CORS).
+ if (!options.rawUrl || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(src)) return '';
+ const ext = src.split(/[?#]/)[0].split('.').pop().toLowerCase();
+ return { svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
+ webp: 'image/webp', gif: 'image/gif', avif: 'image/avif', bmp: 'image/bmp', ico: 'image/x-icon' }[ext] || '';
}
export function prepareDocumentImages(html, options) {
@@ -20,11 +25,12 @@ export function prepareDocumentImages(html, options) {
// README data-* attributes are user content, not trusted loader state.
delete img.dataset.documentSrc;
delete img.dataset.documentSvg;
+ delete img.dataset.documentMime;
const src = img.getAttribute('src');
if (!src) continue;
- const image = resolveDocumentImage(src, options);
- img.dataset.documentSrc = image.url;
- if (image.svg) img.dataset.documentSvg = 'true';
+ img.dataset.documentSrc = documentImageUrl(src, options);
+ const mime = repositoryImageType(src, options);
+ if (mime) img.dataset.documentMime = mime;
img.removeAttribute('src');
img.removeAttribute('srcset');
img.removeAttribute('sizes');
@@ -55,32 +61,34 @@ export function hydrateDocumentImages(root, { retryDelays = [800, 2200] } = {})
status.append(message, retry, original);
frame.append(status);
let attempts = 0, timer, stopped = false, controller, objectUrl;
- const release = () => {
- controller?.abort();
- if (objectUrl) { URL.revokeObjectURL(objectUrl); objectUrl = null; }
+ const releaseUrl = () => {
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
+ objectUrl = undefined;
};
const request = async () => {
if (stopped || !img.isConnected) return;
- release();
+ controller?.abort();
+ releaseUrl();
img.removeAttribute('src');
- if (img.dataset.documentSvg !== 'true') {
- // External hosts may not allow fetch CORS; keep native loading and signed URLs.
- img.src = src;
+ if (img.dataset.documentMime) {
+ const pending = controller = new AbortController();
+ const timeout = setTimeout(() => pending.abort(), 30_000);
+ try {
+ const response = await fetch(src, { signal: pending.signal, referrerPolicy: 'no-referrer', cache: attempts ? 'reload' : 'default' });
+ if (!response.ok) throw new Error(`Image HTTP ${response.status}`);
+ const bytes = await response.blob();
+ if (stopped || pending !== controller || pending.signal.aborted || !img.isConnected) return;
+ // Repository download currently returns octet-stream + attachment +
+ // nosniff, including SVGs. Render only as
![]()
, never inline SVG HTML.
+ objectUrl = URL.createObjectURL(new Blob([bytes], { type: img.dataset.documentMime }));
+ img.src = objectUrl + new URL(src, document.baseURI).hash;
+ } catch {
+ if (!stopped && pending === controller) failed();
+ } finally { clearTimeout(timeout); }
return;
}
- // Repository downloads use application/octet-stream + nosniff, which cannot
- // be decoded as SVG by
![]()
. Set the MIME type without inlining user SVG.
- const current = controller = new AbortController();
- try {
- const response = await fetch(src, { signal: current.signal, referrerPolicy: 'no-referrer', cache: attempts ? 'reload' : 'default' });
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
- const blob = await response.blob();
- if (stopped || current.signal.aborted || !img.isConnected) return;
- objectUrl = URL.createObjectURL(new Blob([blob], { type: 'image/svg+xml' }));
- img.src = objectUrl + new URL(src, document.baseURI).hash;
- } catch {
- if (!stopped && !current.signal.aborted) failed();
- }
+ // External hosts may not allow fetch CORS. Keep native loading and signed URLs.
+ img.src = src;
};
const loaded = () => {
clearTimeout(timer);
@@ -88,6 +96,7 @@ export function hydrateDocumentImages(root, { retryDelays = [800, 2200] } = {})
};
const failed = () => {
if (stopped || !img.isConnected) return;
+ releaseUrl();
img.hidden = true; status.hidden = false; frame.classList.add('unavailable');
const auto = attempts < retryDelays.length;
message.textContent = auto ? '图片加载中,正在重试…' : '图片暂时未能加载';
@@ -108,7 +117,7 @@ export function hydrateDocumentImages(root, { retryDelays = [800, 2200] } = {})
window.addEventListener('online', online);
cleanups.push(() => {
stopped = true; clearTimeout(timer);
- release();
+ controller?.abort(); releaseUrl();
img.removeEventListener('load', loaded); img.removeEventListener('error', failed);
window.removeEventListener('online', online);
retry.removeEventListener('click', manual);
diff --git a/js/experience-packages.js b/js/experience-packages.js
index 5d899a9..28e50f6 100644
--- a/js/experience-packages.js
+++ b/js/experience-packages.js
@@ -1,4 +1,5 @@
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';
@@ -167,6 +168,10 @@ export function validatePackage(raw, kind, sourceUrl) {
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;
});
@@ -178,7 +183,9 @@ export function validatePackage(raw, kind, sourceUrl) {
seen.add(id);
}
if (part.installation) for (let node = part; node; node = byId.get(node.parentId)) {
- if (Math.max(...node.scale) - Math.min(...node.scale) > 1e-8) fail('螺丝及其父零件须使用等比缩放,避免旋转时变形');
+ // 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();
@@ -190,15 +197,48 @@ export function validatePackage(raw, kind, sourceUrl) {
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);
}
- return { id, label: String(step.label || id).slice(0, 120), parts: [...stepParts] };
+ 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;
}
@@ -209,6 +249,8 @@ export async function loadPackage(url, kind, signal) {
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));
}
diff --git a/js/home.js b/js/home.js
index 440ac39..c98f9fc 100644
--- a/js/home.js
+++ b/js/home.js
@@ -19,7 +19,7 @@ const hero = $('hero');
const loader = $('loader');
// 3D 引擎(three.js)单独加载:导航栏、列表先出来,不用等它
-let viewer = null;
+let viewer = null, viewerError = null;
const viewerReady = import('./viewer.js').then(({ RobotViewer }) => {
viewer = new RobotViewer($('stage'), { autoRotate: true, framing: 2.45, targetHeight: 0.4, groundRadius: 1.25, keepModels: true });
viewer.addEventListener('loading', () => loader.classList.remove('hidden', 'error'));
@@ -31,6 +31,9 @@ const viewerReady = import('./viewer.js').then(({ RobotViewer }) => {
tag.classList.toggle('show', !!e.detail.joint);
});
return viewer;
+}).catch(error => {
+ viewerError = error;
+ return null;
});
let slides = [];
let projects = [];
@@ -76,11 +79,15 @@ async function go(i) {
copy.classList.add('swap');
try {
- await (await viewerReady).load(p.robot);
+ const current = await viewerReady;
+ if (!current) throw viewerError;
+ await current.load(p.robot);
} catch (err) {
console.error(err);
loader.classList.add('error');
- $('loader-text').textContent = `无法加载 ${p.name} 的 URDF`;
+ $('loader-text').textContent = viewerError
+ ? '3D 展示组件加载失败,请刷新页面重试'
+ : `无法加载 ${p.name} 的 URDF`;
splashDone({ failed: true });
}
}
@@ -243,7 +250,7 @@ async function initApi() {
// 第一个模型显示出来后,空闲时在后台把其余轮播模型组装好放进内存,切换时直接显示
function prefetchSlides() {
- const run = () => slides.slice(1).forEach((p, i) => setTimeout(() => viewerReady.then((v) => v.preload(p.robot)), i * 400));
+ const run = () => slides.slice(1).forEach((p, i) => setTimeout(() => viewerReady.then((v) => v?.preload(p.robot)), i * 400));
setTimeout(() => (window.requestIdleCallback || ((f) => f()))(run), 1200);
}
diff --git a/js/model-assets.js b/js/model-assets.js
index cfa615f..a5dc643 100644
--- a/js/model-assets.js
+++ b/js/model-assets.js
@@ -17,6 +17,16 @@ function allowedAsset(value) {
}
export function modelAssetUrl(value, hostname = globalThis.location?.hostname || '') {
+ // OSS interprets a literal '+' in an object URL as a space. The API can
+ // return unescaped names such as '1+4 PCB.glb'; encode only the pathname,
+ // leaving signed query strings and already encoded '%2B' unchanged.
+ try {
+ const url = new URL(value);
+ if (url.origin === OSS_ORIGIN && url.pathname.includes('+')) {
+ url.pathname = url.pathname.replace(/\+/g, '%2B');
+ value = url.href;
+ }
+ } catch { /* Relative, blob and non-URL values keep their existing handling. */ }
if (!LOCAL_HOST.test(hostname)) return value;
const url = allowedAsset(value);
return url ? `${MODEL_ASSET_ROUTE}${url.pathname}${url.search}` : value;
diff --git a/js/project.js b/js/project.js
index c740c9a..6a472b3 100644
--- a/js/project.js
+++ b/js/project.js
@@ -12,7 +12,6 @@ import { requireLogin, openModal } from './auth.js';
import { getAssemblyModel, openAssemblyPreview } from './assembly.js';
import { hasWalkingDemo, openWalkingDemo } from './walking.js';
import { projectExperiences } from './project-experiences.js';
-import { loadProjectAssembly, publicResourceUrl } from './project-resources.js';
import { prepareDocumentImages, hydrateDocumentImages } from './document-images.js';
import { constrainedAssemblyDevice } from './assembly-memory.js';
@@ -106,22 +105,29 @@ function renderDescription(description) {
document.fonts.ready.then(updateOverflow);
}
+let previewOpen = false;
function openPreview(open, releaseBackground = false) {
+ if (previewOpen) return;
+ previewOpen = true;
const release = releaseBackground && constrainedAssemblyDevice();
if (release) { stageSuspended = true; releaseStage(); }
const dialog = open();
if (!dialog) {
+ previewOpen = false;
if (release) { stageSuspended = false; setupViewer(); }
return;
}
viewer?.setPaused(true);
- dialog.addEventListener('close', () => {
+ dialog.addEventListener('close', async () => {
+ // Wait for the iframe's physics/inference teardown before rebuilding URDF.
+ await dialog.previewDisposed;
+ previewOpen = false;
if (release) { stageSuspended = false; setupViewer(); }
else viewer?.setPaused(false);
}, { once: true });
}
$('ai-assembly').addEventListener('click', () => openPreview(() => openAssemblyPreview(projectExperiences(project)), true));
-$('walking-demo').addEventListener('click', () => openPreview(() => openWalkingDemo(projectExperiences(project))));
+$('walking-demo').addEventListener('click', () => openPreview(() => openWalkingDemo(projectExperiences(project)), true));
function renderCounters() {
const p = project;
@@ -217,91 +223,78 @@ async function setupViewer() {
const stale = () => controller.signal.aborted || generation !== stageGeneration;
$('loader').classList.remove('hidden', 'error');
$('loader-text').textContent = '正在加载模型…';
- if (!project.robot && !publicResourceUrl(project.modelGlbUrl)) {
+ if (!project.robot) {
$('stage').closest('section').hidden = true;
splashDone();
return;
}
- // The independently bound URDF owns the main interactive preview. A GLB
- // uploaded for assembly must not replace it or supply its coordinate frame.
- if (!project.robot && publicResourceUrl(project.modelGlbUrl)) {
- const { AssemblyViewer } = await import('./assembly-viewer.js');
+ // 详情区只展示后台绑定的 URDF;装配的 GLB 留在 AI 装配弹窗内。
+ $('stage').closest('section').hidden = false;
+ try {
+ // 3D 引擎按需加载:标题、README 先显示
+ const { RobotViewer } = await import('./viewer.js');
if (stale()) return;
- const current = viewer = new AssemblyViewer($('stage'));
+ const current = viewer = new RobotViewer($('stage'), { framing: 2.3, autoRotate: false, onDemand: true, renderPreset: 'studio' });
current.setPaused(!!document.querySelector('.assembly-dialog[open]'));
- $('reset-view').onclick = () => viewer?.resetView();
- try {
- // A supplied assembly frame also defines this project's assembled model orientation.
- // Plain GLB uploads otherwise use glTF's standard Y-up frame.
- const assembly = getAssemblyModel(project) ? await loadProjectAssembly(project, controller.signal).catch(() => null) : null;
- if (stale()) return;
- await current.loadGlb(project.modelGlbUrl, controller.signal, assembly?.displayQuaternion);
- if (stale()) return;
- $('loader').classList.add('hidden');
- $('stage-info').innerHTML = `
${icon('cube', 13)}整机模型拖拽旋转 · 滚轮或双指缩放`;
- } catch (error) {
- if (!controller.signal.aborted) {
- $('loader').classList.add('error');
- $('loader-text').textContent = `整机模型加载失败:${error.message}`;
- }
- } finally { splashDone(); }
- return;
- }
- // 3D 引擎按需加载:标题、README 先显示
- const { RobotViewer } = await import('./viewer.js');
- if (stale()) return;
- const current = viewer = new RobotViewer($('stage'), { framing: 2.3, autoRotate: false, onDemand: true, renderPreset: 'studio' });
- current.setPaused(!!document.querySelector('.assembly-dialog[open]'));
- const loader = $('loader');
- loader.classList.add('with-progress');
- viewer.addEventListener('loading', () => { loader.classList.remove('hidden', 'error'); $('loader-text').textContent = '正在加载 URDF…'; });
- viewer.addEventListener('progress', (e) => {
- splashProgress(e.detail.loaded / e.detail.total);
- $('loader-text').textContent = `正在加载零件 ${e.detail.loaded} / ${e.detail.total}`;
- });
- viewer.addEventListener('load', (e) => {
- loader.classList.add('hidden');
- splashDone();
- $('stage-info').innerHTML = `
${icon('cube', 13)}URDF · ${e.detail.dof} 个可动关节拖动部件转动关节 · 拖拽空白处旋转`;
- const dof = $('fact-dof');
- if (dof) dof.textContent = e.detail.dof;
- });
- viewer.addEventListener('hover', (e) => {
- const tag = $('joint-tag');
- if (e.detail.joint) tag.textContent = e.detail.joint;
- tag.classList.toggle('show', !!e.detail.joint);
- });
- const retry = document.createElement('button');
- retry.type = 'button'; retry.className = 'btn btn-sm'; retry.textContent = '重新加载模型'; retry.hidden = true;
- loader.querySelector('.loader-box').append(retry);
- let loading = false;
- const loadRobot = async () => {
- if (loading || stale()) return;
- loading = true; retry.hidden = true;
- try { await current.load(project.robot); }
- catch (err) {
- if (stale() || err.name === 'AbortError') return;
- console.error(err);
- loader.classList.remove('hidden'); loader.classList.add('error');
- $('loader-text').textContent = `URDF 未能加载:${err.message || '请检查网络连接'}`;
- retry.hidden = false;
- splashDone({ failed: true });
- } finally { loading = false; }
- };
- retry.addEventListener('click', loadRobot);
- const reconnect = () => { if (!retry.hidden) loadRobot(); };
- window.addEventListener('online', reconnect);
- stageCleanup = () => {
- controller.abort();
- window.removeEventListener('online', reconnect);
- retry.remove();
- };
- loadRobot();
+ const loader = $('loader');
+ loader.classList.add('with-progress');
+ viewer.addEventListener('loading', () => { loader.classList.remove('hidden', 'error'); $('loader-text').textContent = '正在加载 URDF…'; });
+ viewer.addEventListener('progress', (e) => {
+ splashProgress(e.detail.loaded / e.detail.total);
+ $('loader-text').textContent = `正在加载零件 ${e.detail.loaded} / ${e.detail.total}`;
+ });
+ viewer.addEventListener('load', (e) => {
+ loader.classList.add('hidden');
+ splashDone();
+ $('stage-info').innerHTML = `
${icon('cube', 13)}URDF · ${e.detail.dof} 个可动关节拖动部件转动关节 · 拖拽空白处旋转`;
+ const dof = $('fact-dof');
+ if (dof) dof.textContent = e.detail.dof;
+ });
+ viewer.addEventListener('hover', (e) => {
+ const tag = $('joint-tag');
+ if (e.detail.joint) tag.textContent = e.detail.joint;
+ tag.classList.toggle('show', !!e.detail.joint);
+ });
+ const retry = document.createElement('button');
+ retry.type = 'button'; retry.className = 'btn btn-sm'; retry.textContent = '重新加载模型'; retry.hidden = true;
+ loader.querySelector('.loader-box').append(retry);
+ let loading = false;
+ const loadRobot = async () => {
+ if (loading || stale()) return;
+ loading = true; retry.hidden = true;
+ try { await current.load(project.robot); }
+ catch (err) {
+ if (stale() || err.name === 'AbortError') return;
+ console.error(err);
+ loader.classList.remove('hidden'); loader.classList.add('error');
+ $('loader-text').textContent = `URDF 未能加载:${err.message || '请检查网络连接'}`;
+ retry.hidden = false;
+ splashDone({ failed: true });
+ } finally { loading = false; }
+ };
+ retry.addEventListener('click', loadRobot);
+ const reconnect = () => { if (!retry.hidden) loadRobot(); };
+ window.addEventListener('online', reconnect);
+ stageCleanup = () => {
+ controller.abort();
+ window.removeEventListener('online', reconnect);
+ retry.remove();
+ };
+ loadRobot();
- // 只展示模型:不播放演示动作、不自动旋转(不是所有模型都有关节映射,演示动作不一定对)
- viewer.setMode('manual');
- viewer.controls.autoRotate = false;
- $('reset-view').onclick = () => viewer?.resetPose();
+ // 只展示模型:不播放演示动作、不自动旋转(不是所有模型都有关节映射,演示动作不一定对)
+ viewer.setMode('manual');
+ viewer.controls.autoRotate = false;
+ $('reset-view').onclick = () => viewer?.resetPose();
+ } catch (error) {
+ if (stale()) return;
+ console.error(error);
+ releaseStage();
+ $('loader').classList.remove('hidden');
+ $('loader').classList.add('error');
+ $('loader-text').textContent = '3D 展示组件加载失败,请刷新页面重试';
+ splashDone({ failed: true });
+ }
}
// ---------- 概览:README ----------
@@ -614,7 +607,7 @@ async function initRemote() {
getReadme(project).catch(() => null).then((readme) => { project.readme = readme; renderReadme(); });
const robot = await ensureRobot(project).catch((err) => { console.error(err); return null; });
project.robot = robot;
- if (robot || publicResourceUrl(project.modelGlbUrl)) { stageSection.hidden = false; setupViewer(); } else splashDone();
+ if (robot) { stageSection.hidden = false; setupViewer(); } else splashDone();
}
// 收藏(点赞)与 Fork
diff --git a/js/render-budget.js b/js/render-budget.js
index 92e4644..adf700d 100644
--- a/js/render-budget.js
+++ b/js/render-budget.js
@@ -16,14 +16,26 @@ export function deviceProfile({
};
}
-// Simulation also needs a CPU/worker budget for control ticks. Keep the
-// material/light setup; spend fewer pixels on high-DPI screens instead.
-export function simulationProfile(options) {
+// Model viewers render the uploaded assets at the screen's native resolution.
+// Do not silently trade image quality for performance; heavy assets must be
+// optimized at their source. Frame limiting and on-demand rendering still apply.
+export function modelViewerProfile(options) {
const profile = deviceProfile(options);
- const compact = options?.compact ?? globalThis.matchMedia?.('(max-width: 640px)').matches ?? false;
- const mobile = compact || profile.fps <= 30;
- return { ...profile, fps: mobile ? 30 : 60, antialias: !mobile && profile.antialias, maxDpr: Math.min(profile.maxDpr, mobile ? 1 : 1.25),
- maxPixels: Math.min(profile.maxPixels, mobile ? 550_000 : 1_100_000) };
+ return {
+ ...profile,
+ antialias: true,
+ shadows: true,
+ maxDpr: Infinity,
+ maxPixels: Infinity,
+ adaptiveQuality: false,
+ };
+}
+
+// Simulation uses the same full-quality rendering on desktop and mobile.
+// The control clock remains independent; never hide heavy assets by blurring
+// the canvas, disabling antialiasing or adapting resolution after slow frames.
+export function simulationProfile(options) {
+ return { ...modelViewerProfile(options), fps: 60 };
}
export class RenderBudget {
@@ -57,6 +69,7 @@ export class RenderBudget {
}
observe(elapsed, cost) {
+ if (this.adaptiveQuality === false) return false;
if (elapsed > 250 || elapsed <= 0 || this.level === 3) return false;
this.sampleMs += elapsed;
this.costMs += cost;
diff --git a/js/viewer.js b/js/viewer.js
index c081a32..efb2c31 100644
--- a/js/viewer.js
+++ b/js/viewer.js
@@ -12,7 +12,7 @@ import { URDFDragControls } from 'urdf-loader/src/URDFDragControls.js';
import { MotionController } from './motion.js';
import { prepareRobotMaterial } from './robot-materials.js';
import { createStudioEnvironment, loadStudioHDR } from './studio-environment.js';
-import { RenderBudget, RenderLoop } from './render-budget.js';
+import { RenderBudget, RenderLoop, modelViewerProfile } from './render-budget.js';
import { fetchResource, queueModelResource } from './resource-loading.js';
import { configureRobotViewerRenderer, createRobotViewerLights, createRobotViewerReflectionMap } from './robot-viewer-lighting.js';
import { disposeAssemblyObjects as disposeObject } from './assembly-memory.js';
@@ -56,7 +56,7 @@ export class RobotViewer extends EventTarget {
this.resumeAt = 0;
this.dragging = false;
this.lastRobotPos = new THREE.Vector3();
- this.budget = new RenderBudget();
+ this.budget = new RenderBudget(modelViewerProfile());
// 缩略图共用同一个离屏渲染器(opts.renderer),避免反复创建 / 销毁 WebGL 上下文
const r = (this.renderer = this.opts.renderer || new THREE.WebGLRenderer({ antialias: this.budget.antialias, alpha: true, preserveDrawingBuffer: this.opts.preserveDrawingBuffer }));
diff --git a/js/walking-lifecycle.js b/js/walking-lifecycle.js
new file mode 100644
index 0000000..b07ffae
--- /dev/null
+++ b/js/walking-lifecycle.js
@@ -0,0 +1,35 @@
+export function isWalkingMemoryError(message) {
+ return /out of memory|memory allocation|could not allocate memory|cannot enlarge memory/i.test(message);
+}
+
+export function walkingErrorMessage(message) {
+ if (isWalkingMemoryError(message))
+ return '浏览器暂时无法为仿真分配内存,当前仿真已停止。请稍后重试;若仍失败,请关闭其他模型页面后再试。';
+ return message;
+}
+
+// Give the child time to drain inference and release native objects. Detach on
+// timeout too: a failed WASM bootstrap may never install its normal disposer.
+export function disposeWalkingFrame(frame, channel, { eventTarget = window, origin = location.origin, timeoutMs = 1500 } = {}) {
+ if (!frame) return Promise.resolve();
+ return new Promise((resolve) => {
+ let finished = false;
+ const child = frame.contentWindow;
+ const finish = () => {
+ if (finished) return;
+ finished = true;
+ clearTimeout(timer);
+ eventTarget.removeEventListener('message', onMessage);
+ frame.remove(); // Destroys the iframe realm and its dedicated workers.
+ resolve();
+ };
+ const onMessage = (event) => {
+ if (event.origin === origin && event.source === child && event.data?.channel === channel && event.data?.type === 'vibemake:walk-disposed') finish();
+ };
+ const timer = setTimeout(finish, timeoutMs);
+ if (!child || !frame.getAttribute('src') || frame.getAttribute('src') === 'about:blank') { finish(); return; }
+ eventTarget.addEventListener('message', onMessage);
+ try { child.postMessage({ type: 'vibemake:walk-dispose', channel }, origin); }
+ catch { finish(); }
+ });
+}
diff --git a/js/walking.js b/js/walking.js
index 2421dc5..dd3a0a7 100644
--- a/js/walking.js
+++ b/js/walking.js
@@ -1,5 +1,6 @@
import { icon } from './layout.js';
import { hasProjectWalking, loadProjectWalking } from './project-resources.js';
+import { disposeWalkingFrame, isWalkingMemoryError, walkingErrorMessage } from './walking-lifecycle.js';
export const hasWalkingDemo = hasProjectWalking;
let activeDialog;
@@ -14,35 +15,62 @@ export function openWalkingDemo(project) {
dialog.setAttribute('aria-label', `${project.name || '机器人'} 仿真`);
dialog.innerHTML = `
-
正在加载仿真…
`;
- const frame = dialog.querySelector('iframe');
const status = dialog.querySelector('.walking-status');
const retry = dialog.querySelector('[data-retry]');
- let timeout, controller, channel, packet;
- let closed = false;
+ let timeout, controller, channel, packet, frame;
+ let teardown = Promise.resolve();
+ const releaseFrame = () => {
+ const oldFrame = frame;
+ frame = null;
+ if (oldFrame) teardown = disposeWalkingFrame(oldFrame, channel);
+ dialog.previewDisposed = teardown;
+ return teardown;
+ };
+ let closed = false, ready = false, recoveredOnce = false;
const showError = (message) => {
if (closed) return;
clearTimeout(timeout);
+ controller?.abort();
+ releaseFrame();
status.hidden = false;
status.querySelector('.spinner').hidden = true;
- status.querySelector('[data-message]').textContent = message;
+ console.error('仿真加载失败', message);
+ status.querySelector('[data-message]').textContent = walkingErrorMessage(message);
retry.hidden = false;
};
- const start = async () => {
+ const fail = (message) => {
+ if (closed) return;
+ // A failed ORT bootstrap is cached inside its realm. Recover once with a
+ // fresh iframe AFTER disposal, never by stacking more sessions/workers in
+ // the failed realm. Do not restart a simulation the user was already using.
+ if (!ready && !recoveredOnce && isWalkingMemoryError(message)) {
+ recoveredOnce = true;
+ console.warn('仿真初始化内存不足,释放后重试一次', message);
+ void start({ recovering: true });
+ return;
+ }
+ showError(message);
+ };
+ const start = async ({ recovering = false } = {}) => {
controller?.abort();
clearTimeout(timeout);
controller = new AbortController();
const signal = controller.signal;
- frame.src = 'about:blank';
+ const released = releaseFrame();
+ ready = false;
packet = null;
- channel = Array.from(crypto.getRandomValues(new Uint32Array(4))).join('-');
retry.hidden = true;
status.hidden = false;
status.querySelector('.spinner').hidden = false;
- status.querySelector('[data-message]').textContent = '正在加载仿真…';
- timeout = setTimeout(() => showError('加载时间较长,请重试'), 90000);
+ status.querySelector('[data-message]').textContent = recovering ? '正在释放资源并重新初始化仿真…' : '正在加载仿真…';
+ timeout = setTimeout(() => fail('加载时间较长,请重试'), 90000);
try {
+ await released;
+ // Let worker termination reach the browser before requesting new memory.
+ if (recovering && !closed && !signal.aborted) await new Promise((resolve) => setTimeout(resolve, 300));
+ if (closed || signal.aborted) return;
+ channel = Array.from(crypto.getRandomValues(new Uint32Array(4))).join('-');
const pkg = await loadProjectWalking(project, signal);
if (closed || signal.aborted) return;
// 执行代码始终来自本站固定运行器;上传包只提供数据,不允许指定任意 iframe / JS。
@@ -53,23 +81,27 @@ export function openWalkingDemo(project) {
if (pkg.format === 'microduck-package') runtime.searchParams.set('bound', 'robot');
runtime.searchParams.set('channel', channel);
if (new URLSearchParams(location.search).get('profile') === '1') runtime.searchParams.set('profile', '1');
+ frame = document.createElement('iframe');
+ frame.className = 'walking-frame';
frame.title = `${project.name || '机器人'} 仿真`;
frame.src = runtime.href;
+ dialog.insertBefore(frame, status);
} catch (error) {
- if (!signal.aborted) showError(error.message || '资源包加载失败,请检查地址和跨域配置');
+ if (!signal.aborted) fail(error.message || '资源包加载失败,请检查地址和跨域配置');
}
};
const onMessage = (event) => {
- if (event.origin !== location.origin || event.source !== frame.contentWindow || event.data?.channel !== channel) return;
+ if (!frame || event.origin !== location.origin || event.source !== frame.contentWindow || event.data?.channel !== channel) return;
if (event.data.type === 'vibemake:walk-request' && packet) {
frame.contentWindow.postMessage({ type: 'vibemake:walk-init', channel, packet }, location.origin);
}
if (event.data.type === 'vibemake:walk-ready') {
+ ready = true;
clearTimeout(timeout);
status.hidden = true;
frame.focus();
}
- if (event.data.type === 'vibemake:walk-error') showError(String(event.data.message || '仿真加载失败'));
+ if (event.data.type === 'vibemake:walk-error') fail(String(event.data.message || '仿真加载失败'));
if (event.data.type === 'vibemake:walk-close') dialog.close();
};
window.addEventListener('message', onMessage);
@@ -78,14 +110,14 @@ export function openWalkingDemo(project) {
controller?.abort();
clearTimeout(timeout);
window.removeEventListener('message', onMessage);
- frame.src = 'about:blank';
- dialog.remove();
+ // Keep the detached-from-view dialog alive until the child has released its
+ // resources. project.js waits for previewDisposed before restoring URDF.
+ releaseFrame().finally(() => { dialog.remove(); activeDialog = null; });
document.body.style.overflow = previousOverflow;
- activeDialog = null;
previousFocus?.focus({ preventScroll: true });
}, { once: true });
dialog.querySelector('[data-close]').addEventListener('click', () => dialog.close());
- retry.addEventListener('click', start);
+ retry.addEventListener('click', () => { recoveredOnce = false; void start(); });
let outside = false;
dialog.addEventListener('pointerdown', (event) => { outside = event.target === dialog; });
dialog.addEventListener('click', (event) => { if (outside && event.target === dialog) dialog.close(); });
diff --git a/package.json b/package.json
index fc288cc..e907a33 100644
--- a/package.json
+++ b/package.json
@@ -7,6 +7,7 @@
"build:walking": "npm --prefix sandbox run build && npm --prefix sandbox run build:robots",
"package:experiences": "node scripts/package-experiences.mjs",
"package:assembly-parts": "node scripts/assemble-microban.mjs",
+ "assembly:generate": "node scripts/generate-numbered-assembly.mjs",
"plan:assembly": "node scripts/plan-assembly-axes.mjs",
"test:assembly-planner": "node --test scripts/assembly-axis-planner.test.mjs",
"test:downloads": "node --test tests/repository-download.test.js",
diff --git a/sandbox/build/ort-memory.js b/sandbox/build/ort-memory.js
new file mode 100644
index 0000000..c7e3318
--- /dev/null
+++ b/sandbox/build/ort-memory.js
@@ -0,0 +1,55 @@
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+
+// ORT 1.27's threaded WASM glue reserves up to 4 GiB even with numThreads=1.
+// Safari can reject that reservation before loading a small policy. Keep the
+// original SIMD binary and float32 policies; change only the memory ceiling.
+// Current five robots use 16–24 MiB in inference regression tests (all duck
+// policies resident). This is a growable ceiling, NOT an initial allocation.
+export const ORT_MAX_BYTES = 192 * 1024 * 1024;
+const UPSTREAM_SHA256 = '1db5e1c5cd2b860eed85e6eeff23e2aaa7cffcc407f67093bcc888f631b94ba9';
+const upstreamUrl = new URL('../node_modules/onnxruntime-web/dist/ort.wasm.bundle.min.mjs', import.meta.url);
+
+export function boundedOrtSource(source) {
+ // Fail the build on upstream changes: never silently ship an unpatched or
+ // partially patched allocator after upgrading the dependency.
+ if (createHash('sha256').update(source).digest('hex') !== UPSTREAM_SHA256) {
+ throw new Error('ORT memory patch: upstream changed; review the allocator and run inference regression before upgrading.');
+ }
+ if (source.split('maximum:65536').length !== 2 || source.split('4294901760').length !== 4) {
+ throw new Error('ORT memory patch: unexpected allocator layout');
+ }
+ return source
+ .replace('maximum:65536', `maximum:${ORT_MAX_BYTES / 65536}`)
+ .replaceAll('4294901760', String(ORT_MAX_BYTES));
+}
+
+// Emit one standalone, content-hashed module. ORT's proxy worker imports this
+// same module, so both the page and worker use the same allocator. Do not patch
+// WebAssembly.Memory globally or modify node_modules / downloaded model files.
+export function ortMemoryPlugin() {
+ const publicId = 'virtual:make-ort-runtime-url';
+ const resolvedId = '\0' + publicId;
+ let config;
+ let source;
+ const getSource = () => source ??= boundedOrtSource(readFileSync(upstreamUrl, 'utf8'));
+ return {
+ name: 'make-ort-memory',
+ configResolved(value) { config = value; },
+ resolveId(id) { if (id === publicId) return resolvedId; },
+ load(id) {
+ if (id !== resolvedId) return;
+ if (config.command === 'serve') return `export default ${JSON.stringify(`${config.base}@make/ort-runtime.js`)};`;
+ const ref = this.emitFile({ type: 'asset', name: 'ort.wasm.bounded.js', source: getSource() });
+ return `export default import.meta.ROLLUP_FILE_URL_${ref};`;
+ },
+ configureServer(server) {
+ server.middlewares.use((req, res, next) => {
+ if (!req.url?.split('?')[0].endsWith('/@make/ort-runtime.js')) return next();
+ res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.end(getSource());
+ });
+ },
+ };
+}
diff --git a/sandbox/package-lock.json b/sandbox/package-lock.json
index b602409..bab68ee 100644
--- a/sandbox/package-lock.json
+++ b/sandbox/package-lock.json
@@ -14,7 +14,7 @@
"@mujoco/mujoco": "^3.11.0",
"@react-three/fiber": "^9.7.0",
"ajv": "^8.20.0",
- "onnxruntime-web": "^1.27.0",
+ "onnxruntime-web": "1.27.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"three": "^0.164.1",
diff --git a/sandbox/package.json b/sandbox/package.json
index 723fd60..f19ecae 100644
--- a/sandbox/package.json
+++ b/sandbox/package.json
@@ -17,7 +17,7 @@
"@mujoco/mujoco": "^3.11.0",
"@react-three/fiber": "^9.7.0",
"ajv": "^8.20.0",
- "onnxruntime-web": "^1.27.0",
+ "onnxruntime-web": "1.27.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"three": "^0.164.1",
diff --git a/sandbox/robot-preview/main.js b/sandbox/robot-preview/main.js
index a116971..368d78d 100644
--- a/sandbox/robot-preview/main.js
+++ b/sandbox/robot-preview/main.js
@@ -1,3 +1,4 @@
+import { bindSimulationDisposal, disposeScene } from '../src/embed/lifecycle.js';
import { createEnvironmentControls } from '../src/embed/environment-controls.js';
let disposeEnvironmentControls;
import * as THREE from 'three';
@@ -16,7 +17,7 @@ const $ = (id) => document.getElementById(id);
const channel = new URLSearchParams(location.search).get('channel');
const send = (type, data = {}) => parent.postMessage({ type, channel, ...data }, location.origin);
const abort = new AbortController();
-let runtime, renderer, environment, demo, loop, observer, initialized = false, closed = false, paused = true, busy = false;
+let runtime, renderer, environment, demo, loop, observer, scene, startup, initialized = false, closed = false, paused = true, busy = false;
let unbindWake;
const held = new Map();
const clearHeld = () => {
@@ -75,7 +76,7 @@ async function start(packet) {
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.domElement.setAttribute('aria-label', '运动模型,可拖拽旋转和缩放');
$('scene').append(renderer.domElement);
- const scene = new THREE.Scene();
+ scene = new THREE.Scene();
environment = addPreviewLighting(scene, renderer);
const camera = new THREE.PerspectiveCamera(40, 1, 0.01, 100);
const resize = () => {
@@ -217,7 +218,7 @@ async function start(packet) {
}
window.addEventListener('message', (event) => {
if (event.source !== parent || event.origin !== location.origin || event.data?.channel !== channel || event.data?.type !== 'vibemake:walk-init' || initialized) return;
- initialized = true; start(event.data.packet);
+ initialized = true; startup = start(event.data.packet);
});
window.addEventListener('keydown', (event) => {
if (event.code === 'Escape') send('vibemake:walk-close');
@@ -228,10 +229,16 @@ document.addEventListener('visibilitychange', () => {
if (document.hidden) pause().catch(() => {});
loop?.setActive(!document.hidden);
});
-window.addEventListener('pagehide', () => {
- disposeEnvironmentControls?.();
+bindSimulationDisposal(async () => {
closed = true; abort.abort(); clearHeld(); observer?.disconnect(); loop?.dispose();
unbindWake?.();
- runtime?.dispose().catch(() => {}); environment?.dispose(); renderer?.dispose(); renderer?.forceContextLoss();
-}, { once: true });
+ disposeEnvironmentControls?.();
+ try {
+ await startup;
+ await runtime?.dispose();
+ } finally {
+ disposeScene(scene); environment?.dispose(); renderer?.dispose(); renderer?.forceContextLoss();
+ renderer?.domElement.remove();
+ }
+}, channel);
send('vibemake:walk-request');
diff --git a/sandbox/src/embed/lifecycle.js b/sandbox/src/embed/lifecycle.js
new file mode 100644
index 0000000..06a8275
--- /dev/null
+++ b/sandbox/src/embed/lifecycle.js
@@ -0,0 +1,29 @@
+// The parent waits for this acknowledgment before recreating its URDF viewer
+// or another simulation. pagehide alone cannot await asynchronous releases.
+export function bindSimulationDisposal(dispose, channel) {
+ let pending;
+ const stop = () => pending ??= Promise.resolve().then(dispose);
+ window.addEventListener('message', (event) => {
+ if (event.origin !== location.origin || event.source !== parent || event.data?.channel !== channel || event.data?.type !== 'vibemake:walk-dispose') return;
+ stop().catch(console.error).finally(() => parent.postMessage({ type: 'vibemake:walk-disposed', channel }, location.origin));
+ });
+ window.addEventListener('pagehide', () => { stop().catch(() => {}); }, { once: true });
+}
+
+export function disposeScene(scene) {
+ const resources = new Set(), images = new Set();
+ scene?.traverse((object) => {
+ if (object.geometry) resources.add(object.geometry);
+ object.shadow?.dispose();
+ for (const material of [object.material].flat().filter(Boolean)) {
+ resources.add(material);
+ for (const value of Object.values(material)) if (value?.isTexture) {
+ resources.add(value);
+ for (const image of [value.source?.data].flat().filter(Boolean)) images.add(image);
+ }
+ }
+ });
+ for (const resource of resources) resource.dispose();
+ for (const image of images) image.close?.();
+ scene?.clear();
+}
diff --git a/sandbox/src/embed/main.js b/sandbox/src/embed/main.js
index dcab45b..24f4bfb 100644
--- a/sandbox/src/embed/main.js
+++ b/sandbox/src/embed/main.js
@@ -1,3 +1,4 @@
+import { bindSimulationDisposal, disposeScene } from './lifecycle.js';
import { createEnvironmentControls } from './environment-controls.js';
let disposeEnvironmentControls;
import * as THREE from 'three';
@@ -15,7 +16,7 @@ import { bindMovementWake, movementCodes } from './movement-wake.js';
const $ = (id) => document.getElementById(id);
const loading = document.querySelector('.demo-loading');
const host = $('scene');
-let renderer, environment, progressTimer, loop, unwatchView, unbindSkillWake;
+let renderer, environment, progressTimer, loop, unwatchView, unbindSkillWake, scene, startup;
let paused = true;
let stopped = false;
let failed = false;
@@ -121,7 +122,7 @@ async function start(resources, packet) {
event.preventDefault();
showFailure('图形渲染中断,请关闭其他模型窗口后重新加载。');
});
- const scene = new THREE.Scene();
+ scene = new THREE.Scene();
scene.background = new THREE.Color(0x08080c);
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.02, 30);
camera.position.set(SPAWN_X + 0.55, 0.35, -SPAWN_Y + 0.7);
@@ -188,21 +189,22 @@ async function start(resources, packet) {
announce('vibemake:walk-ready');
}
window.addEventListener('blur', () => { if (useGame.getState().bootDone) { gameApi.setDemoAuto?.(false); setPaused(true); } });
-window.addEventListener('pagehide', () => {
+bindSimulationDisposal(async () => {
stopped = true;
disposeEnvironmentControls?.();
- unbindWake();
- unbindSkillWake?.();
+ unbindWake(); unbindSkillWake?.();
loadingController.abort();
clearInterval(progressTimer);
- gameApi.stopPresentation?.();
- loop?.dispose();
- unwatchView?.();
- environment?.dispose();
- renderer?.dispose();
- renderer?.forceContextLoss();
-});
-const launch = (resources, packet) => start(resources, packet).catch((error) => { if (!stopped) { console.error('仿真启动失败', error); showFailure(error.message); } });
+ loop?.dispose(); unwatchView?.();
+ try {
+ await startup;
+ await gameApi.stopPresentation?.();
+ } finally {
+ disposeScene(scene); environment?.dispose(); renderer?.dispose(); renderer?.forceContextLoss();
+ renderer?.domElement.remove();
+ }
+}, channel);
+const launch = (resources, packet) => startup = start(resources, packet).catch((error) => { if (!stopped) { console.error('仿真启动失败', error); showFailure(error.message); } });
if (params.has('bound')) {
let initialized = false;
window.addEventListener('message', (event) => {
diff --git a/sandbox/src/game/game.js b/sandbox/src/game/game.js
index 60f63ec..2a9ab19 100644
--- a/sandbox/src/game/game.js
+++ b/sandbox/src/game/game.js
@@ -55,6 +55,7 @@ import { WaypointSource } from "./controls/waypoint.js";
import { DemoSource } from "./controls/demo.js";
import { performanceProbe } from '../embed/performance-probe.js';
import { PoseHistory } from '../embed/pose-history.js';
+import { loadSessionsSequentially } from '../platform/runtime/session-loading.js';
import { ControlScheduler } from '../platform/runtime/ControlScheduler.js';
import * as fx from "./fx/fx-wireframe.js";
import { createWaypointMarker } from "./fx/waypoint-marker.js";
@@ -81,7 +82,7 @@ import mujocoWasmUrl from "@mujoco/mujoco/mujoco.wasm?url";
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.wasm?url";
// Keep the self-contained ORT module separate: its proxy worker imports this
// same file, and must never pull the page bundle (which uses document) into it.
-import ortRuntimeUrl from "onnxruntime-web/wasm?url";
+import ortRuntimeUrl from 'virtual:make-ort-runtime-url';
let bootStarted = false;
@@ -285,6 +286,25 @@ async function boot({ scene, camera, renderer, presentation }) {
return { xml: new XMLSerializer().serializeToString(doc), meshFiles };
}
+ // Start ONNX before the large GLB/physics allocations. Keep all uploaded
+ // actions, but never compile seven policy sessions concurrently on Safari.
+ const donePolicies = bootLine("LOADING POLICIES");
+ const sessionOpts = { executionProviders: ["wasm"] };
+ let sessions;
+ try {
+ const entries = ['walk', 'sitstand', 'roll', 'kickL', 'kickR', 'groundpick', 'stand']
+ .filter((id) => id === 'walk' || walkingSkillAvailable(id))
+ .map((id) => [id, POLICIES[id]]);
+ sessions = await loadSessionsSequentially(entries,
+ (url) => ort.InferenceSession.create(signed(url), sessionOpts),
+ (session) => validateSession(ort, session),
+ (loaded, total) => donePolicies.progress(`${loaded}/${total}`));
+ donePolicies(`${entries.length}/${entries.length}`);
+ } catch (err) {
+ donePolicies("FAILED");
+ throw err;
+ }
+
// ── Boot physics + policy in parallel with the render rig ────────────
const [mujoco, { xml, meshFiles }, k] = await Promise.all([
traced("MUJOCO WASM", loadMujocoFactory({
@@ -328,7 +348,6 @@ async function boot({ scene, camera, renderer, presentation }) {
}
doneMeshes(`${meshFiles.length} FILES`);
- const sessions = {};
// Always boot on the classic (orange) colourway; the quickbar re-skins live.
let currentVariant = DEFAULT_VARIANT;
const rigPromise = (async () => {
@@ -343,31 +362,6 @@ async function boot({ scene, camera, renderer, presentation }) {
throw err;
}
})();
- // Boot policies with a live [n/7] counter on the BIOS line.
- const donePolicies = bootLine("LOADING POLICIES");
- const sessionOpts = { executionProviders: ["wasm"] };
- let policiesLoaded = 0;
- const bootPolicy = (url) =>
- ort.InferenceSession.create(signed(url), sessionOpts).then(async (s) => {
- try { await validateSession(ort, s); }
- catch (error) { await s.release(); throw error; }
- donePolicies.progress(`${++policiesLoaded}/7`);
- return s;
- });
- try {
- [sessions.walk, sessions.sitstand, sessions.roll, sessions.kickL, sessions.kickR,
- sessions.groundpick, sessions.stand] =
- await Promise.all([
- bootPolicy(POLICIES.walk),
- ...['sitstand', 'roll', 'kickL', 'kickR', 'groundpick', 'stand'].map((id) => walkingSkillAvailable(id) ? bootPolicy(POLICIES[id]) : null),
- ]);
- } catch (err) {
- donePolicies("FAILED");
- bootHalt(err?.message || String(err));
- throw err;
- }
- donePolicies("7/7");
-
// ── Community move slots ──────────────────────────────────────────────
// A validated move mounts according to its manifest (Academy D7):
// perpetual -> sessions.walk (default) or sessions.sitstand (R key)
@@ -2224,14 +2218,22 @@ async function boot({ scene, camera, renderer, presentation }) {
displayPose.reset(data.qpos);
controlScheduler.start();
},
- stopPresentation: () => {
+ stopPresentation: async () => {
endGrab();
propVisuals?.dispose();
- controlScheduler.dispose();
+ await controlScheduler.dispose();
controller.dispose();
controls.dispose();
ghosts?.destroy();
- audioCtx().suspend();
+ // Audio shutdown must not prevent releasing the much larger WASM state.
+ await audioCtx().suspend().catch(() => {});
+ await Promise.allSettled([...new Set([...Object.values(sessions), officialWalk, officialSitstand, officialRoll, customPolicy?.session])]
+ .filter(Boolean).map((session) => session.release()));
+ for (const variant of Object.values(locos)) {
+ variant.data.delete();
+ variant.model.delete();
+ }
+ vfs.delete();
},
setLineColor: (name) => setArenaLineColor([grid.material, ...wallMats], name),
setVariant: (name) => {
diff --git a/sandbox/src/platform/loader/SchemaValidator.js b/sandbox/src/platform/loader/SchemaValidator.js
index b7b65b0..da0e52f 100644
--- a/sandbox/src/platform/loader/SchemaValidator.js
+++ b/sandbox/src/platform/loader/SchemaValidator.js
@@ -147,8 +147,8 @@ export function validatePackage(config) {
!term.group
)
throw new Error(`${term.type}: group required`);
- if (term.type === "gyro" && !term.sensor)
- throw new Error("gyro: sensor required");
+ if (["gyro", "linear_velocity"].includes(term.type) && !term.sensor)
+ throw new Error(`${term.type}: sensor required`);
if (term.type === "projected_gravity" && !term.body)
throw new Error("projected_gravity: body required");
if (
diff --git a/sandbox/src/platform/loader/robot.schema.json b/sandbox/src/platform/loader/robot.schema.json
index 2b798fa..e769d44 100644
--- a/sandbox/src/platform/loader/robot.schema.json
+++ b/sandbox/src/platform/loader/robot.schema.json
@@ -182,6 +182,7 @@
"type": {
"enum": [
"gyro",
+ "linear_velocity",
"projected_gravity",
"joint_pos_rel",
"joint_vel",
diff --git a/sandbox/src/platform/policy/ObservationPipeline.js b/sandbox/src/platform/policy/ObservationPipeline.js
index 155372f..6029f2f 100644
--- a/sandbox/src/platform/policy/ObservationPipeline.js
+++ b/sandbox/src/platform/policy/ObservationPipeline.js
@@ -15,7 +15,7 @@ export class ObservationPipeline {
const implementation = registry.get(term.type),
size = implementation.size(term, ctx, names);
let sensor, body;
- if (term.type === "gyro") {
+ if (["gyro", "linear_velocity"].includes(term.type)) {
const id = ctx.sim.mujoco.mj_name2id(
ctx.sim.model,
ctx.sim.mujoco.mjtObj.mjOBJ_SENSOR.value,
@@ -31,7 +31,7 @@ export class ObservationPipeline {
};
if (sensor.dim !== 3)
throw new Error(
- `observations.${name}: gyro ${term.sensor} must have dimension 3`,
+ `observations.${name}: ${term.type} ${term.sensor} must have dimension 3`,
);
}
if (term.type === "projected_gravity") {
diff --git a/sandbox/src/platform/policy/TermRegistry.js b/sandbox/src/platform/policy/TermRegistry.js
index 5d88889..235942a 100644
--- a/sandbox/src/platform/policy/TermRegistry.js
+++ b/sandbox/src/platform/policy/TermRegistry.js
@@ -33,6 +33,8 @@ observationTerms.register("gyro", {
out[offset + i] = c.sim.data.sensordata[op.sensorAdr + i];
},
});
+// Velocity sensors and gyroscopes both expose three body-frame components.
+observationTerms.register("linear_velocity", observationTerms.get("gyro"));
observationTerms.register("projected_gravity", {
size: () => 3,
write: (out, offset, c, op) => {
diff --git a/sandbox/src/platform/policy/controllers/OnnxPolicy.js b/sandbox/src/platform/policy/controllers/OnnxPolicy.js
index b254611..407f382 100644
--- a/sandbox/src/platform/policy/controllers/OnnxPolicy.js
+++ b/sandbox/src/platform/policy/controllers/OnnxPolicy.js
@@ -4,8 +4,8 @@ import { OnnxController } from "./OnnxController.js";
// Common lifecycle for independently trained, feed-forward joint-target skills.
export class OnnxPolicy {
- static async load(ort, bytes, config, shared, skill, reference = null) {
- let session;
+ static async load(ort, bytes, config, shared, skill, reference = null, preparedSession = null) {
+ let session = preparedSession;
try {
const ctx = {
...shared,
@@ -21,7 +21,7 @@ export class OnnxPolicy {
ctx,
);
const actions = new ActionPipeline(skill.actions ?? config.actions, ctx);
- session = await ort.InferenceSession.create(bytes, {
+ session ??= await ort.InferenceSession.create(bytes, {
executionProviders: ["wasm"],
});
const controller = new OnnxController(ort, session, obs, actions.size);
diff --git a/sandbox/src/platform/runtime/RobotRuntime.js b/sandbox/src/platform/runtime/RobotRuntime.js
index 8f71296..c892958 100644
--- a/sandbox/src/platform/runtime/RobotRuntime.js
+++ b/sandbox/src/platform/runtime/RobotRuntime.js
@@ -25,10 +25,9 @@ export class RobotRuntime {
config = structuredClone(pkg.config),
{ mujoco, ort } = await loadRuntimes();
const warnings = [...(pkg.warnings ?? [])];
- let sim, rig, worldPresentation;
+ let sim, rig, worldPresentation, primarySession;
const policies = new Map();
try {
- sim = await SimCore.load(mujoco, pkg, world);
const primary = config.skills.find((s) => s.kind === "primary");
if (primary.controller.type !== "onnx")
throw new Error("Primary controller must be ONNX");
@@ -36,8 +35,12 @@ export class RobotRuntime {
pkg.asset(primary.controller.policy),
"bytes",
);
- const metadata = readOnnxMetadata(bytes),
- names = [...sim.joints.keys()];
+ const metadata = readOnnxMetadata(bytes);
+ // Initialize ONNX before compiling the full physical model/visuals. Its
+ // WASM startup used to compete with both decoded meshes and VFS copies.
+ primarySession = await ort.InferenceSession.create(bytes, { executionProviders: ['wasm'] });
+ sim = await SimCore.load(mujoco, pkg, world);
+ const names = [...sim.joints.keys()];
const values =
config.joints.source === "onnx_metadata"
? resolveJointDefaults(metadata, names)
@@ -79,6 +82,8 @@ export class RobotRuntime {
config.sim.timestep * config.sim.decimation,
)
: null;
+ const preparedSession = skill === primary ? primarySession : null;
+ if (preparedSession) primarySession = null; // OnnxPolicy now owns it, including errors.
policies.set(
skill.id,
await OnnxPolicy.load(
@@ -88,6 +93,7 @@ export class RobotRuntime {
shared,
skill,
reference,
+ preparedSession,
),
);
} catch (error) {
@@ -122,7 +128,10 @@ export class RobotRuntime {
} catch (error) {
worldPresentation?.dispose();
rig?.dispose();
- await Promise.allSettled([...policies.values()].map((p) => p.dispose()));
+ await Promise.allSettled([
+ ...[...policies.values()].map((p) => p.dispose()),
+ primarySession?.release(),
+ ]);
sim?.dispose();
throw error;
}
diff --git a/sandbox/src/platform/runtime/runtimes.js b/sandbox/src/platform/runtime/runtimes.js
index 807ff3c..8f40fde 100644
--- a/sandbox/src/platform/runtime/runtimes.js
+++ b/sandbox/src/platform/runtime/runtimes.js
@@ -1,6 +1,6 @@
import mujocoWasmUrl from "@mujoco/mujoco/mujoco.wasm?url";
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.wasm?url";
-import ortRuntimeUrl from 'onnxruntime-web/wasm?url';
+import ortRuntimeUrl from 'virtual:make-ort-runtime-url';
let pending;
export function loadRuntimes() {
return (pending ??= (async () => {
diff --git a/sandbox/src/platform/runtime/session-loading.js b/sandbox/src/platform/runtime/session-loading.js
new file mode 100644
index 0000000..d5bba45
--- /dev/null
+++ b/sandbox/src/platform/runtime/session-loading.js
@@ -0,0 +1,35 @@
+// Creating several sessions at once temporarily retains several copies of the
+// models and allocator workspaces. Keep every declared action, but load one at
+// a time and roll back all sessions if startup fails.
+export async function loadSessionsSequentially(entries, create, validate = async () => {}, progress = () => {}) {
+ const sessions = {};
+ try {
+ for (const [id, source] of entries) {
+ const session = await create(source);
+ sessions[id] = session;
+ await validate(session);
+ progress(Object.keys(sessions).length, entries.length);
+ }
+ return sessions;
+ } catch (error) {
+ await Promise.allSettled(Object.values(sessions).map((s) => s.release()));
+ throw error;
+ }
+}
+
+// Drop the JS download buffer after copying each asset into MuJoCo's VFS,
+// instead of retaining a second complete copy of the package during compile.
+export async function populateVfs(vfs, assets, fetchBytes, concurrency = 2) {
+ let next = 0, failure;
+ await Promise.all(Array.from({ length: Math.min(concurrency, assets.length) }, async () => {
+ while (!failure && next < assets.length) {
+ const asset = assets[next++];
+ try {
+ const bytes = await fetchBytes(asset);
+ if (!failure) vfs.addBuffer(asset.vfs, new Uint8Array(bytes));
+ } catch (error) { failure ??= error; }
+ }
+ }));
+ // All outstanding downloads have settled before the caller can delete VFS.
+ if (failure) throw failure;
+}
diff --git a/sandbox/src/platform/sim/SceneComposer.js b/sandbox/src/platform/sim/SceneComposer.js
index ca1e844..2e334ae 100644
--- a/sandbox/src/platform/sim/SceneComposer.js
+++ b/sandbox/src/platform/sim/SceneComposer.js
@@ -23,6 +23,10 @@ export function composeScene(xml, config, world, interactiveProps = []) {
name: "platform_floor",
type: "plane",
size: "0 0 0.05",
+ // Uploaded models may make geoms visual-only by default (e.g. Apollo).
+ contype: "1",
+ conaffinity: "1",
+ group: "0",
rgba: world.floor.rgba.join(" "),
friction: world.floor.friction.join(" "),
}))
diff --git a/sandbox/src/platform/sim/SimCore.js b/sandbox/src/platform/sim/SimCore.js
index 582a07b..8d0bfc6 100644
--- a/sandbox/src/platform/sim/SimCore.js
+++ b/sandbox/src/platform/sim/SimCore.js
@@ -2,6 +2,7 @@ import { sharedInteractiveProps } from "../../game/worlds/arena/session-environm
import { resolvePropAddresses, resetProp } from "../../game/interactive-props.js";
import { fetchChecked } from "../loader/PackageLoader.js";
import { composeScene } from "./SceneComposer.js";
+import { populateVfs } from '../runtime/session-loading.js';
export function resolveAddresses(mujoco, model, names) {
const joints = new Map();
for (const name of names) {
@@ -38,14 +39,7 @@ export class SimCore {
const vfs = new mujoco.MjVFS();
let model, data;
try {
- const buffers = new Array(pkg.config.assets.length);
- let next = 0;
- await Promise.all(Array.from({ length: Math.min(4, buffers.length) }, async () => {
- for (let i = next++; i < buffers.length; i = next++) buffers[i] = await fetchChecked(pkg.asset(pkg.config.assets[i].path), "bytes");
- }));
- pkg.config.assets.forEach((a, i) =>
- vfs.addBuffer(a.vfs, new Uint8Array(buffers[i])),
- );
+ await populateVfs(vfs, pkg.config.assets, (asset) => fetchChecked(pkg.asset(asset.path), 'bytes'));
const interactiveSpecs = sharedInteractiveProps(world);
const xml = composeScene(
await fetchChecked(pkg.asset(pkg.config.model)),
diff --git a/sandbox/test/fixtures/apollo/robot.json b/sandbox/test/fixtures/apollo/robot.json
new file mode 100644
index 0000000..704c307
--- /dev/null
+++ b/sandbox/test/fixtures/apollo/robot.json
@@ -0,0 +1,699 @@
+{
+ "schema": 1,
+ "id": "apollo",
+ "name": "Apptronik Apollo",
+ "family": "apollo",
+ "adapter": "generic",
+ "dimensions": {
+ "height": 1.73
+ },
+ "model": "model.xml",
+ "assets": [
+ {
+ "path": "assets/neck_mount_fix_link.stl",
+ "vfs": "assets/neck_mount_fix_link.stl"
+ },
+ {
+ "path": "assets/neck_yaw_link.stl",
+ "vfs": "assets/neck_yaw_link.stl"
+ },
+ {
+ "path": "assets/afh_2_1_link.stl",
+ "vfs": "assets/afh_2_1_link.stl"
+ },
+ {
+ "path": "assets/torso_link.stl",
+ "vfs": "assets/torso_link.stl"
+ },
+ {
+ "path": "assets/battery_mount_fix.stl",
+ "vfs": "assets/battery_mount_fix.stl"
+ },
+ {
+ "path": "assets/torso_pitch_link.stl",
+ "vfs": "assets/torso_pitch_link.stl"
+ },
+ {
+ "path": "assets/torso_roll_link.stl",
+ "vfs": "assets/torso_roll_link.stl"
+ },
+ {
+ "path": "assets/pelvis_link.stl",
+ "vfs": "assets/pelvis_link.stl"
+ },
+ {
+ "path": "assets/l_shoulder_aa_link.stl",
+ "vfs": "assets/l_shoulder_aa_link.stl"
+ },
+ {
+ "path": "assets/l_shoulder_ie_link.stl",
+ "vfs": "assets/l_shoulder_ie_link.stl"
+ },
+ {
+ "path": "assets/l_shoulder_fe_link.stl",
+ "vfs": "assets/l_shoulder_fe_link.stl"
+ },
+ {
+ "path": "assets/l_elbow_fe_link.stl",
+ "vfs": "assets/l_elbow_fe_link.stl"
+ },
+ {
+ "path": "assets/l_wrist_roll_link.stl",
+ "vfs": "assets/l_wrist_roll_link.stl"
+ },
+ {
+ "path": "assets/l_wrist_yaw_link.stl",
+ "vfs": "assets/l_wrist_yaw_link.stl"
+ },
+ {
+ "path": "assets/l_wrist_pitch_link.stl",
+ "vfs": "assets/l_wrist_pitch_link.stl"
+ },
+ {
+ "path": "assets/ability_hand/wrist_adapter.STL",
+ "vfs": "assets/ability_hand/wrist_adapter.STL"
+ },
+ {
+ "path": "assets/ability_hand/wristmesh.STL",
+ "vfs": "assets/ability_hand/wristmesh.STL"
+ },
+ {
+ "path": "assets/ability_hand/FB_palm_ref.STL",
+ "vfs": "assets/ability_hand/FB_palm_ref.STL"
+ },
+ {
+ "path": "assets/ability_hand/idx-F1.STL",
+ "vfs": "assets/ability_hand/idx-F1.STL"
+ },
+ {
+ "path": "assets/ability_hand/idx-F2.STL",
+ "vfs": "assets/ability_hand/idx-F2.STL"
+ },
+ {
+ "path": "assets/ability_hand/thumb-F1.STL",
+ "vfs": "assets/ability_hand/thumb-F1.STL"
+ },
+ {
+ "path": "assets/ability_hand/thumb-F2-left.STL",
+ "vfs": "assets/ability_hand/thumb-F2-left.STL"
+ },
+ {
+ "path": "assets/r_shoulder_aa_link.stl",
+ "vfs": "assets/r_shoulder_aa_link.stl"
+ },
+ {
+ "path": "assets/r_shoulder_ie_link.stl",
+ "vfs": "assets/r_shoulder_ie_link.stl"
+ },
+ {
+ "path": "assets/r_shoulder_fe_link.stl",
+ "vfs": "assets/r_shoulder_fe_link.stl"
+ },
+ {
+ "path": "assets/r_elbow_fe_link.stl",
+ "vfs": "assets/r_elbow_fe_link.stl"
+ },
+ {
+ "path": "assets/r_wrist_roll_link.stl",
+ "vfs": "assets/r_wrist_roll_link.stl"
+ },
+ {
+ "path": "assets/r_wrist_yaw_link.stl",
+ "vfs": "assets/r_wrist_yaw_link.stl"
+ },
+ {
+ "path": "assets/r_wrist_pitch_link.stl",
+ "vfs": "assets/r_wrist_pitch_link.stl"
+ },
+ {
+ "path": "assets/ability_hand/FB_palm_ref_MIR.STL",
+ "vfs": "assets/ability_hand/FB_palm_ref_MIR.STL"
+ },
+ {
+ "path": "assets/ability_hand/thumb-F1-MIR.STL",
+ "vfs": "assets/ability_hand/thumb-F1-MIR.STL"
+ },
+ {
+ "path": "assets/ability_hand/thumb-F2-right.STL",
+ "vfs": "assets/ability_hand/thumb-F2-right.STL"
+ },
+ {
+ "path": "assets/l_hip_ie_link.stl",
+ "vfs": "assets/l_hip_ie_link.stl"
+ },
+ {
+ "path": "assets/l_hip_aa_link.stl",
+ "vfs": "assets/l_hip_aa_link.stl"
+ },
+ {
+ "path": "assets/l_hip_fe_link.stl",
+ "vfs": "assets/l_hip_fe_link.stl"
+ },
+ {
+ "path": "assets/l_knee_fe_link.stl",
+ "vfs": "assets/l_knee_fe_link.stl"
+ },
+ {
+ "path": "assets/l_ankle_ie_link.stl",
+ "vfs": "assets/l_ankle_ie_link.stl"
+ },
+ {
+ "path": "assets/l_foot_link.stl",
+ "vfs": "assets/l_foot_link.stl"
+ },
+ {
+ "path": "assets/r_hip_ie_link.stl",
+ "vfs": "assets/r_hip_ie_link.stl"
+ },
+ {
+ "path": "assets/r_hip_aa_link.stl",
+ "vfs": "assets/r_hip_aa_link.stl"
+ },
+ {
+ "path": "assets/r_hip_fe_link.stl",
+ "vfs": "assets/r_hip_fe_link.stl"
+ },
+ {
+ "path": "assets/r_knee_fe_link.stl",
+ "vfs": "assets/r_knee_fe_link.stl"
+ },
+ {
+ "path": "assets/r_ankle_ie_link.stl",
+ "vfs": "assets/r_ankle_ie_link.stl"
+ },
+ {
+ "path": "assets/r_foot_link.stl",
+ "vfs": "assets/r_foot_link.stl"
+ }
+ ],
+ "base": {
+ "type": "floating",
+ "root_body": "base_link",
+ "freejoint": "floating_base",
+ "spawn": {
+ "pos": [
+ 0,
+ 0,
+ 1.1008384999999998
+ ],
+ "yaw": 0
+ }
+ },
+ "sim": {
+ "timestep": 0.005,
+ "decimation": 4
+ },
+ "joints": {
+ "groups": {
+ "policy": [
+ "torso_yaw",
+ "torso_roll",
+ "torso_pitch",
+ "neck_yaw",
+ "neck_roll",
+ "neck_pitch",
+ "l_shoulder_aa",
+ "l_shoulder_ie",
+ "l_shoulder_fe",
+ "l_elbow_fe",
+ "l_wrist_roll",
+ "l_wrist_yaw",
+ "l_wrist_pitch",
+ "r_shoulder_aa",
+ "r_shoulder_ie",
+ "r_shoulder_fe",
+ "r_elbow_fe",
+ "r_wrist_roll",
+ "r_wrist_yaw",
+ "r_wrist_pitch",
+ "l_hip_ie",
+ "l_hip_aa",
+ "l_hip_fe",
+ "l_knee_fe",
+ "l_ankle_ie",
+ "l_ankle_pd",
+ "r_hip_ie",
+ "r_hip_aa",
+ "r_hip_fe",
+ "r_knee_fe",
+ "r_ankle_ie",
+ "r_ankle_pd"
+ ],
+ "torso_yaw": [
+ "torso_yaw"
+ ],
+ "torso_roll": [
+ "torso_roll"
+ ],
+ "torso_pitch": [
+ "torso_pitch"
+ ],
+ "neck_yaw": [
+ "neck_yaw"
+ ],
+ "neck_roll": [
+ "neck_roll"
+ ],
+ "neck_pitch": [
+ "neck_pitch"
+ ],
+ "l_shoulder_aa": [
+ "l_shoulder_aa"
+ ],
+ "l_shoulder_ie": [
+ "l_shoulder_ie"
+ ],
+ "l_shoulder_fe": [
+ "l_shoulder_fe"
+ ],
+ "l_elbow_fe": [
+ "l_elbow_fe"
+ ],
+ "l_wrist_roll": [
+ "l_wrist_roll"
+ ],
+ "l_wrist_yaw": [
+ "l_wrist_yaw"
+ ],
+ "l_wrist_pitch": [
+ "l_wrist_pitch"
+ ],
+ "r_shoulder_aa": [
+ "r_shoulder_aa"
+ ],
+ "r_shoulder_ie": [
+ "r_shoulder_ie"
+ ],
+ "r_shoulder_fe": [
+ "r_shoulder_fe"
+ ],
+ "r_elbow_fe": [
+ "r_elbow_fe"
+ ],
+ "r_wrist_roll": [
+ "r_wrist_roll"
+ ],
+ "r_wrist_yaw": [
+ "r_wrist_yaw"
+ ],
+ "r_wrist_pitch": [
+ "r_wrist_pitch"
+ ],
+ "l_hip_ie": [
+ "l_hip_ie"
+ ],
+ "l_hip_aa": [
+ "l_hip_aa"
+ ],
+ "l_hip_fe": [
+ "l_hip_fe"
+ ],
+ "l_knee_fe": [
+ "l_knee_fe"
+ ],
+ "l_ankle_ie": [
+ "l_ankle_ie"
+ ],
+ "l_ankle_pd": [
+ "l_ankle_pd"
+ ],
+ "r_hip_ie": [
+ "r_hip_ie"
+ ],
+ "r_hip_aa": [
+ "r_hip_aa"
+ ],
+ "r_hip_fe": [
+ "r_hip_fe"
+ ],
+ "r_knee_fe": [
+ "r_knee_fe"
+ ],
+ "r_ankle_ie": [
+ "r_ankle_ie"
+ ],
+ "r_ankle_pd": [
+ "r_ankle_pd"
+ ]
+ },
+ "defaults": {
+ "torso_yaw": 0.0,
+ "torso_roll": 0.0,
+ "torso_pitch": 0.0,
+ "neck_yaw": 0.0,
+ "neck_roll": 0.0,
+ "neck_pitch": 0.0,
+ "l_shoulder_aa": 0.15,
+ "l_shoulder_ie": 0.0,
+ "l_shoulder_fe": 0.05,
+ "l_elbow_fe": -0.25,
+ "l_wrist_roll": 0.0,
+ "l_wrist_yaw": 0.0,
+ "l_wrist_pitch": 0.0,
+ "r_shoulder_aa": -0.15,
+ "r_shoulder_ie": 0.0,
+ "r_shoulder_fe": 0.05,
+ "r_elbow_fe": -0.25,
+ "r_wrist_roll": 0.0,
+ "r_wrist_yaw": 0.0,
+ "r_wrist_pitch": 0.0,
+ "l_hip_ie": 0.01516856,
+ "l_hip_aa": 0.04179601,
+ "l_hip_fe": -0.15749093,
+ "l_knee_fe": 0.35,
+ "l_ankle_ie": -0.03606629,
+ "l_ankle_pd": -0.18624892,
+ "r_hip_ie": -0.01516856,
+ "r_hip_aa": -0.04179601,
+ "r_hip_fe": -0.15749093,
+ "r_knee_fe": 0.35,
+ "r_ankle_ie": 0.03606629,
+ "r_ankle_pd": -0.18624892
+ }
+ },
+ "observations": {
+ "obs": {
+ "terms": [
+ {
+ "type": "linear_velocity",
+ "sensor": "imu_lin_vel"
+ },
+ {
+ "type": "gyro",
+ "sensor": "imu_ang_vel"
+ },
+ {
+ "type": "projected_gravity",
+ "body": "base_link"
+ },
+ {
+ "type": "joint_pos_rel",
+ "group": "policy"
+ },
+ {
+ "type": "joint_vel",
+ "group": "policy"
+ },
+ {
+ "type": "last_action",
+ "group": "policy"
+ },
+ {
+ "type": "command",
+ "size": 3
+ }
+ ]
+ }
+ },
+ "actions": [
+ {
+ "type": "joint_position",
+ "group": "torso_yaw",
+ "scale": 0.08,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "torso_roll",
+ "scale": 0.08,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "torso_pitch",
+ "scale": 0.08,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "neck_yaw",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "neck_roll",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "neck_pitch",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_shoulder_aa",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_shoulder_ie",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_shoulder_fe",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_elbow_fe",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_wrist_roll",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_wrist_yaw",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_wrist_pitch",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_shoulder_aa",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_shoulder_ie",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_shoulder_fe",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_elbow_fe",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_wrist_roll",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_wrist_yaw",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_wrist_pitch",
+ "scale": 0.0,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_hip_ie",
+ "scale": 0.2,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_hip_aa",
+ "scale": 0.2,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_hip_fe",
+ "scale": 0.3,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_knee_fe",
+ "scale": 0.4,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_ankle_ie",
+ "scale": 0.15,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "l_ankle_pd",
+ "scale": 0.2,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_hip_ie",
+ "scale": 0.2,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_hip_aa",
+ "scale": 0.2,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_hip_fe",
+ "scale": 0.3,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_knee_fe",
+ "scale": 0.4,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_ankle_ie",
+ "scale": 0.15,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "r_ankle_pd",
+ "scale": 0.2,
+ "offset": "default"
+ }
+ ],
+ "actuation": {
+ "type": "native_position"
+ },
+ "commands": {
+ "size": 3,
+ "limits": [
+ 0.5,
+ -0.3,
+ 0.4
+ ]
+ },
+ "skills": [
+ {
+ "id": "walk",
+ "kind": "primary",
+ "owns": "policy",
+ "controller": {
+ "type": "onnx",
+ "policy": "policies/walk.onnx"
+ }
+ }
+ ],
+ "input": {
+ "bindings": [
+ {
+ "action": "move_forward",
+ "codes": [
+ "KeyW",
+ "ArrowUp"
+ ],
+ "label": "Forward"
+ },
+ {
+ "action": "move_backward",
+ "codes": [
+ "KeyS",
+ "ArrowDown"
+ ],
+ "label": "Backward"
+ },
+ {
+ "action": "turn_left",
+ "codes": [
+ "KeyA",
+ "ArrowLeft"
+ ],
+ "label": "Turn left"
+ },
+ {
+ "action": "turn_right",
+ "codes": [
+ "KeyD",
+ "ArrowRight"
+ ],
+ "label": "Turn right"
+ },
+ {
+ "action": "reset",
+ "codes": [
+ "Space"
+ ],
+ "label": "Reset"
+ },
+ {
+ "action": "pause",
+ "codes": [
+ "Escape"
+ ],
+ "label": "Pause / continue"
+ },
+ {
+ "action": "chaseToggle",
+ "codes": [
+ "KeyC"
+ ],
+ "label": "Restore chase camera"
+ }
+ ]
+ },
+ "render": {
+ "source": "mjcf_visual",
+ "groups": [
+ 1
+ ],
+ "camera": {
+ "distance": 3.5
+ }
+ },
+ "presentation": {
+ "theme": "comic"
+ },
+ "termination": {
+ "tilt_z": -0.5,
+ "min_height": 0.98,
+ "on_fall": "hold"
+ },
+ "license": "See LICENSES/apollo.txt and LICENSES/mjlab.txt; policy is locally trained."
+}
diff --git a/sandbox/test/fixtures/t1/robot.json b/sandbox/test/fixtures/t1/robot.json
new file mode 100644
index 0000000..a9d7000
--- /dev/null
+++ b/sandbox/test/fixtures/t1/robot.json
@@ -0,0 +1,524 @@
+{
+ "schema": 1,
+ "id": "t1",
+ "name": "Booster T1",
+ "family": "t1",
+ "adapter": "generic",
+ "dimensions": {
+ "height": 1.18
+ },
+ "model": "model.xml",
+ "assets": [
+ {
+ "path": "meshes/Trunk.STL",
+ "vfs": "meshes/Trunk.STL"
+ },
+ {
+ "path": "meshes/H1.STL",
+ "vfs": "meshes/H1.STL"
+ },
+ {
+ "path": "meshes/H2.STL",
+ "vfs": "meshes/H2.STL"
+ },
+ {
+ "path": "meshes/AL1.STL",
+ "vfs": "meshes/AL1.STL"
+ },
+ {
+ "path": "meshes/AL2.STL",
+ "vfs": "meshes/AL2.STL"
+ },
+ {
+ "path": "meshes/AL3.STL",
+ "vfs": "meshes/AL3.STL"
+ },
+ {
+ "path": "meshes/left_hand_link.STL",
+ "vfs": "meshes/left_hand_link.STL"
+ },
+ {
+ "path": "meshes/AR1.STL",
+ "vfs": "meshes/AR1.STL"
+ },
+ {
+ "path": "meshes/AR2.STL",
+ "vfs": "meshes/AR2.STL"
+ },
+ {
+ "path": "meshes/AR3.STL",
+ "vfs": "meshes/AR3.STL"
+ },
+ {
+ "path": "meshes/right_hand_link.STL",
+ "vfs": "meshes/right_hand_link.STL"
+ },
+ {
+ "path": "meshes/Waist.STL",
+ "vfs": "meshes/Waist.STL"
+ },
+ {
+ "path": "meshes/Hip_Pitch_Left.STL",
+ "vfs": "meshes/Hip_Pitch_Left.STL"
+ },
+ {
+ "path": "meshes/Hip_Roll_Left.STL",
+ "vfs": "meshes/Hip_Roll_Left.STL"
+ },
+ {
+ "path": "meshes/Hip_Yaw_Left.STL",
+ "vfs": "meshes/Hip_Yaw_Left.STL"
+ },
+ {
+ "path": "meshes/Shank_Left.STL",
+ "vfs": "meshes/Shank_Left.STL"
+ },
+ {
+ "path": "meshes/Ankle_Cross_Left.STL",
+ "vfs": "meshes/Ankle_Cross_Left.STL"
+ },
+ {
+ "path": "meshes/left_foot_link.STL",
+ "vfs": "meshes/left_foot_link.STL"
+ },
+ {
+ "path": "meshes/Hip_Pitch_Right.STL",
+ "vfs": "meshes/Hip_Pitch_Right.STL"
+ },
+ {
+ "path": "meshes/Hip_Roll_Right.STL",
+ "vfs": "meshes/Hip_Roll_Right.STL"
+ },
+ {
+ "path": "meshes/Hip_Yaw_Right.STL",
+ "vfs": "meshes/Hip_Yaw_Right.STL"
+ },
+ {
+ "path": "meshes/Shank_Right.STL",
+ "vfs": "meshes/Shank_Right.STL"
+ },
+ {
+ "path": "meshes/Ankle_Cross_Right.STL",
+ "vfs": "meshes/Ankle_Cross_Right.STL"
+ },
+ {
+ "path": "meshes/right_foot_link.STL",
+ "vfs": "meshes/right_foot_link.STL"
+ },
+ {
+ "path": "meshes/Logo.STL",
+ "vfs": "meshes/Logo.STL"
+ }
+ ],
+ "base": {
+ "type": "floating",
+ "root_body": "trunk",
+ "freejoint": "world_joint",
+ "spawn": {
+ "pos": [
+ 0,
+ 0,
+ 0.6811
+ ],
+ "yaw": 0
+ }
+ },
+ "sim": {
+ "timestep": 0.005,
+ "decimation": 4
+ },
+ "joints": {
+ "groups": {
+ "policy": [
+ "aahead_yaw_joint",
+ "aahead_pitch_joint",
+ "left_shoulder_pitch_joint",
+ "left_shoulder_roll_joint",
+ "left_elbow_pitch_joint",
+ "left_elbow_yaw_joint",
+ "right_shoulder_pitch_joint",
+ "right_shoulder_roll_joint",
+ "right_elbow_pitch_joint",
+ "right_elbow_yaw_joint",
+ "waist_yaw_joint",
+ "left_hip_pitch_joint",
+ "left_hip_roll_joint",
+ "left_hip_yaw_joint",
+ "left_knee_pitch_joint",
+ "left_ankle_pitch_joint",
+ "left_ankle_roll_joint",
+ "right_hip_pitch_joint",
+ "right_hip_roll_joint",
+ "right_hip_yaw_joint",
+ "right_knee_pitch_joint",
+ "right_ankle_pitch_joint",
+ "right_ankle_roll_joint"
+ ],
+ "aahead_yaw_joint": [
+ "aahead_yaw_joint"
+ ],
+ "aahead_pitch_joint": [
+ "aahead_pitch_joint"
+ ],
+ "left_shoulder_pitch_joint": [
+ "left_shoulder_pitch_joint"
+ ],
+ "left_shoulder_roll_joint": [
+ "left_shoulder_roll_joint"
+ ],
+ "left_elbow_pitch_joint": [
+ "left_elbow_pitch_joint"
+ ],
+ "left_elbow_yaw_joint": [
+ "left_elbow_yaw_joint"
+ ],
+ "right_shoulder_pitch_joint": [
+ "right_shoulder_pitch_joint"
+ ],
+ "right_shoulder_roll_joint": [
+ "right_shoulder_roll_joint"
+ ],
+ "right_elbow_pitch_joint": [
+ "right_elbow_pitch_joint"
+ ],
+ "right_elbow_yaw_joint": [
+ "right_elbow_yaw_joint"
+ ],
+ "waist_yaw_joint": [
+ "waist_yaw_joint"
+ ],
+ "left_hip_pitch_joint": [
+ "left_hip_pitch_joint"
+ ],
+ "left_hip_roll_joint": [
+ "left_hip_roll_joint"
+ ],
+ "left_hip_yaw_joint": [
+ "left_hip_yaw_joint"
+ ],
+ "left_knee_pitch_joint": [
+ "left_knee_pitch_joint"
+ ],
+ "left_ankle_pitch_joint": [
+ "left_ankle_pitch_joint"
+ ],
+ "left_ankle_roll_joint": [
+ "left_ankle_roll_joint"
+ ],
+ "right_hip_pitch_joint": [
+ "right_hip_pitch_joint"
+ ],
+ "right_hip_roll_joint": [
+ "right_hip_roll_joint"
+ ],
+ "right_hip_yaw_joint": [
+ "right_hip_yaw_joint"
+ ],
+ "right_knee_pitch_joint": [
+ "right_knee_pitch_joint"
+ ],
+ "right_ankle_pitch_joint": [
+ "right_ankle_pitch_joint"
+ ],
+ "right_ankle_roll_joint": [
+ "right_ankle_roll_joint"
+ ]
+ },
+ "defaults": {
+ "aahead_yaw_joint": 0.0,
+ "aahead_pitch_joint": 0.0,
+ "left_shoulder_pitch_joint": 0.2,
+ "left_shoulder_roll_joint": -1.3,
+ "left_elbow_pitch_joint": 0.0,
+ "left_elbow_yaw_joint": -0.4,
+ "right_shoulder_pitch_joint": 0.2,
+ "right_shoulder_roll_joint": 1.3,
+ "right_elbow_pitch_joint": 0.0,
+ "right_elbow_yaw_joint": 0.4,
+ "waist_yaw_joint": 0.0,
+ "left_hip_pitch_joint": -0.2,
+ "left_hip_roll_joint": 0.0,
+ "left_hip_yaw_joint": 0.0,
+ "left_knee_pitch_joint": 0.4,
+ "left_ankle_pitch_joint": -0.2,
+ "left_ankle_roll_joint": 0.0,
+ "right_hip_pitch_joint": -0.2,
+ "right_hip_roll_joint": 0.0,
+ "right_hip_yaw_joint": 0.0,
+ "right_knee_pitch_joint": 0.4,
+ "right_ankle_pitch_joint": -0.2,
+ "right_ankle_roll_joint": 0.0
+ }
+ },
+ "observations": {
+ "obs": {
+ "terms": [
+ {
+ "type": "linear_velocity",
+ "sensor": "imu_lin_vel"
+ },
+ {
+ "type": "gyro",
+ "sensor": "imu_ang_vel"
+ },
+ {
+ "type": "projected_gravity",
+ "body": "trunk"
+ },
+ {
+ "type": "joint_pos_rel",
+ "group": "policy"
+ },
+ {
+ "type": "joint_vel",
+ "group": "policy"
+ },
+ {
+ "type": "last_action",
+ "group": "policy"
+ },
+ {
+ "type": "command",
+ "size": 3
+ }
+ ]
+ }
+ },
+ "actions": [
+ {
+ "type": "joint_position",
+ "group": "aahead_yaw_joint",
+ "scale": 0.35,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "aahead_pitch_joint",
+ "scale": 0.35,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_shoulder_pitch_joint",
+ "scale": 0.23937499999999998,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_shoulder_roll_joint",
+ "scale": 0.23937499999999998,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_elbow_pitch_joint",
+ "scale": 0.23937499999999998,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_elbow_yaw_joint",
+ "scale": 0.23937499999999998,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_shoulder_pitch_joint",
+ "scale": 0.23937499999999998,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_shoulder_roll_joint",
+ "scale": 0.23937499999999998,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_elbow_pitch_joint",
+ "scale": 0.23937499999999998,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_elbow_yaw_joint",
+ "scale": 0.23937499999999998,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "waist_yaw_joint",
+ "scale": 0.17,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_hip_pitch_joint",
+ "scale": 0.1235,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_hip_roll_joint",
+ "scale": 0.11333333333333333,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_hip_yaw_joint",
+ "scale": 0.17,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_knee_pitch_joint",
+ "scale": 0.163125,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_ankle_pitch_joint",
+ "scale": 0.3655,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "left_ankle_roll_joint",
+ "scale": 0.215,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_hip_pitch_joint",
+ "scale": 0.1235,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_hip_roll_joint",
+ "scale": 0.11333333333333333,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_hip_yaw_joint",
+ "scale": 0.17,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_knee_pitch_joint",
+ "scale": 0.163125,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_ankle_pitch_joint",
+ "scale": 0.3655,
+ "offset": "default"
+ },
+ {
+ "type": "joint_position",
+ "group": "right_ankle_roll_joint",
+ "scale": 0.215,
+ "offset": "default"
+ }
+ ],
+ "actuation": {
+ "type": "native_position"
+ },
+ "commands": {
+ "size": 3,
+ "limits": [
+ 0.6,
+ -0.4,
+ 0.6
+ ]
+ },
+ "skills": [
+ {
+ "id": "walk",
+ "kind": "primary",
+ "owns": "policy",
+ "controller": {
+ "type": "onnx",
+ "policy": "policies/walk.onnx"
+ }
+ }
+ ],
+ "input": {
+ "bindings": [
+ {
+ "action": "move_forward",
+ "codes": [
+ "KeyW",
+ "ArrowUp"
+ ],
+ "label": "Forward"
+ },
+ {
+ "action": "move_backward",
+ "codes": [
+ "KeyS",
+ "ArrowDown"
+ ],
+ "label": "Backward"
+ },
+ {
+ "action": "turn_left",
+ "codes": [
+ "KeyA",
+ "ArrowLeft"
+ ],
+ "label": "Turn left"
+ },
+ {
+ "action": "turn_right",
+ "codes": [
+ "KeyD",
+ "ArrowRight"
+ ],
+ "label": "Turn right"
+ },
+ {
+ "action": "reset",
+ "codes": [
+ "Space"
+ ],
+ "label": "Reset"
+ },
+ {
+ "action": "pause",
+ "codes": [
+ "Escape"
+ ],
+ "label": "Pause / continue"
+ },
+ {
+ "action": "chaseToggle",
+ "codes": [
+ "KeyC"
+ ],
+ "label": "Restore chase camera"
+ }
+ ]
+ },
+ "render": {
+ "source": "mjcf_visual",
+ "groups": [
+ 1
+ ],
+ "camera": {
+ "distance": 2.5
+ }
+ },
+ "presentation": {
+ "theme": "comic"
+ },
+ "termination": {
+ "tilt_z": -0.5,
+ "min_height": 0.42,
+ "on_fall": "hold"
+ },
+ "license": "See LICENSES/booster-assets.txt and LICENSES/mjlab.txt; policy is locally trained."
+}
diff --git a/sandbox/test/new-robot-packages.test.js b/sandbox/test/new-robot-packages.test.js
new file mode 100644
index 0000000..a17453e
--- /dev/null
+++ b/sandbox/test/new-robot-packages.test.js
@@ -0,0 +1,23 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { validatePackage } from '../src/platform/loader/SchemaValidator.js';
+import { resourceIndex, validateRobotResources } from '../../js/project-resources.js';
+
+for (const [id, joints, meshes] of [['t1', 23, 25], ['apollo', 32, 44]]) {
+ const fixture = JSON.parse(readFileSync(new URL(`./fixtures/${id}/robot.json`, import.meta.url)));
+ test(`${id}: uploaded package accepts velocity observations and only requires its walk policy`, () => {
+ const config = validatePackage(structuredClone(fixture));
+ assert.equal(config.joints.groups.policy.length, joints);
+ assert.equal(config.assets.length, meshes);
+ const paths = ['robot.json', config.model, ...config.assets.map(a => a.path), 'policies/walk.onnx'];
+ const resources = resourceIndex(paths.map((path, i) => ({ relativePath: `batch/${path}`, sizeBytes: 100, url: `https://cdn.example/file-${i}` })));
+ const packet = validateRobotResources(config, 'batch/robot.json', resources);
+ assert.deepEqual(packet.capabilities, [{ id: 'walk', skillId: 'walk' }]);
+ assert.deepEqual(packet.warnings, []);
+ resources.delete('batch/policies/walk.onnx');
+ assert.throws(() => validateRobotResources(config, 'batch/robot.json', resources), /缺少文件/);
+ delete config.observations.obs.terms.find(t => t.type === 'linear_velocity').sensor;
+ assert.throws(() => validatePackage(config), /linear_velocity: sensor required/);
+ });
+}
diff --git a/sandbox/test/ort-memory.test.js b/sandbox/test/ort-memory.test.js
new file mode 100644
index 0000000..8edba31
--- /dev/null
+++ b/sandbox/test/ort-memory.test.js
@@ -0,0 +1,19 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { boundedOrtSource, ORT_MAX_BYTES } from '../build/ort-memory.js';
+
+const original = readFileSync(new URL('../node_modules/onnxruntime-web/dist/ort.wasm.bundle.min.mjs', import.meta.url), 'utf8');
+
+test('allocator ceiling and growth agree; every other runtime byte is unchanged', () => {
+ const patched = boundedOrtSource(original);
+ assert.ok(patched.includes(`initial:256,maximum:${ORT_MAX_BYTES / 65536},shared:!0`));
+ assert.equal(patched.split(String(ORT_MAX_BYTES)).length - 1, 3);
+ assert.equal(patched.replace(`maximum:${ORT_MAX_BYTES / 65536}`, 'maximum:65536')
+ .replaceAll(String(ORT_MAX_BYTES), '4294901760'), original);
+});
+
+test('dependency or allocator changes stop the build rather than bypass the fix', () => {
+ assert.throws(() => boundedOrtSource(original.replace('initial:256', 'initial:512')), /upstream changed/);
+ assert.throws(() => boundedOrtSource(boundedOrtSource(original)), /upstream changed/);
+});
diff --git a/sandbox/test/policy-pipelines.test.js b/sandbox/test/policy-pipelines.test.js
index 18af2a4..4c798ae 100644
--- a/sandbox/test/policy-pipelines.test.js
+++ b/sandbox/test/policy-pipelines.test.js
@@ -93,6 +93,21 @@ test("observation order/frame/defaults/history use policy order, not model order
/missing/,
);
});
+test("linear velocity reads its own three-component sensor and rejects invalid bindings", () => {
+ const ctx = context();
+ ctx.sim.mujoco.mj_name2id = (_m, _type, name) => name === 'velocity' ? 1 : -1;
+ ctx.sim.model.sensor_adr = [0, 3];
+ ctx.sim.model.sensor_dim = [3, 3];
+ ctx.sim.data.sensordata = new Float64Array([9, 8, 7, 0.4, -0.2, 0.1]);
+ const spec = { obs: { terms: [{ type: 'linear_velocity', sensor: 'velocity' }] } };
+ const pipeline = new ObservationPipeline(spec, ctx);
+ assert.deepEqual(pipeline.write().obs, new Float32Array([0.4, -0.2, 0.1]));
+ ctx.sim.data.sensordata[3] = 0.6;
+ assert.ok(Math.abs(pipeline.write().obs[0] - 0.6) < 1e-6);
+ assert.throws(() => new ObservationPipeline({ obs: { terms: [{ type: 'linear_velocity', sensor: 'missing' }] } }, ctx), /missing sensor/);
+ ctx.sim.model.sensor_dim[1] = 1;
+ assert.throws(() => new ObservationPipeline(spec, ctx), /linear_velocity velocity must have dimension 3/);
+});
test("actions resolve named defaults and native ctrl order; invalid output is atomic", () => {
const ctx = context(),
p = new ActionPipeline([{ group: "policy", scale: 2 }], ctx);
diff --git a/sandbox/test/presentation-performance.test.js b/sandbox/test/presentation-performance.test.js
index 2663f63..0cb37f2 100644
--- a/sandbox/test/presentation-performance.test.js
+++ b/sandbox/test/presentation-performance.test.js
@@ -6,7 +6,6 @@ import { indexExactGeometry } from '../src/embed/index-geometry.js';
import { bindMovementWake } from '../src/embed/movement-wake.js';
import { InputRouter } from '../src/platform/input/InputRouter.js';
import { OnnxController } from '../src/platform/policy/controllers/OnnxController.js';
-import { simulationProfile, deviceProfile } from '../../js/render-budget.js';
test('display interpolation fills 50 Hz poses without mutating physics and handles quaternion sign', () => {
const history = new PoseHistory(20, [1]);
@@ -74,13 +73,3 @@ test('generic ONNX proxy does not detach observation pipeline buffers', async ()
await controller.run(); values[0]=4; await controller.run();
assert.deepEqual(seen,[[1,2],[4,2]]); assert.equal(values.byteLength,8);
});
-
-test('simulation limits pixels on phones without reducing the physics cadence', () => {
- for(const coarse of [true,false]) {
- const options={cores:8,memory:8,coarse,saveData:false};
- const profile=simulationProfile(options), previous=deviceProfile(options);
- assert.equal(profile.fps,coarse?30:60);
- assert.ok(profile.maxPixels
{
@@ -50,6 +50,46 @@ test('only sustained slow frames reduce quality, and degradation is bounded', ()
assert.ok(budget.maxDpr > 0 && budget.maxPixels > 0);
});
+test('model previews retain native resolution, antialiasing and shadows after sustained slow frames', () => {
+ for (const cores of [2, 8]) {
+ const options = { cores, memory: 0, coarse: true, saveData: false };
+ const profile = modelViewerProfile(options), budget = new RenderBudget(profile);
+ assert.equal(profile.antialias, true);
+ assert.equal(profile.shadows, true);
+ assert.equal(profile.fps, 30);
+ assert.equal(budget.pixelRatio(356, 320, 3), 3);
+ for (let i = 0; i < 300; i++) assert.equal(budget.observe(80, 60), false);
+ assert.equal(budget.level, 0);
+ assert.equal(budget.fps, 30);
+ assert.equal(budget.antialias, true);
+ // Device size and low performance must not silently change image quality.
+ for (const [w, h] of [[356, 320], [390, 844], [844, 390], [3840, 2160]]) {
+ const dpr = budget.pixelRatio(w, h, 3);
+ assert.equal(dpr, 3);
+ assert.equal(budget.shadows, true);
+ }
+ }
+});
+
+test('simulation keeps desktop quality on phones, tablets and constrained devices', () => {
+ const expected = simulationProfile({ cores: 8, memory: 8, coarse: false, saveData: false, compact: false });
+ for (const options of [
+ { cores: 2, memory: 2, coarse: true, saveData: true, compact: true },
+ { cores: 8, memory: 0, coarse: true, saveData: false, compact: false },
+ ]) {
+ const profile = simulationProfile(options), budget = new RenderBudget(profile);
+ assert.deepEqual(profile, expected);
+ assert.equal(profile.antialias, true);
+ assert.equal(profile.shadows, true);
+ assert.equal(profile.fps, 60);
+ assert.equal(budget.pixelRatio(390, 844, 3), 3);
+ assert.equal(budget.pixelRatio(1920, 1080, 2), 2);
+ for (let i = 0; i < 300; i++) assert.equal(budget.observe(80, 60), false);
+ assert.equal(budget.level, 0);
+ assert.equal(budget.pixelRatio(390, 844, 3), 3);
+ }
+});
+
test('static scenes stop scheduling; interactions, pause, resume and disposal work', () => {
let id = 0, rendered = 0, animate = false;
const pending = new Map();
diff --git a/sandbox/test/session-loading.test.js b/sandbox/test/session-loading.test.js
new file mode 100644
index 0000000..f481692
--- /dev/null
+++ b/sandbox/test/session-loading.test.js
@@ -0,0 +1,40 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { loadSessionsSequentially, populateVfs } from '../src/platform/runtime/session-loading.js';
+
+test('policy loading keeps every action, compiles one at a time and rolls back on failure', async () => {
+ let active = 0, peak = 0;
+ const released = [];
+ const create = async (id) => {
+ peak = Math.max(peak, ++active);
+ await new Promise((r) => setTimeout(r, 1));
+ active--;
+ return { id, release: async () => released.push(id) };
+ };
+ const entries = ['walk', 'sit', 'kick', 'roll'].map((id) => [id, id]);
+ const sessions = await loadSessionsSequentially(entries, create);
+ assert.deepEqual(Object.keys(sessions), entries.map(([id]) => id));
+ assert.equal(peak, 1);
+ assert.deepEqual(released, []);
+ await assert.rejects(loadSessionsSequentially(entries, create, async (s) => {
+ if (s.id === 'kick') throw new Error('validation failed');
+ }), /validation failed/);
+ assert.deepEqual(released.sort(), ['kick', 'sit', 'walk']);
+});
+
+test('VFS copies downloads incrementally; failure drains pending downloads before cleanup', async () => {
+ const added = [], assets = [1, 2, 3, 4].map((i) => ({ vfs: String(i) }));
+ await populateVfs({ addBuffer: (path, bytes) => added.push([path, [...bytes]]) }, assets,
+ async (a) => Uint8Array.of(Number(a.vfs)).buffer);
+ assert.deepEqual(added, assets.map((a) => [a.vfs, [Number(a.vfs)]]));
+ let pending = 0;
+ await assert.rejects(populateVfs({ addBuffer: () => assert.fail('no writes after failure') }, assets, async (a) => {
+ pending++;
+ try {
+ await new Promise((r) => setTimeout(r, a.vfs === '1' ? 1 : 15));
+ if (a.vfs === '1') throw new Error('aborted');
+ return new ArrayBuffer(1);
+ } finally { pending--; }
+ }), /aborted/);
+ assert.equal(pending, 0);
+});
diff --git a/sandbox/vite.config.js b/sandbox/vite.config.js
index 4664470..f0631a7 100644
--- a/sandbox/vite.config.js
+++ b/sandbox/vite.config.js
@@ -1,10 +1,11 @@
import { defineConfig } from 'vite';
import { copyFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
+import { ortMemoryPlugin } from './build/ort-memory.js';
export default defineConfig({
base: '/play/microduck/',
- plugins: [{
+ plugins: [ortMemoryPlugin(), {
name: 'preserve-upstream-notices',
closeBundle() {
for (const name of ['LICENSE', 'NOTICE', 'UPSTREAM.md']) copyFileSync(
diff --git a/sandbox/vite.robots.config.js b/sandbox/vite.robots.config.js
index 7cdcc56..db6436a 100644
--- a/sandbox/vite.robots.config.js
+++ b/sandbox/vite.robots.config.js
@@ -1,11 +1,12 @@
import { defineConfig } from 'vite';
import { copyFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
+import { ortMemoryPlugin } from './build/ort-memory.js';
export default defineConfig({
root: fileURLToPath(new URL('./robot-preview', import.meta.url)),
base: '/play/robots/',
publicDir: false,
- plugins: [{ name: 'platform-notices', closeBundle() {
+ plugins: [ortMemoryPlugin(), { name: 'platform-notices', closeBundle() {
for (const name of ['LICENSE', 'NOTICE', 'UPSTREAM-PLATFORM.md']) copyFileSync(
fileURLToPath(new URL(name, import.meta.url)), fileURLToPath(new URL(`../play/robots/${name}`, import.meta.url)));
} }],
diff --git a/scripts/assembly-motion.test.mjs b/scripts/assembly-motion.test.mjs
index a22bf25..907eec4 100644
--- a/scripts/assembly-motion.test.mjs
+++ b/scripts/assembly-motion.test.mjs
@@ -59,6 +59,16 @@ test('legacy tool direction is measured at the tip end cap including GLB node tr
shaft.geometry.dispose();
});
+test('GLB float32 scale rounding preserves final poses but real anisotropy is rejected', () => {
+ const source = raw();
+ source.parts[0].scale = [1.0000001343588858, 1.0000001343588858, 1.0000002687177536];
+ assert.deepEqual(validate(source).parts[0].scale, source.parts[0].scale);
+ for (const scale of [[1, 1.0001, 1], [.001, .00101, .001]]) {
+ source.parts[0].scale = scale;
+ assert.throws(() => validate(source), /等比缩放/);
+ }
+});
+
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();
@@ -84,7 +94,7 @@ test('reversed legacy tool faces the screw head, with its handle outside through
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);
+ const progress = i / 100, eased = progress ** 3 * (progress * (progress * 6 - 15) + 10);
transition.sample(m.approachDuration + m.engageDuration + progress * m.tightenDuration);
parent.updateMatrixWorld(true);
const tip = tool.localToWorld(new Vector3(...toolConfig.tipPosition));
diff --git a/scripts/build.mjs b/scripts/build.mjs
index 5935948..ddd16f1 100644
--- a/scripts/build.mjs
+++ b/scripts/build.mjs
@@ -1,4 +1,4 @@
-// 打包上线文件到 dist/,并生成 dist.zip(静态网站,直接放到网站根目录)。
+// 线上输出 dist/ + dist.zip;开发输出 dist-dev/ + dist-dev.zip,互不覆盖。
// 网站没有编译步骤,这里只挑出上线需要的文件,每个页面放进同名目录。
// 用法:node scripts/build.mjs [--env=dev]
import { cpSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
@@ -7,12 +7,20 @@ import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { compressRobot } from './meshes.mjs';
import { readCadEngine, copyCadEngine } from './cad-engine.mjs';
+import { versionSiteAssets } from './lib/version-site-assets.mjs';
const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
-const DIST = join(ROOT, 'dist');
-const CAD_ENGINE = existsSync(join(ROOT, 'cad/engine.json')) ? readCadEngine(join(ROOT, 'cad')) : null;
+const BUILD_ID = Date.now().toString(36);
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 IS_DEV = BUILD_ENV === 'dev';
+const OUTPUT_NAME = IS_DEV ? 'dist-dev' : 'dist';
+const DIST = join(ROOT, OUTPUT_NAME);
+const ARCHIVE_NAME = `${OUTPUT_NAME}.zip`;
+const TARGET_NAME = IS_DEV ? 'DEV 开发环境' : '线上正式环境';
+const FRONTEND = IS_DEV ? 'https://dev-vibemake.robotquan.com' : 'https://vibemake.robotquan.com';
+const API_BASE = IS_DEV ? 'https://dev-vibemake-api.robotquan.com/api' : 'https://vibemake-api.robotquan.com/api';
+const CAD_ENGINE = existsSync(join(ROOT, 'cad/engine.json')) ? readCadEngine(join(ROOT, 'cad')) : null;
const PCB_DIST = resolve(process.env.PCB_DIST || join(ROOT, '../ziro-designer-main/designer/dist'));
if (!existsSync(join(PCB_DIST, 'index.html')))
throw new Error(`PCB build not found at ${PCB_DIST}. Build ziro-designer-main/designer first, or set PCB_DIST.`);
@@ -59,11 +67,23 @@ for (const r of robots) {
writeFileSync(join(DIST, 'build-info.json'), JSON.stringify({
environment: BUILD_ENV,
+ deploymentTarget: IS_DEV ? 'dev' : 'production',
+ buildId: BUILD_ID,
builtAt: new Date().toISOString(),
- ...(BUILD_ENV === 'dev' ? { frontend: 'https://dev-vibemake.robotquan.com', apiBase: 'https://dev-vibemake-api.robotquan.com/api' } : {}),
+ frontend: FRONTEND,
+ apiBase: API_BASE,
+ archive: ARCHIVE_NAME,
}, null, 2) + '\n');
-writeFileSync(join(DIST, 'DEPLOY.md'), `# ${BUILD_ENV === 'dev' ? 'DEV 环境部署' : '部署'}
+writeFileSync(join(DIST, 'DEPLOY.md'), `# ${TARGET_NAME}部署
+
+- 上传文件:${ARCHIVE_NAME}
+- 目标网站:${FRONTEND}
+- 构建版本:${BUILD_ID}
+- 本地目录:${OUTPUT_NAME}/(两种环境分别输出,互不覆盖)
+
+手动发布时先核对面板中的服务器、网站域名和网站根目录。建议先解压到本网站的新版本目录,确认完整后再切换网站目录,避免访问到解压过程中新旧混合的文件;保留上一版本以便回退,不覆盖服务器配置。
+发布后打开 ${FRONTEND}/build-info.json?check=${BUILD_ID},核对 buildId 为 ${BUILD_ID},deploymentTarget 为 ${IS_DEV ? 'dev' : 'production'}。若不同,检查解压位置、网站根目录及缓存配置。
${BUILD_ENV === 'dev' ? `本包仅用于 dev 环境,接口固定为 https://dev-vibemake-api.robotquan.com/api,始终读取接口数据。
推荐域名:https://dev-vibemake.robotquan.com。
@@ -85,16 +105,11 @@ ${BUILD_ENV === 'dev' ? `本包仅用于 dev 环境,接口固定为 https://de
方法 GET/POST/PUT/PATCH/DELETE/OPTIONS;请求头 Authorization、Content-Type、Accept;暴露 X-Request-Id)。
- 阿里云 OSS(Bucket linkerbot)跨域规则也要加上这两个域名,否则封面上传会失败。
- 第三方库(three.js、urdf-loader、marked、DOMPurify)和字体都在 vendor/ 里,不依赖任何外部 CDN。
+- 发布时完整覆盖压缩包中的文件,尤其是 js/、css/ 和各页面 index.html;不要只替换入口 HTML。应用入口及其依赖使用统一构建版本号,见 build-info.json 的 buildId。
+- HTML 建议设置 Cache-Control: no-cache,确保浏览器能获取新入口。首次修复旧缓存后强制刷新一次;若启用了 CDN 缓存 HTML,发布后同步刷新页面缓存。
`);
-// 样式表和导航脚本加版本号,部署新包后浏览器一定拿到新文件(不会用到旧缓存)
-const BUILD_ID = Date.now().toString(36);
-for (const f of ['index.html', 'explore/index.html', 'project/index.html', 'studio/index.html', 'cad/index.html', 'pcb/index.html', 'workspace/index.html']) {
- 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|desktop-tools)\.js)"/g, `src="$1?v=${BUILD_ID}"`));
-}
+await versionSiteAssets(DIST, BUILD_ID, ['index.html', 'explore/index.html', 'project/index.html', 'studio/index.html', 'cad/index.html', 'cad/editor/index.html', 'pcb/index.html', 'workspace/index.html']);
// 检查:不能有 .mjs(静态服务器常把它当成二进制文件返回,模块脚本加载失败)
const walk = (d) => readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(d, e.name)) : [join(d, e.name)]));
@@ -102,14 +117,16 @@ 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, BUILD_ENV === 'dev' ? 'dist-dev.zip' : 'dist.zip');
+const zip = join(ROOT, ARCHIVE_NAME);
rmSync(zip, { force: true });
try {
execFileSync('zip', ['-qr', zip, '.'], { cwd: DIST });
console.log(`已生成 ${zip}`);
-} catch {
- console.log('没有找到 zip 命令,只生成了 dist 目录');
+} catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ console.log(`没有找到 zip 命令,只生成了 ${OUTPUT_NAME} 目录`);
}
+console.log(`部署目标:${TARGET_NAME} · ${FRONTEND} · 版本 ${BUILD_ID}`);
console.log(`dist:${DIST}`);
console.log(`PCB:${join(DIST, 'pcb')} ← ${PCB_DIST}`);
console.log(CAD_ENGINE ? `CAD: ${join(DIST, 'cad')} (build ${CAD_ENGINE.manifest.buildId})` : 'CAD: no local engine installed; deploy the SolidCraft Web package separately.');
diff --git a/scripts/enrich-numbered-assembly.mjs b/scripts/enrich-numbered-assembly.mjs
new file mode 100644
index 0000000..3097d54
--- /dev/null
+++ b/scripts/enrich-numbered-assembly.mjs
@@ -0,0 +1,147 @@
+// Add presentation entry moves and measured tool docking without re-exporting GLBs.
+// Usage: node scripts/enrich-numbered-assembly.mjs manifest parts-root report tool.glb output
+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 draco from 'draco3dgltf';
+import { BufferGeometry, Float32BufferAttribute, Matrix4, Vector3, Quaternion, Group, Mesh } from '../vendor/three/build/three.module.min.js';
+import { screwHead } from '../js/assembly-head.js';
+import { inferToolTipAxis, ScrewTransition } from '../js/assembly-motion.js';
+import { validatePackage } from '../js/experience-packages.js';
+
+const [manifestPath, root, reportPath, toolPath, output] = process.argv.slice(2);
+assert.ok(output, 'Required: manifest parts-root report tool.glb output');
+assert.ok(!fs.existsSync(output), 'Choose a new output directory');
+const read = filename => JSON.parse(fs.readFileSync(filename));
+const sha = bytes => createHash('sha256').update(bytes).digest('hex');
+const clean = vector => vector.toArray().map(x => Math.abs(x) < 1e-12 ? 0 : x);
+const raw = read(manifestPath), config = structuredClone(raw), report = read(reportPath);
+const records = new Map(report.records.map(record => [record.id, record]));
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'draco3d.decoder': await draco.createDecoderModule() });
+const facts = [];
+
+async function geometry(filename) {
+ const document = await io.read(filename), vertices = [], indices = [], point = new Vector3();
+ const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
+ assert.ok(scene, `Missing scene: ${filename}`);
+ scene.traverse(node => {
+ if (!node.getMesh()) return;
+ assert.ok(!node.getSkin(), 'Only rigid meshes are supported');
+ const world = new Matrix4().fromArray(node.getWorldMatrix());
+ for (const primitive of node.getMesh().listPrimitives()) {
+ assert.equal(primitive.getMode(), 4);
+ const position = primitive.getAttribute('POSITION'), base = vertices.length / 3;
+ for (let i = 0; i < position.getCount(); i++) {
+ point.fromArray(position.getElement(i, [])).applyMatrix4(world);
+ vertices.push(...point.toArray());
+ }
+ for (const index of primitive.getIndices()?.getArray() ?? Array.from({ length: position.getCount() }, (_, i) => i)) indices.push(base + index);
+ }
+ });
+ const result = new BufferGeometry().setAttribute('position', new Float32BufferAttribute(vertices, 3));
+ result.setIndex(indices); result.computeBoundingBox();
+ return result;
+}
+
+// This supplied L-key has its long working end at minimum Z. Measure the cap
+// in GLB root coordinates (including the exported node translation).
+const toolGeometry = await geometry(toolPath), toolPoints = toolGeometry.attributes.position;
+const tip = new Vector3(), point = new Vector3(); let capCount = 0;
+for (let i = 0; i < toolPoints.count; i++) {
+ point.fromBufferAttribute(toolPoints, i);
+ if (Math.abs(point.z - toolGeometry.boundingBox.min.z) < 1e-7) { tip.add(point); capCount++; }
+}
+assert.ok(capCount >= 3); tip.divideScalar(capCount);
+const template = new Group(); template.add(new Mesh(toolGeometry));
+const tipAxis = new Vector3(...inferToolTipAxis(template, tip.toArray()));
+assert.ok(tipAxis.dot(new Vector3(0, 0, -1)) > .999, 'Tool working end must be verified');
+const tool = { id: 'hex-key', file: path.basename(toolPath), tipPosition: clean(tip), tipAxis: clean(tipAxis) };
+assert.ok(!config.files.some(file => file.path === tool.file), 'Tool filename already exists');
+config.tools = [tool];
+const toolBytes = fs.readFileSync(toolPath);
+config.files.push({ path: tool.file, bytes: toolBytes.length, sha256: sha(toolBytes) });
+
+for (const part of config.parts) {
+ const record = records.get(part.id); assert.ok(record, `Missing axis record: ${part.id}`);
+ const entry = config.files.find(file => file.path === part.file), filename = path.join(root, part.file);
+ const bytes = fs.readFileSync(filename);
+ assert.equal(bytes.length, entry.bytes); assert.equal(sha(bytes), entry.sha256, `Changed source: ${part.file}`);
+ const g = await geometry(filename), originalOffset = [...part.installOffset];
+ const detail = { id: part.id, file: part.file, originalStatus: record.status, originalOffset };
+ if (record.fastener) {
+ const head = screwHead(g); assert.ok(head, `Ambiguous screw head: ${part.file}`);
+ const outward = head.vector, inward = outward.clone().negate();
+ const axisIndex = outward.toArray().findIndex(value => Math.abs(value) > .99), dimensions = ['x', 'y', 'z'];
+ const k = dimensions[axisIndex], [u, v] = dimensions.filter(value => value !== k);
+ const extremum = outward.getComponent(axisIndex) > 0 ? g.boundingBox.max[k] : g.boundingBox.min[k];
+ const cap = { minU: Infinity, maxU: -Infinity, minV: Infinity, maxV: -Infinity };
+ for (let i = 0; i < g.attributes.position.count; i++) {
+ point.fromBufferAttribute(g.attributes.position, i);
+ if (Math.abs(point[k] - extremum) > .0004) continue;
+ cap.minU = Math.min(cap.minU, point[u]); cap.maxU = Math.max(cap.maxU, point[u]);
+ cap.minV = Math.min(cap.minV, point[v]); cap.maxV = Math.max(cap.maxV, point[v]);
+ }
+ const socket = new Vector3(); socket[k] = extremum; socket[u] = (cap.minU + cap.maxU) / 2; socket[v] = (cap.minV + cap.maxV) / 2;
+ socket.addScaledVector(outward, -.00035);
+ const worldOutward = outward.clone().applyQuaternion(new Quaternion(...part.quaternion)).normalize();
+ assert.ok(!part.focusDirection || worldOutward.dot(new Vector3(...part.focusDirection)) > .99999, `Head direction changed: ${part.id}`);
+ if (!Math.hypot(...part.installOffset)) part.installOffset = clean(worldOutward.clone().multiplyScalar(.018));
+ assert.ok(new Vector3(...part.installOffset).normalize().dot(worldOutward) > .9999, `Wrong entry side: ${part.id}`);
+ const rotation = new Quaternion().setFromUnitVectors(tipAxis, inward);
+ part.installation = { type: 'screw', toolId: tool.id, axis: clean(inward), socketPosition: clean(socket), toolQuaternion: rotation.toArray(),
+ direction: 'clockwise', turns: 3, travel: .0012, approachDuration: 1, engageDuration: .5, tightenDuration: 3.2, retractDuration: .65, toolClearance: .014 };
+ part.focusDirection = clean(worldOutward);
+ Object.assign(detail, { localHead: clean(outward), socket: clean(socket), headWidthRatio: head.widthRatio });
+ // Exercise the actual player, not a duplicated formula: docking remains on
+ // the head side throughout rotation and restores the exact final pose.
+ const instance = new Group(); instance.scale.fromArray(part.scale);
+ const toolInstance = new Group(), transition = new ScrewTransition(instance, part, toolInstance, tool);
+ const m = part.installation;
+ for (const fraction of [0, .17, .5, .83, .999]) {
+ transition.sample(m.approachDuration + m.engageDuration + m.tightenDuration * fraction);
+ instance.updateMatrixWorld(true);
+ const actualTip = toolInstance.localToWorld(tip.clone()), expected = instance.localToWorld(socket.clone());
+ assert.ok(actualTip.distanceTo(expected) < 1e-8, `Tool missed socket: ${part.id}`);
+ const handle = toolInstance.localToWorld(tip.clone().addScaledVector(tipAxis, -.03)).sub(actualTip).normalize();
+ const headWorld = outward.clone().applyQuaternion(instance.quaternion);
+ assert.ok(handle.dot(headWorld) > .9999, `Tool behind screw: ${part.id}`);
+ }
+ transition.sample(transition.duration);
+ assert.deepEqual(instance.position.toArray(), part.position);
+ assert.deepEqual(instance.quaternion.toArray(), part.quaternion);
+ transition.dispose();
+ } else if (!Math.hypot(...part.installOffset)) {
+ // A failed collision check is NOT proof of an acceptable assembly route.
+ // Retain the diagnostics and give it an explicitly unverified display move.
+ const candidates = (record.checks ?? []).filter(check => Number.isFinite(check.remaining) && check.length > 0);
+ candidates.sort((a, b) => a.remaining - b.remaining || b.length - a.length);
+ const chosen = candidates[0];
+ part.installOffset = chosen ? chosen.vector.map(value => value * chosen.length) : [0, Math.min(.06, Math.max(.025, g.boundingBox.getSize(new Vector3()).length())), 0];
+ detail.selectedCandidate = chosen ?? null;
+ }
+ detail.offset = part.installOffset;
+ detail.presentationOnly = !Math.hypot(...originalOffset) && record.status !== 'foundation';
+ assert.ok(Math.hypot(...part.installOffset) > .001, `No entry motion: ${part.id}`);
+ facts.push(detail); g.dispose();
+}
+assert.deepEqual(config.steps, raw.steps);
+for (let i = 0; i < raw.parts.length; i++) for (const key of ['id', 'file', 'parentId', 'position', 'quaternion', 'scale']) assert.deepEqual(config.parts[i][key], raw.parts[i][key]);
+validatePackage(config, 'assembly', 'http://localhost:8090/manifest.json');
+const partsRoot = path.join(output, '零件模型');
+fs.mkdirSync(partsRoot, { recursive: true }); fs.mkdirSync(path.join(output, '核对记录'));
+for (const file of raw.files) {
+ const destination = path.join(partsRoot, file.path); fs.mkdirSync(path.dirname(destination), { recursive: true });
+ fs.copyFileSync(path.join(root, file.path), destination);
+}
+fs.copyFileSync(toolPath, path.join(partsRoot, tool.file));
+fs.writeFileSync(path.join(output, 'Microban-装配步骤-带扳手.json'), JSON.stringify(config, null, 2) + '\n');
+const summary = { parts: config.parts.length, steps: config.steps.length, screws: config.parts.filter(p => p.installation).length,
+ addedEntryMoves: facts.filter(f => !Math.hypot(...f.originalOffset)).length, presentationOnly: facts.filter(f => f.presentationOnly).length,
+ files: config.files.length, tool, note: '补充的演示路径不等于无碰撞路径。保留原始检查记录;扳手对接几何轴心,未验证工具与周围零件的完整扫掠空间及机械规格适配。', partsReview: facts };
+fs.writeFileSync(path.join(output, '核对记录/动画与对接检查.json'), JSON.stringify(summary, null, 2) + '\n');
+fs.copyFileSync(reportPath, path.join(output, '核对记录/原轴向检查.json'));
+fs.writeFileSync(path.join(output, '上传说明.txt'), `Microban 分组装配 · 扳手动画版\n\n1. 后台“零件模型”:选择此处的“零件模型”文件夹,包含 8 个部位文件夹和内六角扳手.glb,共 ${config.files.length} 个 GLB。保留文件名和子目录。\n2. 后台“拼装步骤 JSON”:上传 Microban-装配步骤-带扳手.json。\n3. 整机 GLB 不变,无需重传。核对记录不要上传。\n\n保留 ${config.parts.length} 个零件、${config.steps.length} 步、原顺序和最终姿态。前七组独立安装,之后合装七个部件,再安装第八组。\n${summary.screws} 个螺丝步骤加入扳手:移近、对接螺丝头、顺时针拧紧、退出。工具不计入整机零件。\n补上 ${summary.addedEntryMoves} 个原位出现的进入动画。其中 ${summary.presentationOnly} 条是演示路径,不能当作已经通过无碰撞检查;原始诊断保存在核对记录。工具对接位置与方向已验证,工具扫掠避障及实际螺丝规格适配尚未验证。\n所有 GLB 原样复制,材质与颜色未改。\n\n本地预览:http://localhost:8090/deliverables/microban-wrench-20261105/index.html\n`);
+console.log(JSON.stringify({ output, ...Object.fromEntries(Object.entries(summary).filter(([key]) => !['partsReview', 'tool'].includes(key))) }, null, 2));
diff --git a/scripts/generate-numbered-assembly.mjs b/scripts/generate-numbered-assembly.mjs
new file mode 100644
index 0000000..ba2692e
--- /dev/null
+++ b/scripts/generate-numbered-assembly.mjs
@@ -0,0 +1,167 @@
+// Offline: only validated JSON is consumed by the existing community viewer.
+import { createHash } from 'node:crypto';
+import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { parseArgs } from 'node:util';
+import { strict as assert } from 'node:assert';
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import draco from 'draco3dgltf';
+import { BufferAttribute, BufferGeometry, Matrix4, Quaternion, Vector3 } from 'three';
+import { validateEmbeddedGlb, validatePackage } from '../js/experience-packages.js';
+import { bindAssemblyFiles, resourceIndex } from '../js/project-resources.js';
+import { numberedInput } from './lib/numbered-parts.mjs';
+import { collider } from './lib/assembly-axis-planner.mjs';
+import { planEntry, planGroupEntry } from './lib/numbered-axis.mjs';
+
+const hash = data => createHash('sha256').update(data).digest('hex');
+const clean = a => a.map(x=>Math.abs(x)<1e-14?0:x);
+function rigidMeshes(doc, label) {
+ const r = doc.getRoot(), scene = r.getDefaultScene() ?? r.listScenes()[0], nodes = [];
+ assert.ok(scene && !r.listAnimations().length, `${label}:需要静态装配场景`);
+ scene.traverse(n=>{
+ if (!n.getMesh()) return;
+ assert.ok(!n.getSkin() && !n.getWeights().length && n.getMesh().listPrimitives().every(p=>!p.listTargets().length && p.getMode()===4), `${label}:仅支持刚性三角网格`);
+ nodes.push(n);
+ });
+ return nodes;
+}
+function geometry(mesh) {
+ const pos=[], idx=[], xyz=[];
+ for (const p of mesh.listPrimitives()) {
+ const a=p.getAttribute('POSITION'), i=p.getIndices(), base=pos.length/3;
+ assert.ok(a?.getType()==='VEC3','网格缺少三维顶点');
+ for(let n=0;nn);
+ assert.ok(indices.length%3===0 && indices.every(n=>n>=0 && n1e-15, `${label}:不可逆的分件坐标`);
+ const m=target.clone().multiply(source.clone().invert());
+ const p=new Vector3(),q=new Quaternion(),s=new Vector3();
+ m.decompose(p,q,s); q.normalize();
+ const r=new Matrix4().compose(p,q,s);
+ assert.ok(s.toArray().every(x=>x>0) && m.elements.every((x,i)=>Math.abs(x-r.elements[i])<1e-6),`${label}:当前播放器不支持此镜像或剪切变换`);
+ return { position:p.toArray(),quaternion:q.toArray(),scale:s.toArray() };
+}
+export async function generate(root, dest, log=console.log, options={}) {
+ root=path.resolve(root); dest=path.resolve(dest);
+ const destRel=path.relative(root,dest);
+ assert.ok(destRel==='..' || destRel.startsWith('..'+path.sep) || path.isAbsolute(destRel),'输出请放在输入目录以外');
+ assert.ok(!existsSync(dest),'输出目录已存在,请选择新的目录');
+ const {whole,parts:ordered}=numberedInput(root, options);
+ const groupNumbers=[...new Set(ordered.map(p=>p.group.number))];
+ const grouped=options.finalGroup !== undefined;
+ if (grouped) assert.ok(groupNumbers.length > 1 && options.finalGroup===groupNumbers.at(-1), '--final-group 须为最后一个部位编号,前面的部位分别预装');
+ const io=new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'draco3d.decoder':await draco.createDecoderModule()});
+ const read=async name=>{
+ const bytes=readFileSync(path.resolve(root,name));
+ validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.length));
+ return {doc:await io.readBinary(bytes),bytes};
+ };
+ const ref=await read(whole), nodes=rigidMeshes(ref.doc,whole);
+ assert.equal(nodes.length,ordered.length,`整机有 ${nodes.length} 个网格实例,零件文件有 ${ordered.length} 个`);
+ const byName=new Map(nodes.map(n=>[n.getName(),n]));
+ assert.ok(byName.size===nodes.length && !byName.has(''),'整机网格节点需要唯一的名称');
+ const title=path.parse(whole).name;
+ const raw={schemaVersion:1,kind:'assembly',unit:'meter',title:title+' · 分步装配',displayQuaternion:[0,0,0,1],files:[],parts:[],steps:[]};
+ if (grouped) {
+ raw.playback='grouped-v1';
+ raw.groups=groupNumbers.slice(0,-1).map(n=>({id:`group-${n}`,label:ordered.find(p=>p.group.number===n).group.path,parts:[]}));
+ }
+ const records=[], installed=[], used=new Set(), surfaceCache=new Map();
+ const groupColliders=new Map();
+ let joined=false;
+ for (const item of ordered) {
+ if (grouped && item.group.number===options.finalGroup && !joined) {
+ const obstacles=[];
+ for (const group of raw.groups) {
+ const moving=groupColliders.get(group.id);
+ const result=planGroupEntry(moving,obstacles);
+ const step={id:`join-${group.id}`,type:'join',groupId:group.id,label:`${options.finalGroup} 总装 · 合装${group.label}`,parts:group.parts,installOffset:clean(result.offset),
+ pathStatus:result.presentationOnly?'presentation':'checked'};
+ raw.steps.push(step);
+ records.push({id:step.id,label:step.label,groupId:group.id,...result});
+ obstacles.push(...moving);
+ log(`部件合装 ${group.label}:${result.status}`);
+ }
+ joined=true;
+ }
+ const {doc,bytes}=await read(item.path), loose=rigidMeshes(doc,item.path);
+ assert.equal(loose.length,1,`${item.path}:每个分件 GLB 应包含一个网格实例,可含多种材质`);
+ const n=loose[0], target=byName.get(n.getName()) ?? byName.get(item.stem) ?? byName.get(item.name);
+ assert.ok(target && !used.has(target),`${item.path}:未找到唯一整机实例(分件节点 ${n.getName()}),请核对名称`);
+ used.add(target);
+ const local=geometry(n.getMesh()), refMesh=target.getMesh();
+ if(!surfaceCache.has(refMesh)) surfaceCache.set(refMesh,surface(geometry(refMesh)));
+ assert.equal(surface(local),surfaceCache.get(refMesh),`${item.path}:与整机实例的解码网格不一致`);
+ const world=new Matrix4().fromArray(target.getWorldMatrix());
+ const placement=pose(new Matrix4().fromArray(n.getWorldMatrix()),world,item.path);
+ const id=`p-${item.group.number}-${item.number}`;
+ const moving=collider(id,local.clone().applyMatrix4(world));
+ const group=raw.groups?.find(g=>g.id===`group-${item.group.number}`);
+ const previous=group ? (groupColliders.get(group.id) ?? []) : installed;
+ const result=planEntry(moving,local,world,previous,item.name);
+ if (group) { previous.push(moving); groupColliders.set(group.id,previous); group.parts.push(id); }
+ installed.push(moving);
+ const label=`${item.group.path} · ${item.stepLabel ?? item.number} · ${item.name}`;
+ raw.files.push({path:item.path,bytes:bytes.length,sha256:hash(bytes)});
+ raw.parts.push({id,file:item.path,...placement,installOffset:clean(result.offset),...(result.headDirection?{focusDirection:result.headDirection}:{})});
+ raw.steps.push({id:`step-${item.group.number}-${item.number}`,label,parts:[id],...(group?{groupId:group.id}:{})});
+ records.push({id,label,file:item.path,wholeNode:target.getName(),...result});
+ log(`${installed.length}/${ordered.length} ${label}:${result.status}`);
+ }
+ const uri='https://assembly.invalid/steps.json';
+ const pkg=validatePackage(raw,'assembly',uri);
+ bindAssemblyFiles(pkg.files,resourceIndex(raw.files.map(f=>({relativePath:f.path,sizeBytes:f.bytes,url:new URL(f.path,uri).href}))));
+ const manifest=JSON.stringify(raw,null,2)+'\n';
+ assert.ok(Buffer.byteLength(manifest)<=2*1024*1024,'步骤超过播放器 JSON 大小限制');
+ const review=records.filter(r=>r.status.startsWith('review'));
+ mkdirSync(dest,{recursive:true});
+ writeFileSync(path.join(dest,title+'-装配步骤.json'),manifest,{flag:'wx'});
+ const report={whole,wholeSha256:hash(ref.bytes),steps:raw.steps.length,partCount:ordered.length,groups:raw.groups?.length ?? 0,needReview:review.length,seatingToleranceMeters:0.00015,
+ extraBefore:options.extraBefore ?? null,
+ counts:records.reduce((all,r)=>{all[r.status]=(all[r.status] ?? 0)+1;return all;},{}),
+ visualFits:'visual-thread-fit 检查完整头部通道和带径向余量的螺杆。visual-bore-axis 检查完整头部通道和半径为螺杆一半的孔芯。这两类仅用于轴向演示。',
+ note:'仅检查已装件与当前零件直线平移的网格表面;未检查末端 0.15 mm 配合、旋转、工具及真实装配工艺。',
+ review:review.map(r=>({step:r.id,label:r.label,file:r.file,reason:r.status})),records};
+ mkdirSync(path.join(dest,'核对记录'));
+ writeFileSync(path.join(dest,'核对记录','轴向检查.json'),JSON.stringify(report,null,2)+'\n');
+ writeFileSync(path.join(dest,'核对记录','待核对步骤.txt'),`以下 ${review.length} 步无法确认无碰撞的直线插入通路。普通零件原位显示;部件合装保留就位演示动画,但不是已经证明无碰撞的真实安装路线。\n\n`+review.map(r=>`${r.label}\n ${r.file ?? '整组部件合装'}\n ${r.status==='review-head'?'未能可靠区分螺丝头尾':'候选轴向受阻或检查未能确认'}\n`).join('\n'));
+ const fits=(report.counts['visual-thread-fit'] ?? 0)+(report.counts['visual-bore-axis'] ?? 0);
+ writeFileSync(path.join(dest,'上传说明.txt'),`整机模型单独上传 ${whole}。\n零件模型选择 ${root},保留全部编号部位子目录、文件名。\n拼装步骤只上传 ${title}-装配步骤.json。\n${grouped?`需要部署支持 grouped-v1 的新版前端。前 ${raw.groups.length} 组分别展示;第 ${options.finalGroup} 组前先合装这些部件,再安装该文件夹的零件。\n`:''}共 ${ordered.length} 个零件、${raw.steps.length} 个播放步骤,${fits} 步是螺丝沿孔轴展示,${review.length} 步需人工复核。普通待核对零件原位显示,待核对的部件合装使用就位演示动画(pathStatus: presentation),不能据此判断真实安装过程无碰撞。具体步号请看核对记录。\n原 GLB 几何、材质、颜色未修改。\n`);
+ return report;
+}
+if (pathToFileURL(path.resolve(process.argv[1] ?? '.')).href===import.meta.url) {
+ try {
+ const {values,positionals:[root,out]}=parseArgs({allowPositionals:true,options:{reference:{type:'string'},'final-group':{type:'string'},'extra-before':{type:'string'}}});
+ assert.ok(root && out,'用法:npm run assembly:generate -- "分组 GLB 目录" "新的输出目录" [--reference "整机.glb"] [--final-group 8]');
+ const options={reference:values.reference};
+ if (values['extra-before']) {
+ options.extraBefore=values['extra-before']==='end'?'end':Number(values['extra-before']);
+ assert.ok(options.extraBefore==='end'||Number.isSafeInteger(options.extraBefore)&&options.extraBefore>0,'附加件参数格式:--extra-before 步号,或 --extra-before end');
+ }
+ if(values['final-group']) options.finalGroup=Number(values['final-group']);
+ const r=await generate(root,out,console.log,options);
+ console.log(`完成:${path.resolve(out)}(${r.steps} 步,${r.needReview} 步需复核)`);
+ }
+ catch (err){console.error(err.message);process.exitCode=1;}
+}
diff --git a/scripts/lib/numbered-axis.mjs b/scripts/lib/numbered-axis.mjs
new file mode 100644
index 0000000..d7bfc59
--- /dev/null
+++ b/scripts/lib/numbered-axis.mjs
@@ -0,0 +1,89 @@
+import { Box3, Matrix4, Vector3 } from 'three';
+import { checkFiniteAxis, VIEW_AXES } from './assembly-axis-planner.mjs';
+import { threadFit } from './thread-fit.mjs';
+
+import { screwHead, isAssemblyFastener } from '../../js/assembly-head.js';
+export { screwHead } from '../../js/assembly-head.js';
+
+export function planEntry(item, local, world, installed, name) {
+ const fastener = isAssemblyFastener(name);
+ const head = fastener ? screwHead(local) : null;
+ const meta = { fastener, headWidthRatio:head?.widthRatio ?? null,
+ ...(head ? {headDirection:head.vector.clone().transformDirection(world).toArray()} : {}) };
+ if (!installed.length) return {...meta,status:'foundation',offset:[0,0,0],checks:[]};
+ const axes = [];
+ function add(label,v) {
+ v.normalize();
+ if (!axes.some(c=>c.v.dot(v)>1-1e-8)) axes.push({label,v});
+ }
+ if (head) add('从螺丝头一侧沿杆轴进入',head.vector.clone().transformDirection(world));
+ else if (fastener) return {...meta,status:'review-head',offset:[0,0,0],checks:[]};
+ else {
+ for (const a of VIEW_AXES) add(a.name,new Vector3(...a.vector));
+ for (const a of VIEW_AXES) add('local '+a.name,new Vector3(...a.vector).transformDirection(world));
+ for (const x of [-1,0,1]) for (const y of [-1,0,1]) for (const z of [-1,0,1]) {
+ if (Math.abs(x)+Math.abs(y)+Math.abs(z)>1) add(`斜向 (${x},${y},${z})`,new Vector3(x,y,z));
+ }
+ }
+ const size = item.box.getSize(new Vector3()).length();
+ const travel = Math.min(fastener ? .024 : .08, Math.max(fastener ? .008 : .012, size*(fastener ? 1.7 : 1.05)));
+ const checks = [];
+ for (const length of [travel, travel*0.5]) {
+ for (const {label,v} of axes) {
+ // Reject explicit contacts cheaply before the more expensive conservative
+ // continuous query. Passing these samples alone is never enough.
+ const sweep = item.box.clone().union(item.box.clone().translate(v.clone().multiplyScalar(length)));
+ const obstacles = installed.filter(b=>sweep.intersectsBox(b.box));
+ const matrix = new Matrix4();
+ let block;
+ for (const t of [1,.75,.5,.25,.08]) {
+ const delta = v.clone().multiplyScalar(length*t);
+ const box = item.box.clone().translate(delta);
+ matrix.makeTranslation(delta.x,delta.y,delta.z);
+ const b = obstacles.find(b=>box.intersectsBox(b.box) && b.bvh.intersectsGeometry(item.geometry,matrix));
+ if (b) { block={status:'blocked-or-touching',blocker:b.id,remaining:length*t}; break; }
+ }
+ const checked = block ?? checkFiniteAxis([item],installed,v.toArray(),length,{maxMilliseconds:650,maxIterations:100});
+ checks.push({axis:label,vector:v.toArray(),length,...checked});
+ if (['foundation','clear-to-seating'].includes(checked.status)) {
+ return {...meta,status:'clear-to-seating',offset:v.clone().multiplyScalar(length).toArray(),checks};
+ }
+ }
+ }
+ if (head) {
+ for (const length of [travel, travel*0.5]) {
+ const fit=threadFit(local,world,head.vector,installed,length);
+ if (fit) return {...meta,status:fit.status,offset:axes[0].v.clone().multiplyScalar(length).toArray(),fit,checks};
+ }
+ }
+ // No verified linear route: reveal in place. Do not turn a colliding path
+ // or a query timeout into an apparently approved insertion direction.
+ return {...meta,status:'review-path',offset:[0,0,0],checks};
+}
+
+// The entire completed component moves as one rigid body. Internal contacts
+// within the component are intentional; only already joined components block it.
+export function planGroupEntry(moving, installed) {
+ const bounds=new Box3(); for(const item of moving) bounds.union(item.box);
+ const travel=Math.max(.04, Math.min(.2, bounds.getSize(new Vector3()).length() * .65));
+ if (!installed.length) return { status:'foundation', offset:[0,travel,0], checks:[] };
+ const checks=[];
+ for(const length of [travel, travel * .5]) for(const axis of VIEW_AXES) {
+ const checked=checkFiniteAxis(moving,installed,axis.vector,length,{maxMilliseconds:1800,maxIterations:180});
+ checks.push({axis:axis.name,vector:axis.vector,length,...checked});
+ if (['foundation','clear-to-seating'].includes(checked.status)) return {
+ status:'clear-to-seating',offset:axis.vector.map(v=>v*length),checks,
+ };
+ }
+ // A presentation move is useful even when exact rigid-mesh insertion cannot
+ // be certified (interlocking/press-fit geometry). Keep it EXPLICITLY marked
+ // as unverified, and pick the axis that got closest to seating. Never relabel
+ // such a route as collision-free just to make the preview animate.
+ const obstacleBox=new Box3();for(const item of installed) obstacleBox.union(item.box);
+ const outward=bounds.getCenter(new Vector3()).sub(obstacleBox.getCenter(new Vector3())).normalize();
+ const ranked=checks.filter(c=>Number.isFinite(c.remaining)).sort((a,b)=>
+ a.remaining-b.remaining || new Vector3(...b.vector).dot(outward)-new Vector3(...a.vector).dot(outward));
+ const chosen=ranked[0];
+ const vector=chosen?.vector ?? (outward.lengthSq() ? outward.toArray() : [0,1,0]);
+ return {status:'review-path',presentationOnly:true,offset:vector.map(v=>v*travel),checks};
+}
diff --git a/scripts/lib/numbered-parts.mjs b/scripts/lib/numbered-parts.mjs
new file mode 100644
index 0000000..98ac1fb
--- /dev/null
+++ b/scripts/lib/numbered-parts.mjs
@@ -0,0 +1,71 @@
+// Numeric order is authoritative. A CAD instance suffix (.003) is never a step.
+import { readdirSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+function ordered(items, parent, issues) {
+ const byNumber = new Map();
+ for (const item of items) {
+ if (!Number.isSafeInteger(item.number) || item.number < 1) {
+ issues.push(`缺少有效的开头编号:${item.path}`);
+ continue;
+ }
+ const names = byNumber.get(item.number) ?? [];
+ names.push(item.path);
+ byNumber.set(item.number, names);
+ }
+ const numbers = [...byNumber.keys()].sort((a, b) => a - b);
+ let expected = 1;
+ for (const n of numbers) {
+ if (n !== expected) issues.push(`${parent} 缺号:${expected}${expected === n - 1 ? '' : '–' + (n - 1)}`);
+ if (byNumber.get(n).length > 1) issues.push(`重复编号 ${n}:${byNumber.get(n).join('、')}`);
+ expected = n + 1;
+ }
+ return items.sort((a, b) => a.number - b.number);
+}
+
+export function numberedInput(root, { extraBefore, reference } = {}) {
+ const children = folder => readdirSync(folder, { withFileTypes: true }).filter(e => !e.name.startsWith('.') && e.name !== '__MACOSX');
+ const isGlb = e => e.isFile() && /\.glb$/i.test(e.name);
+ const entries = children(root), models = entries.filter(isGlb);
+ const issues = [];
+ if (reference) {
+ if (!/\.glb$/i.test(reference) || !statSync(reference, { throwIfNoEntry: false })?.isFile()) issues.push('指定的整机 GLB 不存在');
+ } else if (models.length !== 1) issues.push(`根目录应恰好有一个整机 GLB,实际 ${models.length} 个;整机在外部时请用 --reference 指定`);
+ const groups = ordered(entries.filter(e => e.isDirectory()).map(e => ({
+ path: e.name, number: Number(/^(\d+)/u.exec(e.name)?.[1]),
+ })), '部位目录', issues);
+ if (!groups.length) issues.push('没有找到编号部位目录');
+ const parts = [];
+ for (const g of groups) {
+ const files = children(path.join(root, g.path));
+ for (const e of files.filter(e => e.isDirectory() || e.isSymbolicLink())) issues.push(`不支持嵌套目录或链接:${g.path}/${e.name}`);
+ const extras = [];
+ const items = files.filter(isGlb).flatMap(e => {
+ const stem = e.name.slice(0,-4);
+ const extra = /^(\d+)[-_.、 ]+附加[-_.、 ]+(.+)$/u.exec(stem);
+ if (extra) {
+ extras.push({ group: g, stem, name: extra[2], path: g.path + '/' + e.name });
+ return [];
+ }
+ // For "1-23-tibia" inside either leg, 23 is the local step. The outer
+ // directory determines the group; do not sort by the first digit here.
+ // Some exports omit the separator before the name: "4-10STP39-14".
+ const match = /^\d+[-_.、 ]+(\d+)(?:[-_.、 ]+(.+)|([^\d\s._、-].*))$/u.exec(stem)
+ ?? /^(\d+)[-_.、 ]+(.+)$/u.exec(stem);
+ return [{ group: g, number: Number(match?.[1]), stem, name: match?.[2] ?? match?.[3], path: g.path + '/' + e.name }];
+ });
+ if (!items.length) issues.push(`${g.path} 没有 GLB 零件`);
+ const sequence = ordered(items, g.path, issues);
+ if (extras.length) {
+ const index = extraBefore === 'end' ? sequence.length : sequence.findIndex(item => item.number === extraBefore);
+ if (index < 0 || extras.length > 1) {
+ issues.push(`请指定附加件的安装位置或给它编独立步号:${extras.map(item => item.path).join('、')}`);
+ } else {
+ sequence.splice(index, 0, { ...extras[0], number: 'extra', stepLabel: '附加' });
+ }
+ }
+ parts.push(...sequence);
+ }
+ if (issues.length) throw new Error('输入检查失败,未生成装配 JSON:\n' + issues.join('\n'));
+ return { whole: reference ? path.resolve(reference) : models[0].name, parts };
+}
diff --git a/scripts/lib/thread-fit.mjs b/scripts/lib/thread-fit.mjs
new file mode 100644
index 0000000..61f6ea5
--- /dev/null
+++ b/scripts/lib/thread-fit.mjs
@@ -0,0 +1,88 @@
+// Visual fit of a modeled thread in its pilot hole. Only the shaft perimeter
+// has an allowance; the head and the bore core must have a continuous passage.
+import { Box3, Matrix4, Vector3 } from 'three';
+
+const sides = Array.from({length:16}, (_, i) => [Math.cos(i*Math.PI/8), Math.sin(i*Math.PI/8)]);
+
+// Clip the obstacle triangle against a closed convex prism. A triangle wholly
+// inside the swept volume counts too. Tangent planes circumscribe the circle.
+function intersectsPrism(triangle, inverse, floor, ceiling, radius) {
+ let polygon = [triangle.a,triangle.b,triangle.c].map(v=>v.clone().applyMatrix4(inverse));
+ const planes = [[0,0,-1,-floor],[0,0,1,ceiling],...sides.map(([x,y])=>[x,y,0,radius])];
+ for (const [x,y,z,limit] of planes) {
+ const next=[];
+ let prev=polygon.at(-1);
+ let a=prev.x*x+prev.y*y+prev.z*z-limit;
+ for (const point of polygon) {
+ const b=point.x*x+point.y*y+point.z*z-limit;
+ if ((a>0)!==(b>0)) next.push(prev.clone().lerp(point,a/(a-b)));
+ if (b<=0) next.push(point);
+ prev=point; a=b;
+ }
+ if (!next.length) return false;
+ polygon=next;
+ }
+ return true;
+}
+
+export function threadFit(local, world, headAxis, obstacles, travel) {
+ const scale=new Vector3().setFromMatrixScale(world);
+ if (Math.max(...scale.toArray())-Math.min(...scale.toArray())>scale.z*1e-5) return null;
+ const up=headAxis, x=new Vector3().crossVectors(up, Math.abs(up.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0)).normalize();
+ const y=new Vector3().crossVectors(up,x);
+ const center=local.boundingBox.getCenter(new Vector3());
+ const frame=new Matrix4().makeBasis(x,y,up).setPosition(center);
+ const localToFrame=frame.clone().invert();
+ const frameToWorld=world.clone().multiply(frame);
+ const inverse=frameToWorld.clone().invert();
+ const coords=local.attributes.position;
+ const vertices=[];
+ let bottom=Infinity,top=-Infinity,radius=0;
+ for (let i=0;ip.h0 && radius>shaft*1.18)) return null;
+ // Include the full transition in the head envelope. A triangle spanning
+ // directly from tip to head (a taper, not a cylindrical screw) is excluded.
+ let shoulder=Infinity;
+ const pos=local.index.array;
+ for(let i=0;iv.r>shaft*1.02)) for(const v of face) shoulder=Math.min(shoulder,v.h);
+ }
+ if (!(shoulder>bottom+.45*span)) return null;
+ const localTravel=travel/scale.z, seat=.00015/scale.z;
+ const sweptBox=(r,lo,hi)=>new Box3(new Vector3(-r,-r,lo),new Vector3(r,r,hi)).applyMatrix4(frameToWorld).expandByScalar(1e-7);
+ const clear=(r,lo)=>{
+ const start=lo+seat, end=top+localTravel, sweep=sweptBox(r*1.022,start,end);
+ for(const obstacle of obstacles){
+ if(!sweep.intersectsBox(obstacle.box)) continue;
+ // Extend past this obstacle only, so an initially enclosed prism cannot pass.
+ const ceiling=Math.max(end,obstacle.box.clone().applyMatrix4(inverse).max.z+.00001);
+ const bounds=sweptBox(r*1.022,start,ceiling);
+ if(obstacle.bvh.shapecast({
+ intersectsBounds:b=>bounds.intersectsBox(b),
+ intersectsTriangle:t=>intersectsPrism(t,inverse,start,ceiling,r),
+ })) return false;
+ }
+ return true;
+ };
+ if(!clear(radius,shoulder)) return null;
+ // A core check is an explicit visual thread-fit assumption. Never classify
+ // it as clearance for the original full-diameter screw mesh.
+ for(const fraction of [.10,.20,.30]) {
+ const allowance=Math.min(shaft*fraction,.00035/scale.x);
+ if(clear(shaft-allowance,bottom)) return {status:'visual-thread-fit',travel,coreRadiusMeters:(shaft-allowance)*scale.x,
+ shaftRadiusMeters:shaft*scale.x,radialAllowanceMeters:allowance*scale.x,headRadiusMeters:radius*scale.x};
+ }
+ // A coarse polygonal pilot hole can confirm the entry side without
+ // establishing the fit diameter. Expose that distinction in the report.
+ if(clear(shaft/2,bottom)) return {status:'visual-bore-axis',travel,coreRadiusMeters:shaft*.5*scale.x,
+ shaftRadiusMeters:shaft*scale.x,headRadiusMeters:radius*scale.x};
+ return null;
+}
diff --git a/scripts/lib/version-site-assets.mjs b/scripts/lib/version-site-assets.mjs
new file mode 100644
index 0000000..6301775
--- /dev/null
+++ b/scripts/lib/version-site-assets.mjs
@@ -0,0 +1,50 @@
+import { build } from 'esbuild';
+import { existsSync, readFileSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';
+import { join, relative, resolve, sep } from 'node:path';
+
+const walk = dir => readdirSync(dir, { withFileTypes: true }).flatMap(entry =>
+ entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)]);
+
+// Version the entire application module graph, including lazy imports. Versioning
+// only an HTML entry does not invalidate its unversioned dependencies in browsers.
+export async function versionSiteAssets(root, buildId, pages) {
+ root = realpathSync(root);
+ const jsRoot = join(root, 'js');
+ const version = url => {
+ const parsed = new URL(url, 'https://build.invalid/');
+ parsed.searchParams.set('v', buildId);
+ return url.split(/[?#]/)[0] + parsed.search + parsed.hash;
+ };
+ const files = walk(jsRoot).filter(file => file.endsWith('.js'));
+ const result = await build({
+ entryPoints: files, outdir: jsRoot, outbase: jsRoot,
+ bundle: true, format: 'esm', write: false, treeShaking: false,
+ minify: false, charset: 'utf8', logLevel: 'silent',
+ plugins: [{ name: 'version-app-imports', setup(builder) {
+ builder.onResolve({ filter: /.*/ }, args => {
+ if (args.kind === 'entry-point') return;
+ const path = args.path.split(/[?#]/)[0];
+ if (path.startsWith('.') || path.startsWith('/')) {
+ const target = path.startsWith('/') ? resolve(root, '.' + path) : resolve(args.resolveDir, path);
+ const rel = relative(jsRoot, target);
+ if (!rel.startsWith('..' + sep) && !rel.startsWith(sep) && target.endsWith('.js')) {
+ if (!existsSync(target)) throw new Error(`Missing application module: ${args.path} in ${args.importer}`);
+ return { path: version(args.path), external: true };
+ }
+ }
+ // Keep import-map entries and vendor URLs identical: Three must remain
+ // a single shared instance across the viewers and their addons.
+ return { path: args.path, external: true };
+ });
+ } }],
+ });
+ for (const output of result.outputFiles) writeFileSync(output.path, output.contents);
+ for (const page of pages) {
+ const file = join(root, page);
+ const html = readFileSync(file, 'utf8').replace(
+ /(<(?:script|link)\b[^>]*?\b(?:src|href)\s*=\s*)(["'])(\/?(?:js\/[^"']+\.js|css\/[^"']+\.css)(?:\?[^"'#]*)?(?:#[^"']*)?)\2/gi,
+ (_, prefix, quote, url) => `${prefix}${quote}${version(url)}${quote}`,
+ );
+ writeFileSync(file, html);
+ }
+}
diff --git a/scripts/model-assets.test.mjs b/scripts/model-assets.test.mjs
index f04c0e7..c0d7518 100644
--- a/scripts/model-assets.test.mjs
+++ b/scripts/model-assets.test.mjs
@@ -52,6 +52,26 @@ test('asset names and signed query strings survive a proxy round trip', () => {
assert.equal(modelAssetTarget(modelAssetUrl(remote, 'localhost')).href, remote);
});
+test('OSS object names containing + load literally on deployed sites and through the LAN proxy', () => {
+ const root = `${origin}/vibemake/project-resources/sesame/model-parts/batch`;
+ const remote = `${root}/1+4%20PCB%E7%94%B5%E8%B7%AF%E6%9D%BF.glb?Signature=a+b%2Bc%3D&Expires=123`;
+ const encoded = remote.replace('/1+4', '/1%2B4');
+ for (const host of ['vibemake.robotquan.com', 'dev-vibemake.robotquan.com']) {
+ assert.equal(modelAssetUrl(remote, host), encoded);
+ assert.equal(modelAssetUrl(encoded, host), encoded);
+ }
+ for (const host of ['localhost', '192.168.1.6']) {
+ assert.equal(modelAssetTarget(modelAssetUrl(remote, host)).href, encoded);
+ }
+ // A '+' in an unrelated origin, a query, or an encoded literal '%2B'
+ // filename must not be reinterpreted as a different object or signature.
+ for (const unchanged of [
+ 'https://example.com/1+4.glb',
+ `${root}/part.glb?Signature=a+b%2Bc%3D`,
+ `${root}/1%252B4.glb`,
+ ]) assert.equal(modelAssetUrl(unchanged, 'vibemake.robotquan.com'), unchanged);
+});
+
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']) {
diff --git a/scripts/package-new-simulations.mjs b/scripts/package-new-simulations.mjs
new file mode 100644
index 0000000..a237bca
--- /dev/null
+++ b/scripts/package-new-simulations.mjs
@@ -0,0 +1,69 @@
+// Pack data-only Robot Packages for the admin folder uploader. LFS placeholders
+// are hydrated only when the fetched bytes match the supplied source's hash.
+import { readFile, writeFile, readdir, mkdir } from 'node:fs/promises';
+import { resolve, join, dirname, relative } from 'node:path';
+import { createHash } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import assert from 'node:assert/strict';
+import { validatePackage } from '../sandbox/src/platform/loader/SchemaValidator.js';
+import { readOnnxMetadata } from '../sandbox/src/platform/loader/metadata.js';
+import { resourceIndex, validateRobotResources } from '../js/project-resources.js';
+
+const [sourceArg, hydratedArg, outputArg] = process.argv.slice(2);
+if (!outputArg) throw new Error('Usage: node scripts/package-new-simulations.mjs SOURCE_ROBOTS HYDRATED_ROBOTS NEW_OUTPUT_FOLDER');
+const source = resolve(sourceArg), hydrated = resolve(hydratedArg), output = resolve(outputArg);
+const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const json = (path, data) => writeFile(path, JSON.stringify(data, null, 2) + '\n');
+const walk = async (dir) => (await Promise.all((await readdir(dir, { withFileTypes: true }))
+ .filter(e => !e.name.startsWith('.')).map(e => e.isDirectory() ? walk(join(dir, e.name)) : [join(dir, e.name)]))).flat().sort();
+await mkdir(output); // Never overwrite an earlier delivery.
+const report = { checkedAt: new Date().toISOString(), browserPlaybackTested: false, robots: [] };
+for (const [id, folder] of [['t1', '01-Booster-T1'], ['apollo', '02-Apptronik-Apollo']]) {
+ const original = join(source, id), destination = join(output, folder, '仿真资源');
+ const inventory = [];
+ let hydratedFiles = 0;
+ for (const path of await walk(original)) {
+ const name = relative(original, path);
+ let bytes = await readFile(path);
+ const pointer = /^version https:\/\/git-lfs.github.com\/spec\/v1\noid sha256:([a-f0-9]{64})\nsize (\d+)\s*$/.exec(bytes.toString('utf8'));
+ if (pointer) {
+ bytes = await readFile(join(hydrated, id, name));
+ assert.equal(bytes.length, Number(pointer[2]), `${id}/${name}: LFS size`);
+ assert.equal(sha(bytes), pointer[1], `${id}/${name}: LFS hash`);
+ hydratedFiles++;
+ }
+ assert.ok(!bytes.subarray(0, 100).toString().includes('git-lfs.github.com/spec'), `${name}: placeholder`);
+ const target = join(destination, name);
+ await mkdir(dirname(target), { recursive: true });
+ await writeFile(target, bytes);
+ inventory.push({ path: name, bytes: bytes.length, sha256: sha(bytes) });
+ }
+ const config = validatePackage(JSON.parse(await readFile(join(destination, 'robot.json'))));
+ const manifest = JSON.parse(await readFile(join(destination, 'source-manifest.json')));
+ for (const expected of manifest.files) {
+ const actual = inventory.find(f => f.path === expected.file);
+ assert.ok(actual, `${id}: missing ${expected.file}`);
+ assert.equal(actual.bytes, expected.bytes, `${id}/${expected.file}: source size`);
+ assert.equal(actual.sha256, expected.sha256, `${id}/${expected.file}: source hash`);
+ }
+ const entries = inventory.map(f => ({ relativePath: f.path, sizeBytes: f.bytes, url: `https://assets.example/${id}/${f.path}` }));
+ const packet = validateRobotResources(config, 'robot.json', resourceIndex(entries));
+ assert.equal(packet.warnings.length, 0);
+ assert.deepEqual(packet.capabilities, [{ id: 'walk', skillId: 'walk' }]);
+ const primary = config.skills.find(s => s.kind === 'primary');
+ const metadata = readOnnxMetadata(await readFile(join(destination, primary.controller.policy)));
+ assert.deepEqual(metadata.joint_names.split(','), config.joints.groups[primary.owns]);
+ const jointCount = config.joints.groups[primary.owns].length;
+ const totalBytes = inventory.reduce((n, f) => n + f.bytes, 0);
+ const zip = `${id}-仿真上传.zip`;
+ execFileSync('/usr/bin/zip', ['-q', '-r', join(output, folder, zip), '.'], { cwd: destination });
+ execFileSync('/usr/bin/unzip', ['-tq', join(output, folder, zip)], { stdio: 'pipe' });
+ const zipBytes = await readFile(join(output, folder, zip));
+ await json(join(output, folder, '文件校验清单.json'), { id, totalBytes, files: inventory, zip: { path: zip, bytes: zipBytes.length, sha256: sha(zipBytes) } });
+ await writeFile(join(output, folder, '上传说明.txt'), `${config.name} · 仿真上传\n\n后台“机器人运动演示 / 仿真”→ 选择整个“仿真资源”文件夹。\n如果后台使用 ZIP 上传,则选择同目录的“${zip}”。两种方式选一种,不要重复上传。\n\n文件夹内 ${inventory.length} 个文件,约 ${(totalBytes / 1048576).toFixed(1)} MiB。\n入口:robot.json;物理模型:${config.model};策略:${primary.controller.policy};模型网格 ${config.assets.length} 个。\n保留全部子目录、文件名和大小写。不要只选择 meshes/assets/policies,也不要选择包含 ZIP 的外层文件夹。\n\n本包只提供仿真:行走、方向控制、暂停、重置。没有声明踢球或跳舞,不会强制添加这些动作。\n本包没有整机 GLB、装配零件 GLB 和拼装步骤,不要上传到这些栏目。仿真使用原工程的 MJCF + STL + ONNX,未修改材质、训练策略或控制参数。\n\n社区播放器需包含本次 linear_velocity 观测及地面碰撞兼容修改;仅上传文件不会更新线上播放器。\n`);
+ report.robots.push({ id, name: config.name, fileCount: inventory.length, hydratedFiles, totalBytes, jointCount, meshCount: config.assets.length, skills: config.skills.map(s => s.id), sourceManifestVerified: true });
+ console.log(`${config.name}: ${inventory.length} files, ${(totalBytes / 1048576).toFixed(1)} MiB, ${hydratedFiles} LFS objects verified`);
+}
+await json(join(output, '校验报告.json'), report);
+await writeFile(join(output, '先看这里-上传说明.txt'), `新增两款机器人 · 后台仿真上传\n\n01-Booster-T1\n02-Apptronik-Apollo\n\n两个机器人分别对应两个后台项目。每个项目在“机器人运动演示 / 仿真”栏目上传其“仿真资源”文件夹;若后台提供 ZIP 导入,上传同目录 ZIP。\n不要把两个机器人合成一个资源包,不要把最外层总文件夹作为一个机器人上传。\n\n原始模型文件、控制配置、策略、来源和许可证已保留。真实 STL/ONNX 已从原仓库获取并逐文件核对原始 SHA256,不是源码压缩包中的 LFS 占位文件。\n\n上传完成后刷新社区详情,点击“仿真”。打开默认不自动走;按方向或自动行走开始。\n线上播放器必须更新本次兼容代码,否则旧版本会拒绝 linear_velocity 观测。\n\n此处只有仿真资料;整机展示和 AI 装配需要另外提供对应 GLB 与步骤文件。\n`);
+console.log(output);
diff --git a/scripts/refresh-duck-upload.mjs b/scripts/refresh-duck-upload.mjs
new file mode 100644
index 0000000..5130e23
--- /dev/null
+++ b/scripts/refresh-duck-upload.mjs
@@ -0,0 +1,140 @@
+// 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));
diff --git a/tests/assembly-animation.test.js b/tests/assembly-animation.test.js
new file mode 100644
index 0000000..21a2b43
--- /dev/null
+++ b/tests/assembly-animation.test.js
@@ -0,0 +1,126 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { Group, PerspectiveCamera, Vector3 } from 'three';
+import { AssemblyViewer } from '../js/assembly-viewer.js';
+import { ASSEMBLY_PACE, assemblyEase, presentationScrewMotion } from '../js/assembly-animation.js';
+import { ScrewTransition, screwDuration } from '../js/assembly-motion.js';
+
+function viewer() {
+ const v = Object.create(AssemblyViewer.prototype);
+ v.camera = new PerspectiveCamera(32, 1.6, .01, 50);
+ v.camera.position.set(0, 0, 2);
+ v.controls = { target: new Vector3(), update() { return false; } };
+ v.renderer = { domElement: { style: {} }, shadowMap: {}, render() {} };
+ v.loop = { invalidate() {} };
+ v.notifyMotion = () => {};
+ v.transitions = [];
+ return v;
+}
+
+function animate(v, frame, reduced = false) {
+ const original = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: reduced });
+ try { v.moveCamera(frame, true); } finally { globalThis.matchMedia = original; }
+}
+
+test('insertion ramps up and down gently, never overshooting its exact final position', () => {
+ assert.equal(assemblyEase(-1), 0);
+ assert.equal(assemblyEase(2), 1);
+ assert.ok(assemblyEase(.01) / .01 < .001, 'near-zero initial velocity');
+ assert.ok((1 - assemblyEase(.99)) / .01 < .001, 'near-zero final velocity');
+ for (let i = 1; i <= 100; i++) assert.ok(assemblyEase(i / 100) >= assemblyEase((i - 1) / 100));
+ const v = viewer(), part = new Group();
+ part.position.set(1, 0, 0);
+ v.transitions = [{ instance: part, from: part.position.clone(), target: new Vector3(), duration: ASSEMBLY_PACE.insertion, elapsed: 0 }];
+ v.render(.1);
+ assert.ok(part.position.x > .99, 'first 100 ms should not launch the part at full speed');
+ v.render(.45);
+ assert.ok(part.position.x > .5, 'the old half-second duration must no longer finish the insertion');
+ v.render(1);
+ assert.deepEqual(part.position.toArray(), [0, 0, 0]);
+});
+
+test('front/back camera pulls back and arcs without fading or crossing through the work', () => {
+ const v = viewer();
+ const frame = { position: new Vector3(0, 0, -2), target: new Vector3() };
+ animate(v, frame);
+ const duration = v.cameraTransition.motionDuration;
+ const part = new Group();
+ part.position.set(1, 0, 0);
+ v.transitions = [{ instance: part, from: part.position.clone(), target: new Vector3(), duration: 1, elapsed: 0 }];
+ v.render(duration * .18);
+ assert.ok(v.camera.position.z > 2, 'pull out before turning');
+ assert.ok(Math.abs(v.camera.position.x) < 1e-10);
+ const paused = v.camera.position.clone();
+ v.setAnimationPaused(true);
+ v.render(1);
+ assert.deepEqual(v.camera.position.toArray(), paused.toArray());
+ v.setAnimationPaused(false);
+ v.render(duration * .32);
+ assert.ok(Math.abs(v.camera.position.x) > 2, 'midpoint is beside the work, never through its center');
+ assert.ok(Math.abs(v.camera.position.z) < 1e-8);
+ assert.ok(!v.renderer.domElement.style.opacity, 'the canvas stays fully visible');
+ assert.equal(part.position.x, 1, 'installation waits for the camera');
+ v.render(duration * .5);
+ assert.deepEqual(v.camera.position.toArray(), frame.position.toArray());
+ v.render(ASSEMBLY_PACE.cameraHold + .001);
+ assert.equal(part.position.x, 1, 'camera settles before insertion');
+ assert.equal(v.cameraTransition, null);
+ v.render(.5);
+ assert.equal(part.position.x, .5);
+ animate(v, { position: paused, target: new Vector3() });
+ v.render(.2);
+ const interrupted = v.camera.position.clone();
+ v.cancelCameraTransition();
+ v.render(.2);
+ assert.deepEqual(v.camera.position.toArray(), interrupted.toArray());
+ animate(v, frame, true);
+ assert.equal(v.cameraTransition, null, 'reduced motion uses an immediate visible cut');
+ assert.deepEqual(v.camera.position.toArray(), frame.position.toArray());
+});
+
+test('camera takes the short route across the azimuth seam with no sudden frame jumps', () => {
+ const v = viewer();
+ const point = degrees => new Vector3(Math.sin(degrees * Math.PI / 180) * 2, .5, Math.cos(degrees * Math.PI / 180) * 2);
+ v.camera.position.copy(point(175));
+ animate(v, { position: point(-175), target: new Vector3() });
+ assert.ok(Math.abs(v.cameraTransition.theta) < .18);
+ let previous = v.camera.position.clone();
+ while (v.cameraTransition) {
+ v.render(1 / 60);
+ assert.ok(v.camera.position.distanceTo(previous) < .015, 'continuous motion');
+ assert.ok(v.camera.position.z < -1.9, 'no long orbit around the front');
+ previous.copy(v.camera.position);
+ }
+});
+
+test('frame rate does not change the camera path or the time at which it settles', () => {
+ const a = viewer(), b = viewer();
+ const frame = { position: new Vector3(.5, .3, 2), target: new Vector3(.1, 0, 0) };
+ animate(a, frame); animate(b, frame);
+ for (let i = 0; i < 15; i++) a.render(1 / 30);
+ for (let i = 0; i < 30; i++) b.render(1 / 60);
+ assert.ok(a.camera.position.distanceTo(b.camera.position) < 1e-10);
+ assert.ok(a.cameraTransition && b.cameraTransition);
+ for (let i = 0; i < 60; i++) a.render(1 / 30);
+ for (let i = 0; i < 120; i++) b.render(1 / 60);
+ assert.equal(a.cameraTransition, null); assert.equal(b.cameraTransition, null);
+ assert.deepEqual(a.camera.position.toArray(), frame.position.toArray());
+ assert.deepEqual(b.camera.position.toArray(), frame.position.toArray());
+});
+
+test('slower screw phases retain authored paths, longer durations and serial tool scheduling', () => {
+ const original = { type:'screw', approachDuration:.45, engageDuration:.3, tightenDuration:2.4, retractDuration:.35,
+ axis:[0,0,-1], socketPosition:[0,0,0], toolQuaternion:[0,0,0,1], travel:.002, turns:3, direction:'clockwise', toolClearance:.01 };
+ const snapshot = JSON.stringify(original), motion = presentationScrewMotion(original);
+ const part = {position:[0,0,0], quaternion:[0,0,0,1], scale:[1,1,1], installOffset:[0,0,.05], installation:motion};
+ const one = new ScrewTransition(new Group(), part, new Group(), {tipPosition:[0,0,0]});
+ const two = new ScrewTransition(new Group(), part, new Group(), {tipPosition:[0,0,0]}, screwDuration(motion));
+ one.sample(one.duration - .001); two.sample(one.duration - .001);
+ assert.equal(one.tool.visible, true); assert.equal(two.instance.visible, false);
+ one.sample(one.duration); two.sample(one.duration);
+ assert.equal(one.tool.visible, false); assert.equal(two.instance.visible, true);
+ assert.deepEqual(one.instance.position.toArray(), part.position);
+ assert.equal(JSON.stringify(original), snapshot);
+ assert.equal(presentationScrewMotion({...original, approachDuration:4}).approachDuration, 4);
+});
diff --git a/tests/assembly-camera.test.js b/tests/assembly-camera.test.js
new file mode 100644
index 0000000..eaee29a
--- /dev/null
+++ b/tests/assembly-camera.test.js
@@ -0,0 +1,207 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { BoxGeometry, BufferGeometry, Float32BufferAttribute, Group, Mesh, PerspectiveCamera, Vector3 } from '../vendor/three/build/three.module.min.js';
+import { createAssemblyShot, assemblyShotFrame, assemblyShotFits, assemblyHeadDirection, headFacingView, watchAssemblyCameraInput } from '../js/assembly-camera.js';
+import { AssemblyViewer } from '../js/assembly-viewer.js';
+import { ScrewTransition } from '../js/assembly-motion.js';
+
+function fixture(screw = false) {
+ const parent = new Group(), instance = new Group();
+ parent.position.set(1, 2, 3);
+ parent.rotation.set(0.3, 0.8, 0.1);
+ parent.scale.setScalar(2);
+ parent.add(instance);
+ const part = { id: 'part', file: 'part.glb', position: [0.2, 0.3, 0.1], quaternion: [0, 0, 0, 1],
+ scale: [1, 1, 1], installOffset: [0, 0.2, 0] };
+ if (screw) part.installation = { socketPosition: [0, 0, 0.005], axis: [0, 0, -1], toolQuaternion: [0, 0, 0, 1], travel: 0.004, toolClearance: 0.012 };
+ instance.position.fromArray(part.position);
+ instance.position.add(new Vector3(...part.installOffset));
+ const template = new Mesh(new BoxGeometry(0.05, 0.07, 0.01));
+ const tool = { file: 'tool.glb', tipPosition: [0, 0, -0.05] };
+ const templates = new Map([['part.glb', template], ['tool.glb', new Mesh(new BoxGeometry(0.01, 0.01, 0.1))]]);
+ const instances = new Map([['part', instance]]), cache = new Map();
+ const shot = createAssemblyShot([{ part, tool: screw ? tool : null }], instances, templates, cache);
+ return { parent, instance, part, shot, cache, templates, instances, camera: new PerspectiveCamera(32, 1.6, 0.01, 50) };
+}
+const near = (a, b) => assert.ok(a.distanceTo(b) < 1e-8, `${a.toArray()} != ${b.toArray()}`);
+
+test('revealing mobile controls keeps closeup, while drag, pinch and wheel take camera control', () => {
+ const element = new EventTarget(), lifecycle = new AbortController();
+ let changes = 0;
+ watchAssemblyCameraInput(element, () => changes++, lifecycle.signal);
+ const send = (type, id = 1, x = 10, y = 10) => element.dispatchEvent(Object.assign(new Event(type), { pointerId: id, clientX: x, clientY: y }));
+ send('pointerdown'); send('pointermove', 1, 12, 12); send('pointerup');
+ assert.equal(changes, 0, 'tap/jitter must not exit closeup');
+ send('pointerdown'); send('pointermove', 1, 30); send('pointermove', 1, 40); send('pointerup');
+ assert.equal(changes, 1, 'one handoff per drag');
+ send('pointerdown'); send('pointerdown', 2); send('pointercancel'); send('pointercancel', 2);
+ assert.equal(changes, 2);
+ send('wheel'); assert.equal(changes, 3);
+ lifecycle.abort(); send('wheel'); assert.equal(changes, 3, 'dispose removes input listeners');
+});
+
+test('ordinary part shot stays fixed throughout insertion and replay without altering the model', () => {
+ const f = fixture(), json = JSON.stringify(f.part);
+ const first = assemblyShotFrame(f.shot, f.camera);
+ f.instance.position.fromArray(f.part.position);
+ const last = assemblyShotFrame(f.shot, f.camera);
+ near(first.target, last.target);
+ near(first.position, last.position);
+ assert.equal(JSON.stringify(f.part), json);
+ const bounds = f.cache.get('part.glb');
+ const replay = createAssemblyShot([{ part: f.part }], f.instances, f.templates, f.cache);
+ near(first.target, assemblyShotFrame(replay, f.camera).target);
+ near(first.position, assemblyShotFrame(replay, f.camera).position);
+ assert.equal(f.cache.get('part.glb'), bounds, 'reuse bounds rather than clone/analyse GLB per frame');
+});
+
+test('screw camera remains on the head side and does not orbit with tightening', () => {
+ const f = fixture(true);
+ f.instance.position.fromArray(f.part.position);
+ const first = assemblyShotFrame(f.shot, f.camera);
+ const outward = new Vector3(0, 0, 1).applyQuaternion(f.parent.quaternion);
+ assert.ok(f.shot.direction.dot(outward) > 0.5);
+ assert.ok(f.shot.radius > 0.1, 'frame the full tool sweep, not only the tiny screw');
+ for (const angle of [0.2, Math.PI, Math.PI * 2]) {
+ f.instance.quaternion.setFromAxisAngle(new Vector3(0, 0, -1), angle);
+ f.instance.position.add(new Vector3(0.01, 0.02, 0.03));
+ const next = assemblyShotFrame(f.shot, f.camera);
+ near(first.target, next.target);
+ near(first.position, next.position);
+ }
+});
+
+test('tightened framing contains the actual tool through docking, rotation and withdrawal', () => {
+ const f = fixture(true), tool = new Group();
+ tool.add(f.templates.get('tool.glb').clone());
+ Object.assign(f.part.installation, { approachDuration: 1, engageDuration: 1, tightenDuration: 2, retractDuration: 1, turns: 3, direction: 'clockwise' });
+ const transition = new ScrewTransition(f.instance, f.part, tool, {tipPosition: [0,0,-.05]});
+ for(let time=1;time<5;time+=.037) {
+ transition.sample(time); tool.updateWorldMatrix(true,true);
+ const mesh=tool.children[0], points=mesh.geometry.attributes.position;
+ for(let i=0;i {
+ const f = fixture(true), desktop = assemblyShotFrame(f.shot, f.camera);
+ f.camera.aspect = 320 / 620;
+ const mobile = assemblyShotFrame(f.shot, f.camera);
+ assert.ok(mobile.position.distanceTo(mobile.target) > desktop.position.distanceTo(desktop.target));
+ const halfFov = Math.atan(Math.tan(f.camera.fov * Math.PI / 360) * f.camera.aspect);
+ assert.ok(mobile.position.distanceTo(mobile.target) * Math.sin(halfFov) > f.shot.radius);
+ near(desktop.target, mobile.target);
+});
+
+test('ordinary parts preserve the current view instead of rotating to each insertion axis', () => {
+ const f = fixture(), direction = new Vector3(1, 0.2, -1).normalize();
+ for (const offset of [[0.1, 0, 0], [-0.1, 0, 0], [0, -0.1, 0]]) {
+ f.part.installOffset = offset;
+ const shot = createAssemblyShot([{ part: f.part }], f.instances, f.templates, f.cache, 1, direction);
+ near(shot.direction, direction);
+ }
+});
+
+test('generated screw head direction is respected even without a wrench animation',()=>{
+ const f=fixture();
+ f.part.focusDirection=[-1,0,0];
+ const outward=new Vector3(-1,0,0).applyQuaternion(f.parent.quaternion);
+ const shot=createAssemblyShot([{part:f.part}],f.instances,f.templates,f.cache,1,outward.clone().negate());
+ assert.ok(shot.direction.dot(outward)>.4);
+ assert.ok(shot.headDirection.distanceTo(outward)<1e-8);
+});
+
+test('nearby work reuses a fixed shot; out-of-frame or back-facing work needs a new shot', () => {
+ const f = fixture(true), frame = assemblyShotFrame(f.shot, f.camera);
+ f.camera.position.copy(frame.position);
+ assert.equal(assemblyShotFits(f.shot, f.camera, frame.target), true);
+ const adjacent = { ...f.shot, target: f.shot.target.clone().add(new Vector3(0.001, 0, 0)) };
+ assert.equal(assemblyShotFits(adjacent, f.camera, frame.target), true);
+ const behind = { ...adjacent, headDirection: f.shot.headDirection.clone().negate() };
+ assert.equal(assemblyShotFits(behind, f.camera, frame.target), false);
+ adjacent.target.x += 10;
+ assert.equal(assemblyShotFits(adjacent, f.camera, frame.target), false);
+});
+
+test('a whole-model view cannot count as a closeup just because a small part fits', () => {
+ const f = fixture(true), frame = assemblyShotFrame(f.shot, f.camera);
+ f.camera.position.copy(frame.position).sub(frame.target).multiplyScalar(2).add(frame.target);
+ assert.equal(assemblyShotFits(f.shot, f.camera, frame.target), false);
+});
+
+test('the stationary closeup contains the entry and final part without doubling the travel', () => {
+ const f = fixture();
+ const box = f.cache.get('part.glb');
+ for (const t of [0, .25, .5, .75, 1]) {
+ f.instance.position.fromArray(f.part.position).addScaledVector(new Vector3(...f.part.installOffset),t);
+ f.instance.updateWorldMatrix(true,false);
+ for (const x of [box.min.x,box.max.x]) for (const y of [box.min.y,box.max.y]) for (const z of [box.min.z,box.max.z]) {
+ const p = new Vector3(x,y,z).applyMatrix4(f.instance.matrixWorld);
+ assert.ok(p.distanceTo(f.shot.target) <= f.shot.radius);
+ }
+ }
+ assert.ok(f.shot.radius < .4,'avoid wasting the closeup on empty space');
+});
+
+test('joining temporarily frames the assembly without disabling subsequent closeups', () => {
+ const v=Object.create(AssemblyViewer.prototype);
+ v.closeupEnabled=true; v.stepIndex=0; v.config={steps:[{type:'join'}]};
+ let calls=0;
+ v.fitBuildView=options=>{ calls++; assert.equal(options.animate,true); };
+ v.refreshCloseup(true,undefined,true);
+ assert.equal(calls,1); assert.equal(v.closeupEnabled,true);
+ assert.equal(v.closeupShot,null);
+});
+
+test('legacy screw with zero travel derives head side from geometry once, retaining all transforms',()=>{
+ const f=fixture(), points=[];
+ for (const [x,r] of [[-.005,.002],[-.003,.002],[.005,.001]])
+ for (const y of [-r,r]) for(const z of [-r,r]) points.push(x,y,z);
+ const geometry=new BufferGeometry().setAttribute('position',new Float32BufferAttribute(points,3));
+ const mesh=new Mesh(geometry);mesh.rotation.z=.4;
+ const template=new Group();template.add(mesh);
+ const part={...f.part,file:'1-19-STP39-0.glb',installOffset:[0,0,0]};
+ const cache=new Map(), before=Array.from(geometry.attributes.position.array);
+ const direction=assemblyHeadDirection(part,f.instance,template,cache);
+ const expected=new Vector3(-1,0,0).applyQuaternion(mesh.quaternion).applyQuaternion(f.parent.quaternion);
+ near(direction,expected);
+ assert.equal(cache.size,1);
+ const saved=cache.get(part.file);
+ f.instance.position.x+=3;f.instance.rotation.y=2; // Moving/screwing cannot affect the inferred final side.
+ near(assemblyHeadDirection(part,f.instance,template,cache),direction);
+ assert.equal(cache.get(part.file),saved);
+ assert.deepEqual(Array.from(geometry.attributes.position.array),before);
+ assert.equal(assemblyHeadDirection({...part,file:'spacer.glb'},f.instance,template,cache),null);
+ assert.equal(assemblyHeadDirection({...part,file:'bolt.glb'},f.instance,new Mesh(new BoxGeometry()),cache),null);
+});
+
+test('head-facing camera switches back/front only as needed and can see underside fasteners',()=>{
+ let view=new Vector3(1,.25,-.4).normalize();
+ const front=new Vector3(1,0,0),back=new Vector3(-1,0,0);
+ near(headFacingView(view,front),view);
+ view=headFacingView(view,back);assert.ok(view.dot(back)>.5);
+ near(headFacingView(view,back),view);
+ const bottom=headFacingView(new Vector3(0,1,0),new Vector3(0,-1,0));
+ assert.ok(bottom.y<-.5);
+});
+
+test('normal grouped view changes to the screw head side even when work fits on screen',()=>{
+ const f=fixture(),v=Object.create(AssemblyViewer.prototype);
+ const head=new Vector3(-1,0,0), bounds=new BoxGeometry(.1,.1,.1);
+ bounds.computeBoundingBox();
+ v.config={playback:'grouped-v1',steps:[{groupId:'leg',parts:['part']}]};v.stepIndex=0;
+ v.finalPartBounds=new Map();v.assembledBounds=bounds.boundingBox;v.groupBounds=new Map();
+ v.camera=new PerspectiveCamera(32,1.6,.01,50);v.camera.position.set(1,.2,-.3);v.camera.lookAt(0,0,0);
+ v.controls={target:new Vector3()};v.currentWorkBounds=()=>bounds.boundingBox;
+ v.stepHeadDirection=()=>head;
+ let moves=0, animated;v.moveCamera=(frame,animate)=>{moves++;animated=animate;v.camera.position.copy(frame.position);v.controls.target.copy(frame.target);v.camera.lookAt(frame.target);};
+ v.fitBuildView({animate:true});
+ assert.equal(moves,1,'back-facing work cannot reuse an otherwise fitting shot');
+ assert.ok(v.camera.position.clone().sub(v.controls.target).normalize().dot(head)>.5);
+ assert.equal(animated,true,'head-side changes request a transition, not an instant cut');
+ v.fitBuildView({animate:true});assert.equal(moves,1,'same-side next screw reuses the shot');
+});
diff --git a/tests/assembly-framing.test.js b/tests/assembly-framing.test.js
new file mode 100644
index 0000000..054a651
--- /dev/null
+++ b/tests/assembly-framing.test.js
@@ -0,0 +1,27 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {Box3,PerspectiveCamera,Vector3} from '../vendor/three/build/three.module.min.js';
+import {buildWorkBounds,componentViewDirection,workBoundsFit} from '../js/assembly-framing.js';
+
+const box=(x,y,z,w,h,d)=>new Box3().setFromCenterAndSize(new Vector3(x,y,z),new Vector3(w,h,d));
+test('first installed base is framed at the work site, not the center of an invisible completed leg',()=>{
+ const base=box(0,.03,0,.1,.06,.08),top=box(0,.65,0,.15,.1,.12),whole=base.clone().union(top);
+ const bounds=buildWorkBounds(new Map([['base',base],['top',top]]),new Set(['base']),whole);
+ assert.ok(bounds.getCenter(new Vector3()).distanceTo(base.getCenter(new Vector3()))<1e-8);
+ assert.ok(bounds.getSize(new Vector3()).y{
+ const whole=box(0,.5,0,.5,1,.5),left=box(0,.2,-.2,.1,.4,.1),right=box(0,.2,.2,.1,.4,.1);
+ const a=componentViewDirection(left,whole),b=componentViewDirection(right,whole);
+ assert.ok(a.x>0&&b.x>0&&a.y>.3&&b.y>.3);
+ assert.ok(a.z<0&&b.z>0);assert.equal(a.x,b.x);
+});
+test('only off-frame work requires a new shot, and portrait bounds are checked against the actual camera',()=>{
+ const camera=new PerspectiveCamera(32,.5,.01,50);
+ camera.position.set(0,0,2);camera.lookAt(0,0,0);camera.updateProjectionMatrix();
+ assert.equal(workBoundsFit(box(0,0,0,.2,.2,.2),camera),true);
+ assert.equal(workBoundsFit(box(0,0,0,1.8,.2,.2),camera),false);
+ assert.equal(workBoundsFit(box(0,0,3,.2,.2,.2),camera),false);
+});
diff --git a/tests/assembly-memory.test.js b/tests/assembly-memory.test.js
index a72146f..2284d0b 100644
--- a/tests/assembly-memory.test.js
+++ b/tests/assembly-memory.test.js
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as THREE from 'three';
-import { assemblyTextureLimit, textureDimensions, resizeAssemblyImage, fitAssemblyTextures, disposeAssemblyObjects } from '../js/assembly-memory.js';
+import { disposeAssemblyObjects } from '../js/assembly-memory.js';
import { readLimited } from '../js/experience-packages.js';
const bitmap = (width = 1024, height = 1024) => ({ width, height, closed: 0, close() { this.closed++; } });
@@ -11,70 +11,6 @@ const scene = (...textures) => {
return root;
};
-test('a 243-file duck uses a bounded decoded and GPU texture budget on mobile', () => {
- const limit = assemblyTextureLimit(243, true);
- assert.equal(limit, 64);
- const bytes = 266 * limit ** 2 * 4 * (1 + 4 / 3);
- assert.ok(bytes < 16 * 1024 * 1024);
- assert.deepEqual(textureDimensions(2048, 1024, 128), { width: 128, height: 64 });
- assert.deepEqual(textureDimensions(32, 16, 128), { width: 32, height: 16 });
-});
-
-test('downsizes shared sources once without changing materials, geometry or placement', async () => {
- const original = bitmap(), texture = new THREE.Texture(original), clone = texture.clone();
- const root = scene(texture, clone); root.position.set(1, 2, 3);
- const before = root.children.map(mesh => ({ geometry: mesh.geometry, material: mesh.material,
- color: mesh.material.color.toArray(), normalScale: mesh.material.normalScale.toArray() }));
- let calls = 0;
- const stats = await fitAssemblyTextures(root, 128, { resize: async (_, w, h) => { calls++; return bitmap(w, h); } });
- assert.equal(calls, 1); assert.equal(original.closed, 1);
- assert.equal(texture.image, clone.image); assert.equal(texture.image.width, 128);
- assert.equal(stats.beforeBytes / stats.afterBytes, 64);
- root.children.forEach((mesh, i) => {
- assert.equal(mesh.geometry, before[i].geometry); assert.equal(mesh.material, before[i].material);
- assert.deepEqual(mesh.material.color.toArray(), before[i].color);
- assert.deepEqual(mesh.material.normalScale.toArray(), before[i].normalScale);
- assert.equal(mesh.material.metalness, 0.7); assert.equal(mesh.material.roughness, 0.2);
- });
- assert.deepEqual(root.position.toArray(), [1, 2, 3]);
- disposeAssemblyObjects(root);
- assert.equal(texture.image.closed, 1);
-});
-
-test('same bitmap in different sources stays alive until every source is replaced', async () => {
- const original = bitmap(); const a = new THREE.Texture(original), b = new THREE.Texture(original);
- let calls = 0;
- await fitAssemblyTextures(scene(a, b), 128, { resize: async (image, w, h) => {
- calls++; assert.equal(image.closed, 0); return bitmap(w, h);
- } });
- assert.equal(calls, 2); assert.equal(original.closed, 1);
-});
-
-test('close during texture resize releases the new bitmap and keeps cleanup possible', async () => {
- const controller = new AbortController(), original = bitmap(), small = bitmap(128, 128);
- const root = scene(new THREE.Texture(original));
- await assert.rejects(fitAssemblyTextures(root, 128, { signal: controller.signal, resize: async () => {
- controller.abort(); return small;
- } }), { name: 'AbortError' });
- assert.equal(small.closed, 1); assert.equal(original.closed, 0);
- disposeAssemblyObjects(root); assert.equal(original.closed, 1);
-});
-
-test('WebKit ignoring ImageBitmap resize options falls back to an actually smaller canvas', async () => {
- const originalCreate = globalThis.createImageBitmap, originalDocument = globalThis.document;
- const unscaled = bitmap(); let drawn = false;
- globalThis.createImageBitmap = async () => unscaled;
- globalThis.document = { createElement: () => ({ width: 0, height: 0, getContext: () => ({ drawImage: () => { drawn = true; } }) }) };
- try {
- const result = await resizeAssemblyImage(bitmap(), 128, 64);
- assert.equal(result.width, 128); assert.equal(result.height, 64);
- assert.equal(unscaled.closed, 1); assert.equal(drawn, true);
- } finally {
- if (originalCreate) globalThis.createImageBitmap = originalCreate; else delete globalThis.createImageBitmap;
- if (originalDocument) globalThis.document = originalDocument; else delete globalThis.document;
- }
-});
-
test('scene and template clones release each shared GPU resource and bitmap once', () => {
const image = bitmap(), root = scene(new THREE.Texture(image)), clone = root.clone(true);
const mesh = root.children[0], counts = { geometry: 0, material: 0, texture: 0 };
diff --git a/tests/assembly-visibility.test.js b/tests/assembly-visibility.test.js
new file mode 100644
index 0000000..489397c
--- /dev/null
+++ b/tests/assembly-visibility.test.js
@@ -0,0 +1,56 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { Group } from 'three';
+import { validatePackage, visibleAssemblyParts } from '../js/experience-packages.js';
+import { AssemblyViewer } from '../js/assembly-viewer.js';
+
+const ids = (start, end) => Array.from({ length:end - start + 1 }, (_, i) => `p${start+i}`);
+const fixture = () => ({ schemaVersion:1, kind:'assembly', unit:'meter',
+ files:[{path:'part.glb',bytes:1,sha256:'a'.repeat(64)}],
+ parts:ids(1,10).map(id=>({id,file:'part.glb',installOffset:[0,.05,0]})),
+ steps:ids(1,10).map((id,i)=>({id:`s${i+1}`,parts:[id],
+ ...(i>=2&&i<=7?{visibleParts:ids(3,i+1)}:{})})),
+});
+const validate = raw => validatePackage(raw,'assembly','https://example.com/assembly.json');
+
+test('plus subassembly hides 1–2, cumulatively installs 3–8, and step 9 restores earlier parts',()=>{
+ const pkg=validate(fixture());
+ for(const [index,expected] of [[0,ids(1,1)],[1,ids(1,2)],[2,ids(3,3)],
+ [3,ids(3,4)],[7,ids(3,8)],[8,ids(1,9)],[9,ids(1,10)],
+ [2,ids(3,3)],[null,ids(1,10)],[7,ids(3,8)]]) {
+ assert.deepEqual([...visibleAssemblyParts(pkg,index)],expected);
+ }
+});
+
+test('rejects unknown/future parts, hidden active parts, duplicates and invisible parents',()=>{
+ for(const visibleParts of [null,[],['p3','unknown'],['p3','p10'],['p1'],['p3','p3']]) {
+ const raw=fixture();raw.steps[2].visibleParts=visibleParts;
+ assert.throws(()=>validate(raw));
+ }
+ const raw=fixture();raw.parts[2].parentId='p1';
+ assert.throws(()=>validate(raw),/父零件/);
+});
+
+test('real player restores hidden assemblies without replaying them; only the new part moves',()=>{
+ const original=globalThis.matchMedia;
+ globalThis.matchMedia=()=>({matches:false});
+ try {
+ const v=Object.create(AssemblyViewer.prototype);
+ v.config=validate(fixture());
+ v.parts=new Map(v.config.parts.map(p=>[p.id,new Group()]));
+ v.transitions=[];v.stepIndex=null;
+ v.renderer={shadowMap:{},render(){}};v.controls={update(){return false;}};
+ v.loop={invalidate(){}};v.resetView=()=>{};v.notifyMotion=()=>{};v.refreshCloseup=()=>{};
+ const visible=()=>[...v.parts].filter(([,p])=>p.visible).map(([id])=>id);
+ v.setStep(7,true);assert.deepEqual(visible(),ids(3,8));
+ assert.equal(v.transitions.length,1);assert.equal(v.parts.get('p8').position.y,.05);
+ v.setStep(8,true);assert.deepEqual(visible(),ids(1,9));
+ assert.equal(v.transitions.length,1);
+ for(const id of ids(1,8)) assert.deepEqual(v.parts.get(id).position.toArray(),[0,0,0]);
+ assert.equal(v.parts.get('p9').position.y,.05);
+ v.render(3);assert.equal(v.parts.get('p9').position.y,0);
+ v.setStep(2,false);assert.deepEqual(visible(),['p3']);
+ assert.equal(v.transitions.length,0);
+ v.setStep(null,false);assert.deepEqual(visible(),ids(1,10));
+ } finally {globalThis.matchMedia=original;}
+});
diff --git a/tests/build-versions.test.js b/tests/build-versions.test.js
new file mode 100644
index 0000000..30c8efb
--- /dev/null
+++ b/tests/build-versions.test.js
@@ -0,0 +1,50 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { versionSiteAssets } from '../scripts/lib/version-site-assets.mjs';
+
+test('HTML entries, styles and transitive lazy modules share a build version', async t => {
+ const root = mkdtempSync(join(tmpdir(), 'make-version-'));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ mkdirSync(join(root, 'js'));
+ writeFileSync(join(root, 'package.json'), '{"type":"module"}');
+ const put = (file, text) => writeFileSync(join(root, file), text);
+ put('js/entry.js', `import { value } from './middle.js'; export const get = async () => value + (await import('./late.js')).value;`);
+ put('js/middle.js', `export { value } from './budget.js';`);
+ put('js/late.js', `import { value } from './budget.js'; export { value };`);
+ put('js/budget.js', `export const value = 10;`);
+ put('js/vendor-test.js', `import * as THREE from 'three'; import { x } from '../vendor/x.js'; export const text = "import('./fake.js')"; console.log(THREE, x);`);
+ put('index.html', ``);
+ const entry = pathToFileURL(join(root, 'js/entry.js')).href;
+ await versionSiteAssets(root, 'first', ['index.html']);
+ assert.equal(await (await import(entry + '?v=first')).get(), 20);
+ put('js/budget.js', `export const value = 40;`);
+ await versionSiteAssets(root, 'second', ['index.html']);
+ // First graph is still cached. A fresh entry must not reuse its old dependency.
+ assert.equal(await (await import(entry + '?v=second')).get(), 80);
+ for (const file of ['entry.js', 'middle.js', 'late.js']) {
+ const code = readFileSync(join(root, 'js', file), 'utf8');
+ assert.match(code, /\?v=second/);
+ assert.doesNotMatch(code, /v=first/);
+ }
+ const html = readFileSync(join(root, 'index.html'), 'utf8');
+ assert.match(html, /entry\.js\?v=second/);
+ assert.match(html, /assembly\.css\?v=second/);
+ assert.match(html, /style\.css\?v=second/);
+ assert.match(html, /src="\/vendor\/keep\.js"/);
+ const vendor = readFileSync(join(root, 'js/vendor-test.js'), 'utf8');
+ assert.match(vendor, /from "three"/);
+ assert.match(vendor, /from "\.\.\/vendor\/x.js"/);
+ assert.match(vendor, /import\('\.\/fake.js'\)/);
+});
+
+test('missing app dependencies fail the build before packaging', async t => {
+ const root = mkdtempSync(join(tmpdir(), 'make-version-missing-'));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ mkdirSync(join(root, 'js'));
+ writeFileSync(join(root, 'js/entry.js'), `import './missing.js';`);
+ await assert.rejects(versionSiteAssets(root, 'test', []), /Missing application module/);
+});
diff --git a/tests/document-images.test.js b/tests/document-images.test.js
index bd4931f..a54a52e 100644
--- a/tests/document-images.test.js
+++ b/tests/document-images.test.js
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { documentImageUrl } from '../js/document-images.js';
+import { documentImageUrl, repositoryImageType } from '../js/document-images.js';
const rawUrl = (path) => `/api/files?path=${encodeURIComponent(path)}`;
test('resolves images relative to the current markdown file before insertion', () => {
@@ -9,6 +9,16 @@ test('resolves images relative to the current markdown file before insertion', (
assert.equal(documentImageUrl('/media/duck.png', { filePath: 'docs/guide.md', rawUrl }), rawUrl('media/duck.png'));
});
+test('repository images get a declared image MIME; external images retain native loading', () => {
+ assert.equal(repositoryImageType('双腿结构示意.svg', { rawUrl }), 'image/svg+xml');
+ assert.equal(repositoryImageType('../images/duck.PNG?ref=main', { rawUrl }), 'image/png');
+ assert.equal(repositoryImageType('https://host/image.svg', { rawUrl }), '');
+ assert.equal(repositoryImageType('//host/image.png', { rawUrl }), '');
+ assert.equal(repositoryImageType('data:image/svg+xml,hi', { rawUrl }), '');
+ assert.equal(repositoryImageType('image.svg'), '');
+ assert.equal(repositoryImageType('file.html', { rawUrl }), '');
+});
+
test('preserves external and signed image addresses exactly', () => {
for (const src of ['https://github.com/user-attachments/assets/abc', 'https://oss.example/图.png?signature=x%2Fy', '//cdn.example/img.png', 'data:image/png;base64,aA==']) {
assert.equal(documentImageUrl(src, { rawUrl }), src);
diff --git a/tests/grouped-assembly.test.js b/tests/grouped-assembly.test.js
new file mode 100644
index 0000000..b629362
--- /dev/null
+++ b/tests/grouped-assembly.test.js
@@ -0,0 +1,100 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { Vector3, Group } from 'three';
+import { validatePackage, visibleAssemblyParts } from '../js/experience-packages.js';
+import { AssemblyViewer } from '../js/assembly-viewer.js';
+import { ASSEMBLY_PACE } from '../js/assembly-animation.js';
+
+const fixture = () => ({ schemaVersion:1, kind:'assembly', unit:'meter', playback:'grouped-v1',
+ files:[{path:'part.glb',bytes:1,sha256:'a'.repeat(64)}],
+ parts:[{id:'base'}, {id:'bolt',parentId:'base'}, {id:'arm'}, {id:'nut'}].map(p=>({...p,file:'part.glb',installOffset:[0,.03,0]})),
+ groups:[{id:'leg',parts:['base','bolt']},{id:'hand',parts:['arm']}],
+ steps:[{id:'a',groupId:'leg',parts:['base']},{id:'b',groupId:'leg',parts:['bolt']},{id:'c',groupId:'hand',parts:['arm']},
+ {id:'j1',type:'join',groupId:'leg',parts:['base','bolt'],installOffset:[.1,0,0]},
+ {id:'j2',type:'join',groupId:'hand',parts:['arm'],installOffset:[0,.1,0]}, {id:'d',parts:['nut']}],
+});
+const validate = raw => validatePackage(raw,'assembly','https://example.com/manifest.json');
+
+test('isolates local builds, reveals only joined components, supports arbitrary backward/forward jumps and whole view',()=>{
+ const pkg=validate(fixture());
+ for (const [step,expected] of [[1,['base','bolt']],[2,['arm']],[4,['base','bolt','arm']], [0,['base']],
+ [3,['base','bolt']],[5,['base','bolt','arm','nut']],[null,['base','bolt','arm','nut']],[2,['arm']]]) {
+ assert.deepEqual([...visibleAssemblyParts(pkg,step)],expected);
+ }
+});
+
+test('keeps generated head views and distinguishes unverified presentation joins',()=>{
+ const raw=fixture();raw.parts[0].focusDirection=[0,1,0];raw.steps[3].pathStatus='presentation';
+ const pkg=validate(raw);
+ assert.deepEqual(pkg.parts[0].focusDirection,[0,1,0]);assert.equal(pkg.steps[3].pathStatus,'presentation');
+ raw.parts[0].focusDirection=[0,0,0];assert.throws(()=>validate(raw));
+});
+
+test('camera settles before installation and remains stationary while the part moves',()=>{
+ const v=Object.create(AssemblyViewer.prototype), part=new Group(), camera=new Group();
+ part.position.set(0,1,0);
+ v.camera=camera;v.controls={target:new Vector3(),update(){return false;}};
+ v.renderer={shadowMap:{},domElement:{style:{}},render(){}};v.notifyMotion=()=>{};v.loop={invalidate(){}};
+ const original=globalThis.matchMedia;globalThis.matchMedia=()=>({matches:false});
+ camera.position.set(0,0,2);
+ try {v.moveCamera({position:new Vector3(1,1,2),target:new Vector3(0,.5,0)},true);}
+ finally {globalThis.matchMedia=original;}
+ v.transitions=[{instance:part,from:part.position.clone(),target:new Vector3(),duration:1,elapsed:0}];
+ const duration=v.cameraTransition.motionDuration;
+ v.render(.2);assert.equal(part.position.y,1);assert.ok(camera.position.length()>0);
+ v.render(duration-.2);assert.equal(part.position.y,1);
+ assert.ok(v.cameraTransition,'hold the settled shot briefly before insertion');
+ v.render(ASSEMBLY_PACE.cameraHold);assert.equal(part.position.y,1);assert.equal(v.cameraTransition,null);
+ const shot=camera.position.clone();v.render(.2);
+ assert.ok(part.position.y<1);assert.deepEqual(camera.position.toArray(),shot.toArray());
+ v.render(1);assert.equal(part.position.y,0);
+});
+
+test('rejects unfinished, repeated, partial and out-of-order components, and cross-group parenting',()=>{
+ const cases=[
+ x=>x.steps.splice(1,1),
+ x=>x.steps[3].parts=['base'],
+ x=>x.steps.splice(4,0,{...x.steps[3],id:'duplicate'}),
+ x=>[x.steps[0],x.steps[2]]=[x.steps[2],x.steps[0]],
+ x=>x.steps.splice(3,0,x.steps.pop()),
+ x=>x.parts[2].parentId='base',
+ x=>delete x.playback,
+ x=>x.steps[4].installOffset=[0,NaN,0],
+ x=>x.groups[1].parts.push('bolt'),
+ x=>x.steps.splice(4,1),
+ ];
+ for(const mutate of cases) {const x=fixture();mutate(x);assert.throws(()=>validate(x));}
+});
+
+test('real player replays joins rigidly, never repeats screw operations, restores final poses on seek and whole view',()=>{
+ const original=globalThis.matchMedia;
+ globalThis.matchMedia=()=>({matches:false});
+ try {
+ const v=Object.create(AssemblyViewer.prototype);
+ v.config=validate(fixture());
+ v.config.parts[1].installation={type:'screw'}; // Joining must not start another screw operation.
+ v.parts=new Map(v.config.parts.map(p=>[p.id,new Group()]));
+ v.parts.get('base').add(v.parts.get('bolt'));
+ v.transitions=[];v.stepIndex=null;
+ v.renderer={shadowMap:{},render(){}};v.controls={update(){return false;}};v.loop={invalidate(){}};
+ v.resetView=()=>{};v.notifyMotion=()=>{};v.refreshCloseup=()=>{};
+ const visible=()=>[...v.parts].filter(([,p])=>p.visible).map(([id])=>id);
+ v.setStep(3,true);
+ assert.equal(v.closeupEnabled,true,'entering a join also enables the following installation closeups');
+ assert.equal(v.transitions.length,1);
+ assert.deepEqual(v.parts.get('base').position.toArray(),[.1,0,0]);
+ assert.deepEqual(v.parts.get('bolt').position.toArray(),[0,0,0]);
+ v.parts.get('base').updateMatrixWorld(true);
+ assert.deepEqual(v.parts.get('bolt').getWorldPosition(new Vector3()).toArray(),[.1,0,0]);
+ v.render(2);
+ assert.deepEqual(v.parts.get('base').position.toArray(),[0,0,0]);
+ v.setStep(2,false);assert.deepEqual(visible(),['arm']);
+ assert.equal(v.closeupEnabled,true);
+ v.setCloseup(false,{restore:false});
+ v.setStep(4,true);assert.deepEqual(visible(),['base','bolt','arm']);
+ assert.equal(v.closeupEnabled,false,'respect manual camera mode across steps');
+ v.setStep(0,false);assert.deepEqual(visible(),['base']);
+ v.setStep(null,false);assert.deepEqual(visible(),['base','bolt','arm','nut']);
+ for(const part of v.parts.values()) assert.deepEqual(part.position.toArray(),[0,0,0]);
+ } finally {globalThis.matchMedia=original;}
+});
diff --git a/tests/numbered-assembly.test.js b/tests/numbered-assembly.test.js
new file mode 100644
index 0000000..f580730
--- /dev/null
+++ b/tests/numbered-assembly.test.js
@@ -0,0 +1,120 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { Document, NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { draco } from '@gltf-transform/functions';
+import draco3d from 'draco3dgltf';
+import { BufferGeometry, Float32BufferAttribute, BoxGeometry } from 'three';
+import { generate } from '../scripts/generate-numbered-assembly.mjs';
+import { numberedInput } from '../scripts/lib/numbered-parts.mjs';
+import { screwHead, planGroupEntry } from '../scripts/lib/numbered-axis.mjs';
+
+const workspace=t=>{const dir=mkdtempSync(path.join(os.tmpdir(),'make-parts-'));t.after(()=>rmSync(dir,{recursive:true,force:true}));return dir;};
+test('orders by numeric group and local sequence, reports missing/duplicate/unnumbered files together', t=>{
+ const p=workspace(t);writeFileSync(path.join(p,'whole.glb'),'');
+ for(let i=10;i>=1;i--){
+ const dir=path.join(p,i+'部');mkdirSync(dir);
+ for(let j=12;j>=1;j--)writeFileSync(path.join(dir,(j===11?'2':'1')+'-'+j+'-零件.007.glb'),'');
+ }
+ const input=numberedInput(p);assert.equal(input.parts[10].number,11);assert.equal(input.parts[108].group.number,10);
+ const dir=path.join(p,'1部');rmSync(path.join(dir,'1-3-零件.007.glb'));
+ writeFileSync(path.join(dir,'1-2-重复.glb'),'');writeFileSync(path.join(dir,'螺丝.012.glb'),'');
+ assert.throws(()=>numberedInput(p),e=>['缺号:3','重复编号 2','螺丝.012.glb'].every(s=>e.message.includes(s)));
+});
+test('identifies either screw head end, declines a symmetric shaft',()=>{
+ function part(head,tail){
+ const all=[];
+ for(const [z,r] of [[-.008,tail],[0,head]])for(let i=0;i<24;i++)all.push(r*Math.cos(i*Math.PI/12),r*Math.sin(i*Math.PI/12),z);
+ return new BufferGeometry().setAttribute('position',new Float32BufferAttribute(all,3));
+ }
+ assert.deepEqual(screwHead(part(.002,.001)).vector.toArray(),[0,0,1]);
+ assert.deepEqual(screwHead(part(.001,.002)).vector.toArray(),[0,0,-1]);
+ assert.equal(screwHead(part(.001,.001)),null);
+});
+test('Draco parts: restores final pose despite loose transform, binds grouped upload paths, rejects wrong mesh',async t=>{
+ const p=workspace(t), dir=path.join(p,'source'), group=path.join(dir,'1测试');mkdirSync(group,{recursive:true});
+ const io=new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({'draco3d.encoder':await draco3d.createEncoderModule()});
+ async function writeGlb(file,entries) {
+ const d=new Document(), b=d.createBuffer(), s=d.createScene();
+ for(const [name,x,w] of entries) {
+ const g=new BoxGeometry(w,.008,.006);
+ const a=d.createAccessor().setType('VEC3').setArray(g.attributes.position.array).setBuffer(b);
+ const idx=d.createAccessor().setType('SCALAR').setArray(g.index.array).setBuffer(b);
+ const prim=d.createPrimitive().setAttribute('POSITION',a).setIndices(idx);
+ s.addChild(d.createNode(name).setTranslation([x,0,0]).setMesh(d.createMesh().addPrimitive(prim)));
+ }
+ await d.transform(draco());await io.write(file,d);
+ }
+ await writeGlb(path.join(dir,'整机.glb'),[['left',.1,.02],['right',.3,.015]]);
+ await writeGlb(path.join(group,'1-1-甲.glb'),[['left',-.1,.02]]);
+ await writeGlb(path.join(group,'1-2-乙.glb'),[['right',0,.015]]);
+ const out=path.join(p,'out'),r=await generate(dir,out,()=>{});
+ const raw=JSON.parse(readFileSync(path.join(out,'整机-装配步骤.json')));
+ assert.equal(r.needReview,0);assert.equal(r.steps,2);assert.equal(raw.files[0].path,'1测试/1-1-甲.glb');
+ assert.ok(Math.abs(raw.parts[0].position[0]-.2)<1e-6);assert.ok(Math.hypot(...raw.parts[1].installOffset)>0);
+ // Whole model may be external; local components are built independently and
+ // joined before the final folder's fasteners. No geometry is re-exported.
+ const third=path.join(dir,'2总装');mkdirSync(third);
+ await writeGlb(path.join(third,'2-1-丙.glb'),[['final',.5,.01]]);
+ const last=path.join(dir,'3总装');mkdirSync(last);
+ await writeGlb(path.join(last,'3-1-丁.glb'),[['cap',.7,.01]]);
+ const external=path.join(p,'外部整机.glb');
+ await writeGlb(external,[['left',.1,.02],['right',.3,.015],['final',.5,.01],['cap',.7,.01]]);
+ const groupedOut=path.join(p,'grouped');
+ const grouped=await generate(dir,groupedOut,()=>{},{reference:external,finalGroup:3});
+ const groupedRaw=JSON.parse(readFileSync(path.join(groupedOut,'外部整机-装配步骤.json')));
+ assert.equal(grouped.steps,6);assert.equal(groupedRaw.steps[3].type,'join');
+ assert.equal(groupedRaw.steps[5].groupId,undefined);
+ assert.equal(grouped.records.find(r=>r.id==='p-2-1').status,'foundation');
+ assert.deepEqual(groupedRaw.groups[0].parts,['p-1-1','p-1-2']);
+ rmSync(third,{recursive:true});
+ rmSync(last,{recursive:true});
+ await writeGlb(path.join(group,'1-2-乙.glb'),[['right',0,.025]]);
+ const invalid=path.join(p,'invalid');await assert.rejects(generate(dir,invalid,()=>{}),/网格不一致/);assert.equal(existsSync(invalid),false);
+});
+
+test('compact prefixes keep both digits and extra caps retain original relative paths', t=>{
+ const dir=workspace(t),g=path.join(dir,'1部');mkdirSync(g);
+ writeFileSync(path.join(dir,'整机.glb'),'');
+ for(let i=1;i<=13;i++)writeFileSync(path.join(g,`1-${i}STP39-14.glb`),'');
+ writeFileSync(path.join(g,'1-附加-端盖.glb'),'');
+ assert.throws(()=>numberedInput(dir),/附加件/);
+ const {parts}=numberedInput(dir,{extraBefore:13});
+ assert.equal(parts[9].number,10);
+ assert.equal(parts[9].name,'STP39-14');
+ assert.deepEqual(parts.slice(-2).map(p=>p.path),['1部/1-附加-端盖.glb','1部/1-13STP39-14.glb']);
+});
+
+test('a threaded pilot hole admits an axial preview but a solid plate or an obstructed head does not',async()=>{
+ const {CylinderGeometry,Matrix4,Vector3}=await import('three');
+ const {mergeGeometries}=await import('three/addons/utils/BufferGeometryUtils.js');
+ const {collider}=await import('../scripts/lib/assembly-axis-planner.mjs');
+ const {threadFit}=await import('../scripts/lib/thread-fit.mjs');
+ const shaft=new CylinderGeometry(.001,.001,.006,32).translate(0,-.003,0);
+ const cap=new CylinderGeometry(.002,.002,.0016,32).translate(0,.0008,0);
+ const local=mergeGeometries([shaft,cap]);local.computeBoundingBox();
+ const around=bore=>{
+ const rim=new CylinderGeometry(bore,bore,.006,48,1,true).translate(0,-.003,0);
+ return [collider('rim',rim)];
+ };
+ const check=obstacles=>threadFit(local,new Matrix4(),new Vector3(0,1,0),obstacles,.02);
+ assert.equal(check(around(.00089))?.status,'visual-thread-fit');
+ assert.equal(check(around(.00062))?.status,'visual-bore-axis');
+ const block=collider('plate',new BoxGeometry(.01,.00001,.01).translate(0,-.003,0));
+ assert.equal(check([block]),null);
+ const lip=collider('lip',new BoxGeometry(.0001,.00001,.0001).translate(.0016,.003,0));
+ assert.equal(check([...around(.00089),lip]),null);
+});
+
+test('group placement always has a visible move; blocked presentation paths stay explicitly unverified',async()=>{
+ const {collider}=await import('../scripts/lib/assembly-axis-planner.mjs');
+ const moving=[collider('moving',new BoxGeometry(.01,.01,.01))];
+ const first=planGroupEntry(moving,[]);
+ assert.equal(first.status,'foundation');assert.ok(Math.hypot(...first.offset)>0);
+ const blocked=planGroupEntry(moving,[collider('closed shell',new BoxGeometry(.06,.06,.06))]);
+ assert.equal(blocked.status,'review-path');assert.equal(blocked.presentationOnly,true);
+ assert.ok(Math.hypot(...blocked.offset)>0);assert.ok(blocked.checks.length>0);
+});
diff --git a/tests/walking-lifecycle.test.js b/tests/walking-lifecycle.test.js
new file mode 100644
index 0000000..0b793b0
--- /dev/null
+++ b/tests/walking-lifecycle.test.js
@@ -0,0 +1,36 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { disposeWalkingFrame, walkingErrorMessage } from '../js/walking-lifecycle.js';
+
+function fixture() {
+ const target = new EventTarget(), posted = [];
+ let removed = 0;
+ const child = { postMessage: (...args) => posted.push(args) };
+ const frame = { contentWindow: child, getAttribute: () => '/play/robots/index.html', remove: () => removed++ };
+ const message = (channel, origin = 'https://example.com', source = child) => {
+ const event = new Event('message');
+ Object.assign(event, { origin, source, data: { type: 'vibemake:walk-disposed', channel } });
+ target.dispatchEvent(event);
+ };
+ return { frame, message, posted, removed: () => removed, options: { eventTarget: target, origin: 'https://example.com', timeoutMs: 25 } };
+}
+test('iframe is removed only after a trusted disposal acknowledgment', async () => {
+ const f = fixture();
+ const pending = disposeWalkingFrame(f.frame, 'test', f.options);
+ assert.equal(f.posted[0][0].type, 'vibemake:walk-dispose');
+ f.message('other'); f.message('test', 'https://other.example'); f.message('test', 'https://example.com', {});
+ assert.equal(f.removed(), 0);
+ f.message('test');
+ await pending;
+ assert.equal(f.removed(), 1);
+});
+test('failed startup cannot retain its iframe indefinitely', async () => {
+ const f = fixture();
+ await disposeWalkingFrame(f.frame, 'test', f.options);
+ f.message('test');
+ assert.equal(f.removed(), 1);
+});
+test('memory failure is explained as browser allocation failure, other errors preserved', () => {
+ assert.match(walkingErrorMessage('no available backend found. ERR: [wasm] RangeError: Out of memory'), /浏览器.*分配内存/);
+ assert.equal(walkingErrorMessage('robot.json invalid'), 'robot.json invalid');
+});
diff --git a/生成装配步骤.command b/生成装配步骤.command
new file mode 100755
index 0000000..8c95127
--- /dev/null
+++ b/生成装配步骤.command
@@ -0,0 +1,28 @@
+#!/bin/zsh
+set -eu
+cd -- "${0:A:h}"
+if (( $# )); then
+ source_dir=$1
+else
+ source_dir=$(osascript -e 'POSIX path of (choose folder with prompt "选择包含编号部位文件夹的零件父目录")') || exit 0
+fi
+source_dir=${source_dir:A}
+output_dir="${source_dir}-装配输出-$(date +%Y%m%d-%H%M%S)"
+extra_files=("$source_dir"/*/[0-9]*附加*.glb(N))
+extra_args=()
+whole_models=("$source_dir"/*.glb(N) "$source_dir"/*.GLB(N))
+if (( ${#whole_models} != 1 )); then
+ reference_file=$(osascript -e 'POSIX path of (choose file with prompt "选择与这些零件对应的整机 GLB")') || exit 0
+ extra_args+=(--reference "$reference_file")
+fi
+play_mode=$(osascript -e 'button returned of (display dialog "部件预装后总装:前面各文件夹独立安装,最后一个文件夹之前合装全部部件,再安装最后一组散件。\n\n累计装配:始终保留之前的所有零件。" buttons {"取消", "累计装配", "部件预装后总装"} default button "部件预装后总装" cancel button "取消" with title "选择装配流程")') || exit 0
+if [[ "$play_mode" == "部件预装后总装" ]]; then
+ final_group=$(node --input-type=module -e 'import fs from "node:fs"; const groups=fs.readdirSync(process.argv[1],{withFileTypes:true}).filter(e=>e.isDirectory()).map(e=>Number(/^\d+/.exec(e.name)?.[0])).filter(Number.isFinite); console.log(Math.max(...groups));' "$source_dir")
+ extra_args+=(--final-group "$final_group")
+fi
+if (( ${#extra_files} )); then
+ extra_position=$(osascript -e 'text returned of (display dialog "每个部位的附加件要插在哪个步号之前?填写步号,或填写 end 放在各组末尾。" default answer "" with title "附加件的顺序")') || exit 0
+ extra_args+=(--extra-before "$extra_position")
+fi
+npm run assembly:generate -- "$source_dir" "$output_dir" "${extra_args[@]}"
+open "$output_dir"