From 32098ef433a860e504541da8a752ff64c976709f Mon Sep 17 00:00:00 2001 From: Jerry <99706807@qq.com> Date: Fri, 13 Nov 2026 16:54:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E7=BC=96=E5=8F=B7=E8=A3=85?= =?UTF-8?q?=E9=85=8D=E7=94=9F=E6=88=90=E5=B7=A5=E5=85=B7=E3=80=81=E5=88=86?= =?UTF-8?q?=E7=BB=84=E5=90=88=E8=A3=85=E4=B8=8E=E8=B5=84=E6=BA=90=E5=8A=A0?= =?UTF-8?q?=E8=BD=BD=E5=85=BC=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/assembly-screw-animation.md | 1 + docs/numbered-glb-assembly.md | 23 +++- js/assembly-camera.js | 2 +- js/assembly-groups.js | 28 ++++- js/assembly-motion.js | 4 +- js/assembly-viewer.js | 8 +- js/experience-packages.js | 28 +++-- js/project-resources.js | 22 +++- package.json | 1 + scripts/assembly-motion.test.mjs | 10 +- scripts/assembly-tool.html | 123 +++++++++++++++++++++ scripts/assembly-tool.mjs | 104 ++++++++++++++++++ scripts/experience-packages.test.mjs | 12 +- scripts/generate-numbered-assembly.mjs | 114 +++++++++++++++---- scripts/lib/numbered-axis.mjs | 3 +- scripts/lib/numbered-parts.mjs | 63 ++++++++--- scripts/lib/numbered-schedule.mjs | 43 ++++++++ scripts/lib/numbered-tool.mjs | 145 +++++++++++++++++++++++++ scripts/project-resources.test.mjs | 24 ++++ tests/grouped-assembly.test.js | 11 +- tests/numbered-assembly.test.js | 81 +++++++++++++- tests/numbered-schedule.test.js | 60 ++++++++++ 生成装配步骤.command | 4 +- 23 files changed, 839 insertions(+), 75 deletions(-) create mode 100644 scripts/assembly-tool.html create mode 100644 scripts/assembly-tool.mjs create mode 100644 scripts/lib/numbered-schedule.mjs create mode 100644 scripts/lib/numbered-tool.mjs create mode 100644 tests/numbered-schedule.test.js diff --git a/docs/assembly-screw-animation.md b/docs/assembly-screw-animation.md index ad6be62..2745d60 100644 --- a/docs/assembly-screw-animation.md +++ b/docs/assembly-screw-animation.md @@ -55,6 +55,7 @@ | `socketPosition` | 工具插入后的端点位置,相对螺丝 GLB 场景根坐标;此处在头部表面下 0.9 mm。也是旋转轴经过的点。 | | `axis` | 螺丝局部坐标下的插入方向,必须是单位向量。本批螺丝轴是局部 -Z;经零件自身和父级四元数转换,不是写死世界 -Z。 | | `toolQuaternion` | 工具 GLB 坐标到螺丝局部坐标的旋转,`[x,y,z,w]`。本工具绕局部 Z 转 30°,让六角边对齐孔口。 | +| `toolScale` | 可选工具显示比例,默认 1。缩放后播放器重新计算端点位置,使工具尖端仍与对接点重合。 | | `direction` | 从工具一侧朝孔内看,`clockwise` 为顺时针,`counterclockwise` 为逆时针。 | | `turns` | 旋转整数圈,1–20。以整数圈结束,保证回到原 JSON 的最终朝向。 | | `travel` | 最后边转边拧入的距离,单位米。与已有 `installOffset` 分开:后者是零件起始偏移,使用父级坐标。 | diff --git a/docs/numbered-glb-assembly.md b/docs/numbered-glb-assembly.md index 6f5a82e..7459587 100644 --- a/docs/numbered-glb-assembly.md +++ b/docs/numbered-glb-assembly.md @@ -1,6 +1,8 @@ # 从编号 GLB 文件夹生成装配步骤 -Mac 双击项目根目录的 **生成装配步骤.command**,选择源文件夹,整机不在根目录时再选择整机 GLB,然后选择“部件预装后总装”或“累计装配”。完成后 Finder 会打开新的输出目录。只把里面的 **整机名-装配步骤.json** 上传到后台“拼装步骤”。核对记录不用上传。需要本项目的 Node.js 与依赖(首次安装运行 `npm ci`)。也可从项目根目录运行: +本地网页工具用 `npm run assembly:tool` 启动,打开 `http://127.0.0.1:8095/`,选择整机 GLB 与分件文件夹。生成后下载装配 JSON 和核对报告,后台「拼装步骤」只需上传装配 JSON。文件在本机处理,首次使用需运行 `npm ci`。本地页面接受小于 256 MiB 的请求,较大模型可以用下面的命令行方式。 + +Mac 双击项目根目录的 **生成装配步骤.command**,选择源文件夹,整机不在根目录时再选择整机 GLB,然后选择“按目录和标记装配”或“部件预装后总装”。完成后 Finder 会打开新的输出目录。只把里面的 **整机名-装配步骤.json** 上传到后台“拼装步骤”。核对记录不用上传。也可从项目根目录运行: ```sh npm run assembly:generate -- "/路径/机器人分组" "/路径/新的输出目录" @@ -20,6 +22,9 @@ npm run assembly:generate -- "/路径/机器人分组" "/路径/新的输出目 ``` - 整机可以放在根目录,也可独立存放并用 `--reference` 指定。各一级部位目录从 1 连续编号;每组从 1 连续编零件号,一件一步。不读 Finder 排列、修改时间或 Blender 实例后缀。文件支持“组-步-名称.glb”或“步-名称.glb”。所属部位以**目录**为准,两条腿可复用同一套步骤前缀。组内缺号、重号和未编号会一起报出。 +- 整机单独选择时,零件也可以全部平铺在一个目录内。连续 `组+步` 文件组成独立展示段,接回常规步后恢复此前装好的零件。安装方向按该步可见的已装件检查。 +- 默认每个大组件独立展示。含小组件的目录按 `5A`、`5B` 等字母顺序单独预装,最后进入 `!5` 或 `!5`,显示本大组件的全部已装零件再安装合装散件。 +- 最外层 `#11` 目录先插入十个合装步骤,让第 1~10 个已完成大组件按编号逐个移入整机位置,再安装第 11 目录的散件,不一次性显示全部组件。组内的 `#8-41` 先保留第 8 组当前已装件,再让第 1~7 个组件逐个移入,最后安装第 41 件。连续的 `#8-42` 等沿用已合装状态,不重复合装;没有 `#` 的 `8-47` 恢复第 8 组范围,`8+47` 则从第 47 件开始独立显示。之后再次进入 `#` 段会重新播放逐组汇合。按数字步号排序,原始相对路径保留 `#`,下载地址编码为 `%23`。 - 后台整机选根目录 GLB;零件选择包含全部编号部位的父目录。可以单独把部位文件夹放进一个“零件模型”目录再传,须保留组名、文件名与层级。文件更名、重新导出、调整顺序后请重新生成 JSON。 - 程序支持普通和 Draco 压缩的自包含刚性三角 GLB;每个分件对应整机一个唯一网格节点,可含多种材质。优先按网格节点名匹配,再尝试文件名。核对解码后的三角面,按“整机世界变换 × 分件世界变换的逆”恢复最终位置。缺件、重复、几何变化、无法表示的变换均停止。原文件不被改写。这里不处理不同坐标系下重新烘焙的网格、蒙皮或多零件合成一个节点的整机。 - 先按编号锁定顺序,再相对当前可见阶段的已装件检查进入方向:独立预装仅检查同组,总装检查已合装部件和已安装的总装散件。普通件尝试场景轴及零件局部轴,必要时试较短行程。识别到名称含螺丝、螺钉、screw、bolt 或 Microban 型号 STP39 / BTS2 的零件,会比较局部两端的宽度,仅沿可信的螺丝头侧轴线进入。无圆头特征或轴线未对齐导出局部坐标轴时可能需要人工复核。这里只处理平移,不合成工具或拧转动画。 @@ -39,7 +44,7 @@ npm run assembly:generate -- "/路径/机器人分组" "/路径/新的输出目 npm run assembly:generate -- "/Users/jerry/Downloads/Microban-分散整体glb命名标注安装顺序 2" "/Users/jerry/Downloads/Microban-新的输出目录" --reference "/Users/jerry/Downloads/Microban.glb" --final-group 8 ``` -`--final-group` 指定最后一个目录的编号,不限于 8。前面的每个目录是一个独立预装部件,最后一组是合装后的散件。省略参数则保持旧版累计装配。 +`--final-group` 指定最后一个目录的编号,不限于 8。前面的每个目录是一个独立预装部件,最后一组是合装后的散件。RP1 这类带小组件或 `#` 标记的目录用默认模式,直接按文件和文件夹的标记装配。 - 各目录以及目录内按数字顺序,材料、几何、颜色不改动。 - 从社区打开装配弹窗,加载完成后默认从第一步自动播放;暂停、拖动步骤滑块、查看整体或关闭弹窗会停止连续播放。只有模型没有步骤时默认显示整体。 @@ -71,6 +76,14 @@ npm run assembly:generate -- "/Users/jerry/Downloads/Microban-分散整体glb命 以上只是分组字段示意;完整资源清单、零件变换等仍由生成器写入。普通步骤每个零件只能出现一次;合装步骤必须引用整个已完成部件且每个部件只合装一次。总装散件步骤不带 `groupId`,必须放在全部合装步骤之后。`installOffset` 是装配坐标系中起点相对终点的向量,单位米。 +### `#` 逐组汇合协议 + +按目录标记生成且含 `#` 时,使用 `playback: "scoped-v1"`。所有零件和步骤都有所属大组,所有步骤都有完整的 `visibleParts` 快照。生成器在每段 `#` 开头自动添加 `type: "join"` 步骤,每步引用一个完整的已装好大组件,并提供共同的 `installOffset`。组内零件保持相对位置整体移入,组内的螺丝和工具动作不重播。原编号零件仍只安装一次;同一个完整组件可在不同 `#` 段再次汇合。 + +例如 `#11` 前的十个合装步骤分别显示:第 1 组;第 1、2 组;……;第 1~10 组。之后再安装 `#11-1` 等散件。新增的合装步骤计入播放进度,但不改源文件编号。组内 `#` 则以当前已安装的部分为固定参照,让此前大组按编号进入。`A…!` 的小组件显隐规则、`+ / -` 的局部隔离恢复规则保持不变。前后跳步、拖动进度、重播都按目标快照恢复,不要求从头播放。 + +后台仍只保存原装配 JSON;线上播放器须支持 `scoped-v1`。本地生成器、网页生成工具和社区播放器共用此规则。仅上传新 JSON 不会更新线上前端代码。整组进入的路线仍区分 `checked` 与 `presentation`,后者是展示动画,未证明无碰撞。 + 可选的零件字段 `focusDirection` 为父级装配坐标系中的单位向量,指向已识别的螺丝头外侧,用于特写镜头;它不改变零件姿态或材质。相机取景、平滑过渡和分辨率由前端控制,不需要逐步写相机 JSON。详情与装配继续使用原生像素比和抗锯齿,不自动降低清晰度。 普通播放也会检查当前螺丝头是否朝向镜头,不需要打开“特写”。旧 JSON 没有方向字段时,播放器仅对名称明确的螺丝按几何两端宽度推断头部,结果按文件缓存,不修改文件。形状不明确时保留视角,不猜头尾。正反面的大角度变化先小幅拉远,沿最短水平转角绕到安装侧后推近,模型全程可见;同侧连续步骤沿用原视角。相机采用缓入缓出曲线,停稳后才开始安装,插入期间镜头保持固定。此观察方向与碰撞路径独立,不会修改未确认零件的安装位移。 @@ -84,3 +97,9 @@ npm run assembly:generate -- "/Users/jerry/Downloads/Microban-分散整体glb命 Sesame 的本次文件按以下规则生成:`1-1`、`1-2` 正常安装;`1+3` 只显示第 3 件;`1+4` 显示第 3、4 件;依此累计到 `1+8`,期间第 1、2 件隐藏。`1-9` 不设置显示覆盖,恢复第 1~8 件并播放第 9 件的安装,后续继续累计。文件名中的 `+` 保留原样,下载地址在 OSS 路径中编码为 `%2B`。 例如,第 4 步可写为 `{"id":"step-1-4","parts":["p-1-4"],"visibleParts":["p-1-3","p-1-4"]}`。第 9 步恢复正常写法 `{"id":"step-1-9","parts":["p-1-9"]}`。这是显示范围调整,不会对恢复显示的旧零件重复播放安装动画。新版 JSON 需要同时部署支持 `visibleParts` 的播放器。 + +### 内六角扳手 + +网页选择「内六角扳手 GLB」,或在命令行加 `--hex-key "/路径/内六角扳手.glb"`。工具 GLB 的工作端应朝局部 `-Z`,生成器测量工作端的六角尺寸。对已确认进入方向的内六角螺丝,匹配孔的轮廓和对边尺寸后,写入工具轴、对接点和旋转配置。工具与螺丝旋转的扫掠空间需要另行复核。 + +报告列出匹配数量和跳过原因。JSON 引用了工具时,将原工具 GLB 放在零件上传目录的根层,使用原文件名一起上传。工具不占用装配步号。 diff --git a/js/assembly-camera.js b/js/assembly-camera.js index 7b5e0b2..2344923 100644 --- a/js/assembly-camera.js +++ b/js/assembly-camera.js @@ -121,7 +121,7 @@ export function createAssemblyShot(parts, instances, templates, boundsCache, con // Bound the rotating handle as a cylinder around the socket axis. A // sphere with the full key length wastes most of a portrait viewport. 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 delta = new Vector3(x, y, z).sub(tip).applyQuaternion(rotation), axial = delta.dot(axis); + const delta = new Vector3(x, y, z).sub(tip).multiplyScalar(motion.toolScale ?? 1).applyQuaternion(rotation), axial = delta.dot(axis); axialMin = Math.min(axialMin, axial); axialMax = Math.max(axialMax, axial); radial = Math.max(radial, delta.addScaledVector(axis, -axial).length()); } diff --git a/js/assembly-groups.js b/js/assembly-groups.js index 30f0b32..f81e555 100644 --- a/js/assembly-groups.js +++ b/js/assembly-groups.js @@ -1,8 +1,10 @@ // Optional grouped playback. Legacy manifests remain cumulative. +export const isGroupedAssembly = pkg => ['grouped-v1', 'scoped-v1'].includes(pkg?.playback); + export function validateAssemblyGroups(pkg) { const fail = message => { throw new Error(message); }; - if (pkg.playback !== 'grouped-v1') { - if (pkg.playback !== undefined || pkg.groups !== undefined || pkg.steps.some(s => s.groupId || s.type === 'join')) fail('分组装配需要 playback: grouped-v1'); + if (!isGroupedAssembly(pkg)) { + if (pkg.playback !== undefined || pkg.groups !== undefined || pkg.steps.some(s => s.groupId || s.type === 'join')) fail('分组装配需要受支持的 playback 协议'); return; } if (!Array.isArray(pkg.groups) || !pkg.groups.length || pkg.groups.length > 100) fail('分组装配需要有效的部件清单'); @@ -18,6 +20,21 @@ export function validateAssemblyGroups(pkg) { return { id: g.id, label: String(g.label || g.id).slice(0, 120), parts: [...g.parts] }; }); for (const p of pkg.parts) if (p.parentId && membership.get(p.id) !== membership.get(p.parentId)) fail('父子零件必须属于同一部件'); + if (pkg.playback === 'scoped-v1') { + if (membership.size !== pkg.parts.length) fail('按范围装配必须包含全部零件的分组'); + const built = new Set(); + for (const step of pkg.steps) { + if (!step.visibleParts || !groupIds.has(step.groupId)) fail('按范围装配需要完整显示清单和有效部件编号'); + if (step.parts.some(id => membership.get(id) !== step.groupId)) fail('步骤引用的零件不属于当前部件'); + if (step.type === 'join') { + const members = pkg.groups.find(g => g.id === step.groupId).parts; + if (members.length !== step.parts.length || members.some(id => !built.has(id))) fail('合装步骤必须包含整个已完成部件'); + } else { + for (const id of step.parts) built.add(id); + } + } + return; + } const built = new Set(), joined = new Set(); let groupIndex = 0, joining = false, finishing = false; for (const step of pkg.steps) { @@ -48,7 +65,12 @@ export function validateAssemblyGroups(pkg) { export function assemblyStageKey(pkg, index) { const step = index === null ? null : pkg.steps[index]; - return pkg.playback === 'grouped-v1' && step?.groupId && step.type !== 'join' ? step.groupId : null; + if (!isGroupedAssembly(pkg) || !step?.groupId || step.type === 'join') return null; + if (pkg.playback === 'scoped-v1') { + const members = new Set(pkg.groups.find(g => g.id === step.groupId)?.parts); + if (step.visibleParts.some(id => !members.has(id))) return null; + } + return step.groupId; } export function groupedVisibleParts(pkg, index) { diff --git a/js/assembly-motion.js b/js/assembly-motion.js index 51df679..9effc41 100644 --- a/js/assembly-motion.js +++ b/js/assembly-motion.js @@ -70,7 +70,9 @@ export class ScrewTransition { this.pivotOffset = new Vector3(); this.offset = new Vector3(); tool.quaternion.copy(alignedToolQuaternion(this.motion, toolConfig)); - this.toolDock = this.socket.clone().sub(new Vector3(...toolConfig.tipPosition).applyQuaternion(tool.quaternion)); + const toolScale = this.motion.toolScale ?? 1; + tool.scale.multiplyScalar(toolScale); + this.toolDock = this.socket.clone().sub(new Vector3(...toolConfig.tipPosition).multiplyScalar(toolScale).applyQuaternion(tool.quaternion)); instance.add(tool); this.sample(0); } diff --git a/js/assembly-viewer.js b/js/assembly-viewer.js index 0e46279..4b27911 100644 --- a/js/assembly-viewer.js +++ b/js/assembly-viewer.js @@ -10,7 +10,7 @@ import { ScrewTransition, screwDuration, inferToolTipAxis } from './assembly-mot import { createExplodedLayout } from './assembly-explode.js'; import { createAssemblyShot, assemblyShotFrame, assemblyShotFits, assemblyHeadDirection, headFacingView, createCameraMove, sampleCameraMove, watchAssemblyCameraInput } from './assembly-camera.js'; import { constrainedAssemblyDevice, disposeAssemblyObjects as disposeObject } from './assembly-memory.js'; -import { assemblyStageKey, stepEntryOffset } from './assembly-groups.js'; +import { assemblyStageKey, stepEntryOffset, isGroupedAssembly } from './assembly-groups.js'; import { buildWorkBounds, componentViewDirection, workBoundsFit } from './assembly-framing.js'; import { ASSEMBLY_PACE, assemblyEase, presentationScrewMotion } from './assembly-animation.js'; @@ -313,7 +313,7 @@ export class AssemblyViewer { else if (this.closeupEnabled) { if (stageChanged) this.closeupShot = null; this.refreshCloseup(true, undefined, motion); - } else if (this.config.playback === 'grouped-v1' || this.stepHeadDirection()) this.fitBuildView({ stageChanged, animate: motion }); + } else if (isGroupedAssembly(this.config) || this.stepHeadDirection()) this.fitBuildView({ stageChanged, animate: motion }); this.renderer.shadowMap.needsUpdate = true; this.notifyMotion(); this.loop.invalidate(); @@ -502,7 +502,7 @@ export class AssemblyViewer { if (this.closeupEnabled) this.setCloseup(false, { restore: false }); this.focusedPartId = null; this.cancelCameraTransition(); - if (this.config?.playback === 'grouped-v1' && Number.isInteger(this.stepIndex) && !this.exploded) { + if (isGroupedAssembly(this.config) && Number.isInteger(this.stepIndex) && !this.exploded) { this.fitBuildView({ force:true }); return; } @@ -531,7 +531,7 @@ export class AssemblyViewer { this.camera.updateProjectionMatrix(); if (refit) { if (this.closeupEnabled) this.refreshCloseup(true, this.focusedPartId, false); - else if (this.config?.playback === 'grouped-v1' && Number.isInteger(this.stepIndex)) { + else if (isGroupedAssembly(this.config) && Number.isInteger(this.stepIndex)) { this.cancelCameraTransition(); this.fitBuildView(); } else this.resetView(); diff --git a/js/experience-packages.js b/js/experience-packages.js index 28e50f6..0c61873 100644 --- a/js/experience-packages.js +++ b/js/experience-packages.js @@ -3,7 +3,9 @@ import { validateAssemblyGroups, groupedVisibleParts } from './assembly-groups.j export const PACKAGE_FIELDS = { assembly: 'assemblyManifestUrl', walking: 'walkingManifestUrl' }; export const WALKING_PROFILE = 'microduck-alpha-v1'; -const MAX_JSON_BYTES = 2 * 1024 * 1024; +// Large assemblies include visibility snapshots so seeking never depends on +// previous playback. Keep this shared with the offline generator. +export const MAX_PACKAGE_JSON_BYTES = 16 * 1024 * 1024; const fail = (message) => { throw new Error(message); }; export function packageUrl(project, kind, base = globalThis.location?.href) { @@ -15,21 +17,22 @@ export function packageUrl(project, kind, base = globalThis.location?.href) { } catch { return null; } } -export function assetPath(path) { - if (typeof path !== 'string' || !path || path.length > 512 || /[\\:%?#\x00-\x1f]/.test(path) +export function assetPath(path, { assembly = false } = {}) { + if (typeof path !== 'string' || !path || path.length > 512 || /[\\:%?\x00-\x1f]/.test(path) || (!assembly && path.includes('#')) || path.split('/').some((segment) => !segment || segment === '.' || segment === '..')) fail('资源路径必须是包内相对路径'); return path; } -export function assetUrl(path, manifestUrl) { - return new URL(assetPath(path), new URL('.', manifestUrl)).href; +export function assetUrl(path, manifestUrl, options) { + const segments = assetPath(path, options).split('/'); + return new URL(segments.map(encodeURIComponent).join('/'), new URL('.', manifestUrl)).href; } export async function fetchPackageJson(url, signal) { if (/\.zip(?:[?#]|$)/i.test(url)) fail('请填写压缩包解压后的 manifest.json 地址,不能填写 ZIP 地址'); const response = await fetch(modelAssetUrl(url), { signal, credentials: 'omit' }); if (!response.ok) fail(`资源清单请求失败(HTTP ${response.status})`); - const bytes = await readLimited(response, MAX_JSON_BYTES); + const bytes = await readLimited(response, MAX_PACKAGE_JSON_BYTES); try { return JSON.parse(new TextDecoder().decode(bytes)); } catch { fail('资源清单不是有效 JSON,请确认地址返回的是文件内容'); } } @@ -90,18 +93,20 @@ const identifier = (value) => { export function validatePackage(raw, kind, sourceUrl) { if (!raw || raw.schemaVersion !== 1 || raw.kind !== kind) fail('资源包类型或 schemaVersion 不受支持'); - if (!Array.isArray(raw.files) || !raw.files.length || raw.files.length > 1000) fail('资源文件清单为空或超过 1000 个'); + const options = { assembly: kind === 'assembly' }; + if (!Array.isArray(raw.files) || !raw.files.length) fail('资源文件清单为空'); + if (kind === 'walking' && raw.files.length > 1000) fail('行走资源文件清单超过 1000 个'); const files = new Map(); let total = 0; for (const file of raw.files) { - const path = assetPath(file.path); + const path = assetPath(file.path, options); if (files.has(path) || !Number.isSafeInteger(file.bytes) || file.bytes <= 0 || !/^[a-f0-9]{64}$/.test(file.sha256)) fail(`文件清单无效:${path}`); total += file.bytes; - files.set(path, { ...file, url: assetUrl(path, sourceUrl) }); + files.set(path, { ...file, url: assetUrl(path, sourceUrl, options) }); } const pkg = { ...raw, sourceUrl, files, totalBytes: total }; const requireFile = (path) => { - assetPath(path); + assetPath(path, options); if (!files.has(path)) fail(`清单缺少文件:${path}`); return path; }; @@ -115,7 +120,7 @@ export function validatePackage(raw, kind, sourceUrl) { return pkg; } if (raw.unit !== 'meter') fail('装配包必须使用米作为统一单位'); - if (!Array.isArray(raw.parts) || !raw.parts.length || raw.parts.length > 1000) fail('装配包需要 1–1000 个零件'); + if (!Array.isArray(raw.parts) || !raw.parts.length) fail('装配包需要至少一个零件'); pkg.displayQuaternion = quaternion(raw.displayQuaternion); const glbFile = (path) => { const file = requireFile(path); @@ -150,6 +155,7 @@ export function validatePackage(raw, kind, sourceUrl) { return { type: 'screw', toolId: value.toolId, axis, socketPosition: vector(value.socketPosition, undefined, 3, '螺丝工具对接点'), toolQuaternion: quaternion(value.toolQuaternion), direction: value.direction, + ...(value.toolScale === undefined ? {} : {toolScale:bounded(value.toolScale, 0.1, 10, '工具显示缩放')}), turns: bounded(value.turns, 1, 20, '旋转圈数'), travel: bounded(value.travel, 0.00001, 0.1, '拧入距离(米)'), toolClearance: bounded(value.toolClearance ?? 0.012, 0.001, 0.2, '工具退出距离(米)'), diff --git a/js/project-resources.js b/js/project-resources.js index 3468a1f..90aef5f 100644 --- a/js/project-resources.js +++ b/js/project-resources.js @@ -10,12 +10,24 @@ export function publicResourceUrl(value, base = globalThis.location?.href) { } catch { return null; } } -export function resourceIndex(entries) { - if (!Array.isArray(entries) || !entries.length || entries.length > 1000) throw new Error('资源文件清单为空或超过 1000 个'); +function assemblyFileUrl(value, path) { + if (typeof value !== 'string' || !path.includes('#')) return publicResourceUrl(value); + // Recover literal # only if the resulting pathname matches the uploaded key. + const [base] = value.split('?'); + const repaired = publicResourceUrl(base.replaceAll('#', '%23') + value.slice(base.length)); + try { + if (repaired && decodeURIComponent(new URL(repaired).pathname).endsWith('/' + path)) return repaired; + } catch { /* Leave already-valid API URLs intact. */ } + return publicResourceUrl(value); +} + +export function resourceIndex(entries, { assembly = false } = {}) { + if (!Array.isArray(entries) || !entries.length) throw new Error('资源文件清单为空'); + if (!assembly && entries.length > 1000) throw new Error('行走资源文件清单超过 1000 个'); const files = new Map(); for (const entry of entries) { - const path = assetPath(entry.relativePath); - const url = publicResourceUrl(entry.url); + const path = assetPath(entry.relativePath, { assembly }); + const url = assembly ? assemblyFileUrl(entry.url, path) : publicResourceUrl(entry.url); if (files.has(path) || !url || !Number.isSafeInteger(entry.sizeBytes) || entry.sizeBytes <= 0) throw new Error(`资源清单无效:${path}`); files.set(path, { path, url, bytes: entry.sizeBytes }); } @@ -70,7 +82,7 @@ export async function loadProjectAssembly(project, signal) { if (!url) throw new Error('此项目尚未配置拼装步骤'); const pkg = await loadPackage(url, 'assembly', signal); if (project.assemblyJsonUrl) { - const bound = bindAssemblyFiles(pkg.files, resourceIndex(project.modelPartsFiles)); + const bound = bindAssemblyFiles(pkg.files, resourceIndex(project.modelPartsFiles, { assembly: true })); for (const [path, file] of pkg.files) { const actual = bound.get(path); file.url = actual.url; diff --git a/package.json b/package.json index 58476b3..f1a0f39 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "package:experiences": "node scripts/package-experiences.mjs", "package:assembly-parts": "node scripts/assemble-microban.mjs", "assembly:generate": "node scripts/generate-numbered-assembly.mjs", + "assembly:tool": "node scripts/assembly-tool.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/scripts/assembly-motion.test.mjs b/scripts/assembly-motion.test.mjs index 907eec4..f47e60c 100644 --- a/scripts/assembly-motion.test.mjs +++ b/scripts/assembly-motion.test.mjs @@ -16,8 +16,10 @@ const raw = () => ({ schemaVersion: 1, kind: 'assembly', unit: 'meter', } }], steps: [{ id: 'step', parts: ['screw'] }], }); const validate = p => validatePackage(p, 'assembly', 'https://example.com/manifest.json'); -function fixture(delay = 0) { - const pkg = validate(raw()), part = pkg.parts[0], toolConfig = pkg.tools[0]; +function fixture(delay = 0, toolScale) { + const source = raw(); + if (toolScale !== undefined) source.parts[0].installation.toolScale = toolScale; + const pkg = validate(source), part = pkg.parts[0], toolConfig = pkg.tools[0]; const parent = new Group(), instance = new Group(), tool = new Group(); parent.position.set(-2, 3, -4); parent.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), 1.1); @@ -45,6 +47,7 @@ test('invalid tool references, axes, timing and distorted parent scales fail bef p => p.parts[0].installation.axis = [0, 0, 0], p => p.parts[0].installation.axis = [0, 0, 2], p => p.parts[0].installation.turns = 2.5, p => p.parts[0].installation.turns = 0, p => p.parts[0].installation.direction = 'left', p => p.parts[0].installation.travel = -1, + p => p.parts[0].installation.toolScale = -1, p => p.parts[0].installation.tightenDuration = Infinity, p => p.parts[0].installation.socketPosition = [], p => p.parts[0].scale = [1, 2, 1], p => { p.parts.push({id: 'parent', file: 'part.glb', scale: [1, 2, 1]}); p.parts[0].parentId = 'parent'; }, @@ -92,7 +95,8 @@ 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(); + const { parent, instance, tool, part, toolConfig, transition, m } = fixture(0, 1.65); + assert.equal(tool.scale.x, 1.65); for (let i = 0; i <= 100; i++) { const progress = i / 100, eased = progress ** 3 * (progress * (progress * 6 - 15) + 10); transition.sample(m.approachDuration + m.engageDuration + progress * m.tightenDuration); diff --git a/scripts/assembly-tool.html b/scripts/assembly-tool.html new file mode 100644 index 0000000..25b8294 --- /dev/null +++ b/scripts/assembly-tool.html @@ -0,0 +1,123 @@ + + + + + + 装配 JSON 生成器 + + + +
+

装配 JSON 生成器

+

选择整机和编号零件,在本机计算装配步骤。

+
+ + + + + + +

+
+ +
+ + + diff --git a/scripts/assembly-tool.mjs b/scripts/assembly-tool.mjs new file mode 100644 index 0000000..dc57120 --- /dev/null +++ b/scripts/assembly-tool.mjs @@ -0,0 +1,104 @@ +import { createServer } from 'node:http'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { Readable } from 'node:stream'; +import { assetPath } from '../js/experience-packages.js'; +import { generate } from './generate-numbered-assembly.mjs'; + +const host = '127.0.0.1'; +const port = Number(process.env.ASSEMBLY_TOOL_PORT ?? 8095); +const origin = `http://${host}:${port}`; +const maxBytes = 256 * 1024 * 1024; +const page = await readFile(new URL('./assembly-tool.html', import.meta.url)); +let busy = false; + +function glbPath(value, maxLevels) { + const relativePath = assetPath(value, { assembly: true }); + if (!/\.glb$/i.test(relativePath) || relativePath.split('/').length > maxLevels + || relativePath.split('/').some(segment => segment.startsWith('.'))) { + throw new Error(`不支持的 GLB 路径:${relativePath}`); + } + return relativePath; +} + +async function generateFromUpload(req) { + const form = await new Request(origin, { + method: 'POST', headers: { 'Content-Type': req.headers['content-type'] }, + body: Readable.toWeb(req), duplex: 'half', + }).formData(); + const names = JSON.parse(form.get('paths')); + const files = form.getAll('parts'); + const whole = form.get('whole'); + const wholeName = glbPath(form.get('wholeName'), 1); + if (!(whole instanceof File) || !whole.size || !Array.isArray(names) || files.length !== names.length + || !files.length || files.some(file => !(file instanceof File) || !file.size)) { + throw new Error('请选择整机 GLB 和至少一个非空的分件 GLB。'); + } + const relativePaths = names.map(name => glbPath(name, 3)); + if (new Set(relativePaths).size !== names.length) throw new Error('零件路径重复。'); + if (relativePaths.some(name => name.includes('/')) && relativePaths.some(name => !name.includes('/'))) { + throw new Error('零件请统一平铺或放入编号部位目录。整机 GLB 请通过上方的单独入口选择。'); + } + const extra = form.get('extraBefore'); + const extraBefore = !extra ? undefined : extra === 'end' ? extra : Number(extra); + if (extraBefore !== undefined && extraBefore !== 'end' && (!Number.isSafeInteger(extraBefore) || extraBefore < 1)) { + throw new Error('附加件位置请填写正整数步号或 end。'); + } + const key = form.get('hexKey'); + const keyName = key instanceof File && key.size ? glbPath(form.get('hexKeyName'), 1) : undefined; + + const work = await mkdtemp(path.join(tmpdir(), 'vibemake-assembly-tool-')); + try { + const root = path.join(work, 'parts'); + const output = path.join(work, 'output'); + const reference = path.join(work, wholeName); + await writeFile(reference, new Uint8Array(await whole.arrayBuffer()), { flag: 'wx' }); + let hexKey; + if (keyName) { + const toolDirectory = path.join(work, 'tool'); + await mkdir(toolDirectory); + hexKey = path.join(toolDirectory, keyName); + await writeFile(hexKey, new Uint8Array(await key.arrayBuffer()), { flag: 'wx' }); + } + for (const [index, relativePath] of relativePaths.entries()) { + const target = path.join(root, relativePath); + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, new Uint8Array(await files[index].arrayBuffer()), { flag: 'wx' }); + } + const finalGroup = form.get('mode') === 'grouped' ? 'last' : undefined; + const report = await generate(root, output, () => {}, { reference, finalGroup, extraBefore, hexKey }); + report.whole = wholeName; + const filename = `${path.parse(wholeName).name}-装配步骤.json`; + const manifest = await readFile(path.join(output, filename), 'utf8'); + return { filename, manifest, report }; + } finally { + await rm(work, { recursive: true, force: true }); + } +} + +createServer(async (req, res) => { + const json = (status, data) => { + res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify(data)); + }; + if (req.headers.host !== `${host}:${port}`) return json(403, { error: '请从本机地址打开工具。' }); + if (req.method === 'GET' && req.url === '/') { + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY' }); + return res.end(page); + } + if (req.method !== 'POST' || req.url !== '/generate') return json(404, { error: '页面不存在。' }); + if (req.headers.origin !== origin) return json(403, { error: '请从本机页面提交文件。' }); + if (busy) return json(409, { error: '已有任务在生成,请稍后再试。' }); + if (!Number.isSafeInteger(Number(req.headers['content-length'])) || Number(req.headers['content-length']) > maxBytes) { + return json(413, { error: '模型上传请求总大小须小于 256 MiB。' }); + } + busy = true; + try { + json(200, await generateFromUpload(req)); + } catch (error) { + json(400, { error: error.message }); + } finally { + busy = false; + } +}).listen(port, host, () => console.log(`装配 JSON 工具已启动:${origin}/`)); diff --git a/scripts/experience-packages.test.mjs b/scripts/experience-packages.test.mjs index a3d45b0..f371600 100644 --- a/scripts/experience-packages.test.mjs +++ b/scripts/experience-packages.test.mjs @@ -1,7 +1,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; -import { packageUrl, assetPath, assetUrl, validatePackage, visibleAssemblyParts, validateEmbeddedGlb, readLimited } from '../js/experience-packages.js'; +import { packageUrl, assetPath, assetUrl, validatePackage, visibleAssemblyParts, validateEmbeddedGlb, readLimited, fetchPackageJson, MAX_PACKAGE_JSON_BYTES } from '../js/experience-packages.js'; import { expectedController, validateController } from '../sandbox/src/game/package-config.js'; import { projectExperiences } from '../js/project-experiences.js'; @@ -99,6 +99,16 @@ test('JSON and asset readers reject oversized responses with or without Content- assert.equal(new TextDecoder().decode(await readLimited(new Response('1234'), 4)), '1234'); }); +test('large seekable assembly manifests load within the shared generator limit', async t => { + const body = JSON.stringify({ title: 'RP1', snapshots: 'x'.repeat(3 * 1024 * 1024) }); + t.mock.method(globalThis, 'fetch', async () => new Response(body)); + assert.equal((await fetchPackageJson(url)).title, 'RP1'); + globalThis.fetch.mock.mockImplementation(async () => new Response('{}', { + headers: { 'Content-Length': String(MAX_PACKAGE_JSON_BYTES + 1) }, + })); + await assert.rejects(fetchPackageJson(url), /超过/); +}); + test('shipped source GLB remains a self-contained valid assembly asset', () => { const bytes = readFileSync(new URL('../assets/models/microban-assembly.glb', import.meta.url)); assert.doesNotThrow(() => validateEmbeddedGlb(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length))); diff --git a/scripts/generate-numbered-assembly.mjs b/scripts/generate-numbered-assembly.mjs index ba2692e..93d4e87 100644 --- a/scripts/generate-numbered-assembly.mjs +++ b/scripts/generate-numbered-assembly.mjs @@ -1,6 +1,6 @@ // 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 { copyFileSync, readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { parseArgs } from 'node:util'; @@ -9,11 +9,13 @@ 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 { assetUrl, validateEmbeddedGlb, validatePackage, MAX_PACKAGE_JSON_BYTES } from '../js/experience-packages.js'; import { bindAssemblyFiles, resourceIndex } from '../js/project-resources.js'; import { numberedInput } from './lib/numbered-parts.mjs'; +import { numberedPartId, numberedSchedule } from './lib/numbered-schedule.mjs'; import { collider } from './lib/assembly-axis-planner.mjs'; import { planEntry, planGroupEntry } from './lib/numbered-axis.mjs'; +import { hexInstallation, measureHexKey, measurePhillips, namedToolInstallation } from './lib/numbered-tool.mjs'; const hash = data => createHash('sha256').update(data).digest('hex'); const clean = a => a.map(x=>Math.abs(x)<1e-14?0:x); @@ -69,34 +71,60 @@ export async function generate(root, dest, log=console.log, options={}) { 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 finalGroup=options.finalGroup === 'last' ? groupNumbers.at(-1) : options.finalGroup; + const grouped=finalGroup !== undefined; + if (grouped) assert.ok(groupNumbers.length > 1 && finalGroup===groupNumbers.at(-1), '分组总装至少需要两个编号部位目录,最后一个目录放总装散件'); + if (grouped) assert.ok(ordered.every(item => !item.subgroup && !item.group.revealAll && !item.revealAll), '含小组件或 # 标记的目录请使用按目录和标记装配模式'); + const schedule=!grouped && ordered.some(item=>item.revealAll || item.group.revealAll) ? numberedSchedule(ordered) : null; 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); + const ref=await read(whole), allNodes=rigidMeshes(ref.doc,whole); + const wholeOnly=new Set(options.wholeOnlyNodes ?? []); + const nodes=allNodes.filter(node=>!wholeOnly.has(node.getName())); + assert.equal(allNodes.length-nodes.length,wholeOnly.size,'整机专用网格名称缺失或重复'); 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:[]}; + const tools=new Map(); + for (const [type, filenameOnDisk] of Object.entries(options.namedTools ?? (options.hexKey ? {hex:options.hexKey} : {}))) { + const filename=path.basename(filenameOnDisk); + assert.ok(/\.glb$/i.test(filename) && ordered.every(item => item.path !== filename), '请选择名称与分件不同的工具 GLB'); + const {doc,bytes}=await read(path.resolve(filenameOnDisk)); + const meshes=rigidMeshes(doc,filename).map(node => geometry(node.getMesh()).applyMatrix4(new Matrix4().fromArray(node.getWorldMatrix()))); + const measure=type==='phillips' ? measurePhillips : measureHexKey; + tools.set(type,{ ...measure(meshes,filename), source:filenameOnDisk, file:{path:filename,bytes:bytes.length,sha256:hash(bytes)} }); + } 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:[]})); } + if (schedule) { raw.playback='scoped-v1'; raw.groups=schedule.groups; } const records=[], installed=[], used=new Set(), surfaceCache=new Map(); const groupColliders=new Map(); - let joined=false; + let joined=false, groupStart=0, scopeStart=0, isolatedStart, previousGroup, previousDirectory; for (const item of ordered) { - if (grouped && item.group.number===options.finalGroup && !joined) { + const id=numberedPartId(item), action=schedule?.actions.get(id); + for (const join of action?.joins ?? []) { + const moving=groupColliders.get(join.groupId); + const visible=new Set(join.visibleParts), members=new Set(join.parts); + const obstacles=installed.filter(part=>visible.has(part.id) && !members.has(part.id)); + const result=planGroupEntry(moving,obstacles); + raw.steps.push({...join,installOffset:clean(result.offset),pathStatus:result.presentationOnly?'presentation':'checked'}); + records.push({id:join.id,label:join.label,groupId:join.groupId,...result}); + log(`部件合装 ${join.label}:${result.status}`); + } + if (grouped && item.group.number===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), + const step={id:`join-${group.id}`,type:'join',groupId:group.id,label:`${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}); @@ -114,30 +142,66 @@ export async function generate(root, dest, log=console.log, options={}) { 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 sourceMatrix=new Matrix4().fromArray(n.getWorldMatrix()); + const placement=pose(sourceMatrix,world,item.path); 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); } + if (item.group.number!==previousGroup) groupStart=installed.length; + if (item.directory!==previousDirectory) { + scopeStart=item.subgroup==='finish' ? groupStart : installed.length; + isolatedStart=undefined; + } + isolatedStart=item.isolated ? isolatedStart ?? installed.length : undefined; + const start=isolatedStart ?? (item.revealAll || item.group.revealAll ? 0 : scopeStart); + const visibleSet=action && new Set(action.visibleParts); + const previous=visibleSet ? installed.filter(part=>visibleSet.has(part.id)) : isolatedStart !== undefined || !grouped ? installed.slice(start) + : group ? (groupColliders.get(group.id) ?? []) : installed; + const toolType=options.selectTool ? options.selectTool(item.name) : /内六角|socket[ -]head|hex[ -]socket|allen/i.test(item.name) ? 'hex' : undefined; + const tool=tools.get(toolType); + const result=planEntry(moving,local,world,previous,item.name,tool && options.selectTool ? {fastener:true} : undefined); + const toolMatch=tool && (options.selectTool ? namedToolInstallation : hexInstallation)(local,sourceMatrix,placement,result,tool); + previousGroup=item.group.number; + previousDirectory=item.directory; + const visibleParts=action?.visibleParts ?? ((grouped ? item.isolated : start > 0) ? [...previous.map(part=>part.id), id] : undefined); + if (group) { + const members=groupColliders.get(group.id) ?? []; + members.push(moving); groupColliders.set(group.id,members); + if (!schedule) group.parts.push(id); + } installed.push(moving); - const label=`${item.group.path} · ${item.stepLabel ?? item.number} · ${item.name}`; + const label=[item.directory,item.stepLabel ?? item.number,item.name].filter(Boolean).join(' · '); 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}); + raw.parts.push({id,file:item.path,...placement,installOffset:clean(toolMatch?.offset ?? result.offset),...(result.headDirection?{focusDirection:result.headDirection}:{}), + ...(toolMatch?.installation ? {installation:toolMatch.installation} : {})}); + raw.steps.push({id:`step-${id.slice(2)}`,label,parts:[id],...(group?{groupId:group.id}:{}), + ...(visibleParts ? {visibleParts} : {})}); + records.push({id,label,file:item.path,wholeNode:target.getName(),...result, + ...(toolMatch ? {toolMatch:{type:toolType,matched:!!toolMatch.installation, reason:toolMatch.reason, acrossFlats:toolMatch.acrossFlats, + docking:toolMatch.docking, presentationOffset:toolMatch.offset && !Math.hypot(...result.offset) ? toolMatch.offset : undefined}} : {})}); log(`${installed.length}/${ordered.length} ${label}:${result.status}`); } + const toolCount=raw.parts.filter(part=>part.installation).length; + const usedToolIds=new Set(raw.parts.flatMap(part=>part.installation ? [part.installation.toolId] : [])); + const usedTools=[...tools.values()].filter(tool=>usedToolIds.has(tool.config.id)); + if (toolCount) { + raw.tools=usedTools.map(tool=>tool.config); + raw.files.push(...usedTools.map(tool=>tool.file)); + } 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 assemblyOptions={assembly:true}; + bindAssemblyFiles(pkg.files,resourceIndex(raw.files.map(f=>({relativePath:f.path,sizeBytes:f.bytes,url:assetUrl(f.path,uri,assemblyOptions)})),assemblyOptions)); + let manifest=JSON.stringify(raw,null,2)+'\n'; + if (Buffer.byteLength(manifest)>MAX_PACKAGE_JSON_BYTES) manifest=JSON.stringify(raw)+'\n'; + assert.ok(Buffer.byteLength(manifest)<=MAX_PACKAGE_JSON_BYTES,'步骤超过播放器 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, + ...(tools.size ? {tool:{file:usedTools.map(tool=>tool.file.path).join('、'), matched:toolCount, + skipped:records.filter(record=>record.toolMatch && !record.toolMatch.matched).length, + note:options.selectTool?'按给定命名规则选工具。头部表面对接和补充位移用于演示,工具及螺丝的旋转扫掠空间未核对。':'六角孔与工具尺寸、工作轴已匹配的步骤可播放拧入。工具和螺丝旋转时的扫掠空间未检查。'}} : {}), + ...(wholeOnly.size ? {wholeOnlyNodes:[...wholeOnly]} : {}), 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 检查完整头部通道和半径为螺杆一半的孔芯。这两类仅用于轴向演示。', @@ -146,15 +210,19 @@ export async function generate(root, dest, log=console.log, options={}) { 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')); + if (toolCount) { + mkdirSync(path.join(dest,'工具模型')); + for (const tool of usedTools) copyFileSync(tool.source,path.join(dest,'工具模型',tool.file.path)); + } 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`); + writeFileSync(path.join(dest,'上传说明.txt'),`整机模型单独上传 ${whole}。\n零件模型选择 ${root},保留全部编号部位子目录、文件名。\n拼装步骤只上传 ${title}-装配步骤.json。\n${toolCount?`把工具模型目录里的 ${report.tool.file} 放到零件上传目录根层,与分件一同上传。\n`:''}${schedule?`需要部署支持 scoped-v1 的新版前端。遇到 # 时按编号逐组移入此前完成的大组件,再安装当前散件;连续 # 不重复合装。\n`:''}${grouped?`需要部署支持 grouped-v1 的新版前端。前 ${raw.groups.length} 组分别展示;第 ${finalGroup} 组前先合装这些部件,再安装该文件夹的零件。\n`:''}共 ${ordered.length} 个零件、${raw.steps.length} 个播放步骤,${fits} 步是螺丝沿孔轴展示,${review.length} 步需人工复核。未核验的轴向动画仅用于展示,具体步号请看核对记录。\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'}}}); + const {values,positionals:[root,out]}=parseArgs({allowPositionals:true,options:{reference:{type:'string'},'final-group':{type:'string'},'extra-before':{type:'string'},'hex-key':{type:'string'}}}); assert.ok(root && out,'用法:npm run assembly:generate -- "分组 GLB 目录" "新的输出目录" [--reference "整机.glb"] [--final-group 8]'); - const options={reference:values.reference}; + const options={reference:values.reference,hexKey:values['hex-key']}; 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'); diff --git a/scripts/lib/numbered-axis.mjs b/scripts/lib/numbered-axis.mjs index d7bfc59..c79fcbb 100644 --- a/scripts/lib/numbered-axis.mjs +++ b/scripts/lib/numbered-axis.mjs @@ -5,8 +5,7 @@ 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); +export function planEntry(item, local, world, installed, name, { fastener = isAssemblyFastener(name) } = {}) { const head = fastener ? screwHead(local) : null; const meta = { fastener, headWidthRatio:head?.widthRatio ?? null, ...(head ? {headDirection:head.vector.clone().transformDirection(world).toArray()} : {}) }; diff --git a/scripts/lib/numbered-parts.mjs b/scripts/lib/numbered-parts.mjs index 98ac1fb..935965e 100644 --- a/scripts/lib/numbered-parts.mjs +++ b/scripts/lib/numbered-parts.mjs @@ -27,35 +27,46 @@ 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 directories = entries.filter(e => e.isDirectory()); + const flat = !!reference && directories.length === 0; 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); + const groups = flat ? [{ path: '', number: 1 }] : ordered(directories.map(entry => { + const match = /^([##]?)\s*(\d+)/u.exec(entry.name); + return { path: entry.name, number: Number(match?.[2]), revealAll: !!match?.[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 readSequence = (g, directory, files, subgroup) => { + const relativePath = name => directory ? `${directory}/${name}` : name; + for (const e of files.filter(e => e.isDirectory() || e.isSymbolicLink())) issues.push(`不支持嵌套目录或链接:${relativePath(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 }); + extras.push({ group: g, stem, name: extra[2], path: relativePath(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 }]; + const pair = /^([##!!]?)\s*(\d+)([a-zA-Z]?)(\+|[-_.、 ]+)(\d+)(?:[-_.、 ]+(.+)|([^\d\s._、-].*))?$/u.exec(stem); + const single = pair ? null : /^(\d+)[-_.、 ]+(.+)$/u.exec(stem); + const isolated = pair?.[4] === '+'; + const revealAll = /[##]/u.test(pair?.[1] ?? ''); + const combine = /[!!]/u.test(pair?.[1] ?? ''); + if ((revealAll && isolated) || (combine && (subgroup !== 'finish' || Number(pair[2]) !== g.number))) { + issues.push(`步骤标记与所属目录不一致:${relativePath(e.name)}`); + } + return [{ group: g, number: Number(pair?.[5] ?? single?.[1]), stem, + name: pair ? pair[6] ?? pair[7] ?? stem : single?.[2], path: relativePath(e.name), isolated, revealAll, + stepLabel: pair && (isolated || pair[1]) ? `${pair[1]}${pair[2]}${pair[3]}${pair[4]}${pair[5]}` : undefined }]; }); - if (!items.length) issues.push(`${g.path} 没有 GLB 零件`); - const sequence = ordered(items, g.path, issues); + if (!items.length) issues.push(`${directory || '零件目录'} 没有 GLB 零件`); + const sequence = ordered(items, directory || '零件目录', issues); if (extras.length) { const index = extraBefore === 'end' ? sequence.length : sequence.findIndex(item => item.number === extraBefore); if (index < 0 || extras.length > 1) { @@ -64,7 +75,33 @@ export function numberedInput(root, { extraBefore, reference } = {}) { sequence.splice(index, 0, { ...extras[0], number: 'extra', stepLabel: '附加' }); } } - parts.push(...sequence); + parts.push(...sequence.map(item => ({ ...item, directory, subgroup }))); + }; + for (const group of groups) { + const files = flat ? entries : children(path.join(root, group.path)); + const subdirs = files.filter(entry => entry.isDirectory()); + if (!subdirs.length) { + readSequence(group, group.path, files); + continue; + } + if (files.some(entry => isGlb(entry) || entry.isSymbolicLink())) issues.push(`${group.path} 的分件请统一放入小组件文件夹`); + const subgroups = new Map(); + for (const entry of subdirs) { + const combine = /^[!!]\s*(\d+)(?!\d)/u.exec(entry.name); + const ordinary = /^(\d+)([a-zA-Z])(?:$|[^a-zA-Z])/u.exec(entry.name); + const key = combine ? 'finish' : ordinary?.[2].toUpperCase(); + if (!key || Number((combine ?? ordinary)[1]) !== group.number || subgroups.has(key)) { + issues.push(`小组件目录编号无效或重复:${group.path}/${entry.name}`); + continue; + } + subgroups.set(key, entry.name); + } + const letters = [...subgroups.keys()].filter(key => key !== 'finish').sort(); + if (!letters.length || letters.some((key, index) => key.charCodeAt(0) !== 65 + index)) issues.push(`${group.path} 的小组件须从 A 起连续编号`); + for (const key of [...letters, ...(subgroups.has('finish') ? ['finish'] : [])]) { + const directory = `${group.path}/${subgroups.get(key)}`; + readSequence(group, directory, children(path.join(root, directory)), key); + } } 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/numbered-schedule.mjs b/scripts/lib/numbered-schedule.mjs new file mode 100644 index 0000000..e108ea4 --- /dev/null +++ b/scripts/lib/numbered-schedule.mjs @@ -0,0 +1,43 @@ +// Compile filename rules independently of geometry. Every step is seekable: +// visibility describes the entire scene, not a mutation of the previous frame. +export const numberedPartId = item => `p-${item.group.number}${item.subgroup ? `-${item.subgroup}` : ''}-${item.number}`; + +export function numberedSchedule(ordered) { + const numbers = [...new Set(ordered.map(item => item.group.number))]; + const groups = numbers.map(number => ({ + id: `group-${number}`, label: ordered.find(item => item.group.number === number).group.path, + parts: ordered.filter(item => item.group.number === number).map(numberedPartId), + })); + const actions = new Map(), installed = []; + let groupStart = 0, scopeStart = 0, isolatedStart, previousGroup, previousDirectory; + let revealing = false; + for (const item of ordered) { + const id = numberedPartId(item), groupChanged = previousGroup !== item.group.number; + if (groupChanged) { groupStart = installed.length; revealing = false; } + if (previousDirectory !== item.directory) { + scopeStart = item.subgroup === 'finish' ? groupStart : installed.length; + isolatedStart = undefined; + } + isolatedStart = item.isolated ? isolatedStart ?? installed.length : undefined; + const reveal = !item.isolated && (item.revealAll || item.group.revealAll); + const joins = []; + if (reveal && !revealing) { + // Keep the current partial assembly as an anchor for an internal #. + // At an outer # folder boundary the stage starts empty instead. + const visible = installed.slice(groupStart); + for (const number of numbers.filter(n => n < item.group.number)) { + const group = groups.find(g => g.id === `group-${number}`); + visible.push(...group.parts); + joins.push({ id: `join-before-${id}-${group.id}`, type: 'join', groupId: group.id, + label: `${item.group.path} · 合装 ${group.label}`, parts: [...group.parts], visibleParts: [...visible] }); + } + } + const start = isolatedStart ?? (reveal ? 0 : scopeStart); + actions.set(id, { joins, visibleParts: [...installed.slice(start), id] }); + installed.push(id); + revealing = reveal; + previousGroup = item.group.number; + previousDirectory = item.directory; + } + return { groups, actions }; +} diff --git a/scripts/lib/numbered-tool.mjs b/scripts/lib/numbered-tool.mjs new file mode 100644 index 0000000..8417d9d --- /dev/null +++ b/scripts/lib/numbered-tool.mjs @@ -0,0 +1,145 @@ +import { DoubleSide, Matrix4, Quaternion, Ray, Vector3 } from 'three'; +import { MeshBVH } from 'three-mesh-bvh'; +import { screwHead } from './numbered-axis.mjs'; + +const workAxis = new Vector3(0, 0, -1); +const angles = Array.from({ length: 72 }, (_, index) => index * Math.PI / 36); +const meshPoints = meshes => meshes.flatMap(mesh => { + const vertices = mesh.getAttribute('position'); + return Array.from({ length: vertices.count }, (_, index) => new Vector3().fromBufferAttribute(vertices, index)); +}); + +function capHull(points) { + const sorted = points.sort((a, b) => a.x - b.x || a.y - b.y); + const half = vertices => { + const result = []; + for (const point of vertices) { + while (result.length >= 2) { + const [a, b] = result.slice(-2); + const turn = (b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x); + if (turn > 1e-12) break; + result.pop(); + } + result.push(point); + } + return result.slice(0, -1); + }; + return [...half(sorted), ...half(sorted.reverse())]; +} + +// Supported key exports point the working end down local Z. Verify the six +// vertices at the tip before using its center and measured across-flats size. +export function measureHexKey(meshes, file) { + const points = meshPoints(meshes); + const endZ = points.reduce((min, point) => Math.min(min, point.z), Infinity); + const cap = new Map(points.filter(point => Math.abs(point.z - endZ) < 1e-7) + .map(point => [`${point.x.toFixed(7)},${point.y.toFixed(7)}`, point])); + const corners = capHull([...cap.values()]); + if (corners.length !== 6) throw new Error('扳手 GLB 的工作端须朝局部 -Z,末端须有完整的六角截面'); + const tip = corners.reduce((center, point) => center.add(point), new Vector3()).divideScalar(6); + const flatCenters = corners.map((point, index) => point.clone().add(corners[(index + 1) % 6]).multiplyScalar(.5).sub(tip)); + const radii = flatCenters.map(point => point.length()); + const radius = Math.min(...radii); + if (radius <= 0 || Math.max(...radii) > radius * 1.03 || corners.some(point => + Math.abs(point.distanceTo(tip) / radius - 2 / Math.sqrt(3)) > .04)) { + throw new Error('扳手工作端的六角尺寸无法确认'); + } + return { config: { id: 'hex-key', file, tipPosition: tip.toArray(), tipAxis: workAxis.toArray() }, + flatDirection: flatCenters[0].normalize(), acrossFlats: radius * 2 }; +} + +export function measurePhillips(meshes, file) { + const points = meshPoints(meshes); + const z = points.reduce((min, point) => Math.min(min, point.z), Infinity); + const cap = points.filter(point => point.z - z < 1e-7); + const tip = cap.reduce((center, point) => center.add(point), new Vector3()).divideScalar(cap.length); + tip.z = z; + const end = points.filter(point => point.z - z <= .0026); + const acrossFlats = 2 * end.reduce((max, point) => Math.max(max, Math.hypot(point.x-tip.x,point.y-tip.y)), 0); + if (cap.length < 3 || !(acrossFlats > 0)) throw new Error('十字扳手 GLB 的工作端无法确认'); + return { config: { id: 'phillips', file, tipPosition: tip.toArray(), tipAxis: workAxis.toArray() }, acrossFlats }; +} + +export function hexInstallation(local, sourceMatrix, placement, result, tool, { scaleToSocket = false } = {}) { + if (!['clear-to-seating', 'visual-thread-fit', 'visual-bore-axis'].includes(result.status)) return { reason: '安装方向未确认' }; + const sourceScale = new Vector3().setFromMatrixScale(sourceMatrix).toArray(); + if (sourceMatrix.determinant() <= 0 || [sourceScale, placement.scale].some(scale => Math.max(...scale) - Math.min(...scale) > Math.max(...scale) * 1e-6)) { + return { reason: '零件缩放不适合拧转' }; + } + const head = screwHead(local); + if (!head) return { reason: '螺丝头方向不明确' }; + const outward = head.vector; + const inward = outward.clone().negate(); + const face = local.boundingBox.getCenter(new Vector3()); + const axisIndex = outward.toArray().findIndex(value => value !== 0); + face.setComponent(axisIndex, (outward.getComponent(axisIndex) > 0 ? local.boundingBox.max : local.boundingBox.min).getComponent(axisIndex)); + + local.clearGroups(); + const bvh = new MeshBVH(local); + const margin = .0002 / sourceScale[0]; + const floor = bvh.raycastFirst(new Ray(face.clone().addScaledVector(outward, margin), inward), DoubleSide); + const depth = (floor?.distance ?? 0) - margin; + if (depth < .00025 / sourceScale[0]) return { reason: '未找到螺丝头内的沉孔' }; + const center = face.clone().addScaledVector(inward, Math.min(depth * .5, .001 / sourceScale[0])); + const x = new Vector3().crossVectors(inward, axisIndex === 0 ? new Vector3(0, 1, 0) : new Vector3(1, 0, 0)).normalize(); + const y = new Vector3().crossVectors(inward, x); + const samples = angles.map(angle => { + const ray = x.clone().multiplyScalar(Math.cos(angle)).addScaledVector(y, Math.sin(angle)); + const hit = bvh.raycastFirst(new Ray(center, ray), DoubleSide); + return { ray, hit }; + }); + if (samples.some(sample => !sample.hit?.face)) return { reason: '六角孔壁不完整' }; + const nearest = samples.reduce((a, b) => a.hit.distance < b.hit.distance ? a : b); + const flat = nearest.hit.face.normal.clone().projectOnPlane(inward).normalize(); + if (flat.dot(nearest.ray) < 0) flat.negate(); + const radius = nearest.hit.distance * flat.dot(nearest.ray); + if (!(radius > 0)) return { reason: '六角孔尺寸无法确认' }; + const normals = Array.from({ length: 6 }, (_, index) => flat.clone().applyAxisAngle(inward, index * Math.PI / 3)); + if (samples.some(({ ray, hit }) => Math.abs(hit.distance * Math.max(...normals.map(normal => normal.dot(ray))) / radius - 1) > .06)) { + return { reason: '沉孔轮廓与六角不匹配' }; + } + const acrossFlats = 2 * radius * sourceScale[0]; + if (!scaleToSocket && (tool.acrossFlats > acrossFlats * 1.005 || tool.acrossFlats < acrossFlats * .85)) return { reason: '扳手尺寸与六角孔不匹配', acrossFlats }; + + const axis = inward.transformDirection(sourceMatrix); + const partFlat = flat.transformDirection(sourceMatrix); + const toolBasis = new Matrix4().makeBasis(tool.flatDirection, new Vector3().crossVectors(workAxis, tool.flatDirection), workAxis); + const socketBasis = new Matrix4().makeBasis(partFlat, new Vector3().crossVectors(axis, partFlat), axis); + const toolQuaternion = new Quaternion().setFromRotationMatrix(socketBasis.multiply(toolBasis.invert())).normalize(); + const travel = Math.min(.0012, Math.hypot(...result.offset) / placement.scale[0]); + if (travel < .00001) return { reason: '拧入行程不足' }; + return { acrossFlats, installation: { type: 'screw', toolId: tool.config.id, axis: axis.toArray(), + socketPosition: center.applyMatrix4(sourceMatrix).toArray(), toolQuaternion: toolQuaternion.toArray(), + ...(scaleToSocket ? {toolScale: Math.min(10, Math.max(.1, acrossFlats * .95 / tool.acrossFlats))} : {}), + direction: 'clockwise', turns: 3, travel } }; +} + +// These supplied instructions specify the tool by name. Where the export has +// no usable socket, place the bit at the head face for the display animation. +export function namedToolInstallation(local, sourceMatrix, placement, result, tool) { + const sourceScale = new Vector3().setFromMatrixScale(sourceMatrix).toArray(); + if (sourceMatrix.determinant() <= 0 || [sourceScale, placement.scale].some(scale => + Math.max(...scale) - Math.min(...scale) > Math.max(...scale) * 1e-6)) return { reason: '零件缩放不适合拧转' }; + const head = screwHead(local); + if (!head || !result.headDirection) return { reason: '螺丝头方向不明确' }; + // An unverified full insertion route should not be used for display. Keep + // the screw at the seating point while the selected tool demonstrates a turn. + const offset = Math.hypot(...result.offset) > 0 ? result.offset : result.headDirection.map(v => v * .00015); + const travel = Math.min(.0012, Math.hypot(...offset) / placement.scale[0]); + if (travel < .00001) return { reason: '拧入行程不足' }; + if (tool.config.id === 'hex-key') { + const measured = hexInstallation(local, sourceMatrix, placement, { ...result, status: 'clear-to-seating', offset }, tool, { scaleToSocket: true }); + if (measured.installation) return { ...measured, offset, docking: 'socket' }; + } + const outward = head.vector; + const axisIndex = outward.toArray().findIndex(value => value !== 0); + const bounds = local.boundingBox; + const face = bounds.getCenter(new Vector3()); + face.setComponent(axisIndex, (outward.getComponent(axisIndex) > 0 ? bounds.max : bounds.min).getComponent(axisIndex)); + const size = bounds.getSize(new Vector3()).toArray().filter((_, index) => index !== axisIndex); + const toolScale = Math.min(10, Math.max(.1, Math.min(...size) * sourceScale[0] * .5 / tool.acrossFlats)); + const axis = outward.clone().negate().transformDirection(sourceMatrix); + return { offset, docking: 'head-face', installation: { type:'screw', toolId:tool.config.id, axis:axis.toArray(), + socketPosition:face.applyMatrix4(sourceMatrix).toArray(), toolQuaternion:new Quaternion().setFromUnitVectors(workAxis,axis).toArray(), + toolScale, direction:'clockwise', turns:3, travel } }; +} diff --git a/scripts/project-resources.test.mjs b/scripts/project-resources.test.mjs index 6e960f3..a0f7045 100644 --- a/scripts/project-resources.test.mjs +++ b/scripts/project-resources.test.mjs @@ -78,6 +78,30 @@ test('large uploaded assemblies are not blocked by a total-size cap', () => { sizeBytes: 210 * 1024 * 1024, url: 'https://cdn.example/' + relativePath }))); assert.equal(files.size, 2); }); +test('assembly loads more than 2000 parts and files through the project API binding', async () => { + const count = 2100; + const files = Array.from({ length: count }, (_, index) => ({ + path: `parts/${index}.glb`, bytes: 100, sha256: 'a'.repeat(64), + })); + const parts = files.map((file, index) => ({ id: `part-${index}`, file: file.path })); + const raw = { schemaVersion: 1, kind: 'assembly', unit: 'meter', files, parts, + steps: parts.map(part => ({ id: `install-${part.id}`, parts: [part.id] })) }; + const project = { + assemblyJsonUrl: 'https://cdn.example/steps.json', + modelPartsFiles: files.map(file => ({ relativePath: file.path, sizeBytes: file.bytes, + url: `https://cdn.example/upload/${file.path}` })), + }; + const original = globalThis.fetch; + globalThis.fetch = async () => new Response(JSON.stringify(raw)); + try { + const assembly = await loadProjectAssembly(project); + assert.equal(assembly.steps.length, count); + assert.equal(assembly.files.size, count); + assert.equal(assembly.files.get(files.at(-1).path).url, project.modelPartsFiles.at(-1).url); + await assert.rejects(loadProjectAssembly({ ...project, modelPartsFiles: [] }), /清单为空/); + assert.throws(() => resourceIndex(project.modelPartsFiles), /超过 1000 个/); + } finally { globalThis.fetch = original; } +}); test('assembly resolves exact API URLs across different upload batches and rejects a mismatched part', async () => { const raw = { schemaVersion: 1, kind: 'assembly', unit: 'meter', files: [{ path: 'parts/a.glb', bytes: 100, sha256: 'a'.repeat(64) }], parts: [{ id: 'a', file: 'parts/a.glb' }], steps: [{ id: 'one', parts: ['a'] }] }; const project = { assemblyJsonUrl: 'https://cdn.example/json/batch/steps.json', modelPartsFiles: [{ relativePath: 'parts/a.glb', sizeBytes: 100, url: 'https://cdn.example/parts/other/parts/a.glb' }] }; diff --git a/tests/grouped-assembly.test.js b/tests/grouped-assembly.test.js index b629362..2887d09 100644 --- a/tests/grouped-assembly.test.js +++ b/tests/grouped-assembly.test.js @@ -66,12 +66,19 @@ test('rejects unfinished, repeated, partial and out-of-order components, and cro 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',()=>{ +for (const protocol of ['grouped-v1','scoped-v1']) test(protocol+': 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()); + const raw=fixture(); + if(protocol==='scoped-v1') { + raw.playback=protocol; + raw.groups.push({id:'finish',parts:['nut']});raw.steps[5].groupId='finish'; + const scopes=[['base'],['base','bolt'],['arm'],['base','bolt'],['base','bolt','arm'],['base','bolt','arm','nut']]; + raw.steps.forEach((step,index)=>step.visibleParts=scopes[index]); + } + v.config=validate(raw); 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')); diff --git a/tests/numbered-assembly.test.js b/tests/numbered-assembly.test.js index f580730..caa5fff 100644 --- a/tests/numbered-assembly.test.js +++ b/tests/numbered-assembly.test.js @@ -1,16 +1,19 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs'; +import { copyFileSync, 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 { BufferGeometry, Float32BufferAttribute, BoxGeometry, CylinderGeometry, Matrix4, Quaternion, Vector3 } 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'; +import { hexInstallation, measureHexKey } from '../scripts/lib/numbered-tool.mjs'; +import { validatePackage, visibleAssemblyParts } from '../js/experience-packages.js'; +import { resourceIndex } from '../js/project-resources.js'; 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=>{ @@ -70,12 +73,86 @@ test('Draco parts: restores final pose despite loose transform, binds grouped up 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']); + const flat=path.join(p,'flat'); + mkdirSync(flat); + for (const [source, name] of [ + [path.join(group,'1-1-甲.glb'),'1-1-甲.glb'], + [path.join(group,'1-2-乙.glb'),'1+2-乙.glb'], + [path.join(third,'2-1-丙.glb'),'1+3-丙.glb'], + [path.join(last,'3-1-丁.glb'),'1-4-丁.glb'], + ]) copyFileSync(source,path.join(flat,name)); + const flatOut=path.join(p,'flat-out'); + const isolated=await generate(flat,flatOut,()=>{},{reference:external}); + const flatRaw=JSON.parse(readFileSync(path.join(flatOut,'外部整机-装配步骤.json'))); + assert.deepEqual(flatRaw.files.map(file=>file.path),['1-1-甲.glb','1+2-乙.glb','1+3-丙.glb','1-4-丁.glb']); + assert.deepEqual(flatRaw.steps.map(step=>step.visibleParts),[undefined,['p-1-2'],['p-1-2','p-1-3'],undefined]); + assert.equal(isolated.records[1].status,'foundation','the hidden base does not obstruct the isolated group'); + assert.notEqual(isolated.records[3].status,'foundation','the regular step uses the accumulated assembly'); + const rules=path.join(p,'rules'); + const layout=['1腿/1-1.glb','2髋/2A/2A-1.glb','2髋/2B/2B-1.glb','2髋/!2/!2-1.glb','2髋/!2/!2-2.glb', + '3盖/3-1.glb','3盖/#3-2.glb','3盖/3-3.glb','3盖/#3-4.glb','3盖/3+5.glb','3盖/3+6.glb','3盖/3-7.glb','#4总装/#4-1.glb']; + const references=layout.map((_,i)=>[`part-${i}`,i*.1,.01]); + const ruleReference=path.join(p,'规则整机.glb'); + await writeGlb(ruleReference,references); + for (const [i,file] of [...layout.entries()].reverse()) { + const target=path.join(rules,file); + mkdirSync(path.dirname(target),{recursive:true}); + await writeGlb(target,[[references[i][0],0,.01]]); + } + const ruleOut=path.join(p,'rule-out'); + const ruled=await generate(rules,ruleOut,()=>{},{reference:ruleReference}); + const ruleRaw=JSON.parse(readFileSync(path.join(ruleOut,'规则整机-装配步骤.json'))); + const parsed=validatePackage(ruleRaw,'assembly','https://example.com/rp1/steps.json'); + const ids=ruleRaw.parts.map(part=>part.id); + assert.deepEqual(ruleRaw.files.map(file=>file.path),layout); + assert.deepEqual(parsed.steps.flatMap((step,index)=>step.type==='join'?[]:[[...visibleAssemblyParts(parsed,index)]]), + [[0],[1],[2],[1,2,3],[1,2,3,4],[5],[0,1,2,3,4,5,6],[5,6,7],[0,1,2,3,4,5,6,7,8],[9],[9,10],[5,6,7,8,9,10,11], + layout.map((_,i)=>i)].map(scope=>scope.map(i=>ids[i]))); + assert.equal(ruled.records.find(record=>record.id==='p-3-5').status,'foundation'); + assert.equal(parsed.playback,'scoped-v1'); + assert.equal(parsed.steps.filter(step=>step.type==='join').length,7); + assert.deepEqual(parsed.steps.slice(-4,-1).map(step=>step.groupId),['group-1','group-2','group-3']); + assert.match(parsed.files.get(layout.at(-1)).url,/\/%234.*\/%234-1\.glb$/); + const signed='https://example.com/rp1/'+layout.at(-1)+'?signature=x%2By%23z'; + assert.match(resourceIndex([{relativePath:layout.at(-1),url:signed,sizeBytes:1}],{assembly:true}).get(layout.at(-1)).url, + /\/%234.*\/%234-1\.glb\?signature=x%2By%23z$/); 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('hex tool measures and aligns to a recessed socket and skips blocked or mismatched fasteners',()=>{ + const tipGeometry=new CylinderGeometry(.0017/Math.sqrt(3),.0017/Math.sqrt(3),.02,6).rotateX(Math.PI/2); + const tool=measureHexKey([tipGeometry],'key.glb'); + assert.ok(Math.abs(tool.acrossFlats-.0017)<1e-8); + // Shaft, circular head and hex socket wall, including a floor below its rim. + const rings=[[-.008,.0011],[-.0015,.0011],[-.0015,.0025],[0,.0025],[0,.0009,true],[-.001,.0009,true],[-.001,0]]; + const vertices=[], indices=[]; + const sides=36; + for (const [z,r,hex] of rings) for (let i=0;i{ const dir=workspace(t),g=path.join(dir,'1部');mkdirSync(g); writeFileSync(path.join(dir,'整机.glb'),''); diff --git a/tests/numbered-schedule.test.js b/tests/numbered-schedule.test.js new file mode 100644 index 0000000..e219287 --- /dev/null +++ b/tests/numbered-schedule.test.js @@ -0,0 +1,60 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { numberedSchedule } from '../scripts/lib/numbered-schedule.mjs'; +import { validatePackage, visibleAssemblyParts } from '../js/experience-packages.js'; +import { assemblyStageKey } from '../js/assembly-groups.js'; + +const item=(group,number,flags={})=>({group:{number:group,path:`${group}组件`},directory:`${group}组件`,number,...flags}); +const compile=ordered=>{ + const schedule=numberedSchedule(ordered); + const parts=[...schedule.actions].map(([id])=>({id,file:'part.glb'})); + const steps=[...schedule.actions].flatMap(([id,action])=>[...action.joins.map(join=>({...join,installOffset:[0,.1,0]})), + {id:`step-${id}`,groupId:schedule.groups.find(group=>group.parts.includes(id)).id,parts:[id],visibleParts:action.visibleParts}]); + return validatePackage({schemaVersion:1,kind:'assembly',unit:'meter',playback:'scoped-v1', + files:[{path:'part.glb',bytes:1,sha256:'a'.repeat(64)}],parts,steps,groups:schedule.groups},'assembly','https://example.com/manifest.json'); +}; + +test('outer #11 installs ten completed folders in numeric order then its loose parts, even on arbitrary seeks',()=>{ + const ordered=Array.from({length:10},(_,i)=>item(i+1,1)); + ordered.push(item(11,1,{group:{number:11,path:'#11总装',revealAll:true}}),item(11,2,{group:{number:11,path:'#11总装',revealAll:true}})); + const pkg=compile(ordered); + assert.equal(pkg.steps.length,22); + for(const n of [10,1,7,2,9,3,8,4,6,5]) { + const index=9+n,step=pkg.steps[index]; + assert.equal(step.type,'join');assert.equal(step.groupId,`group-${n}`); + assert.deepEqual([...visibleAssemblyParts(pkg,index)],Array.from({length:n},(_,i)=>`p-${i+1}-1`)); + assert.equal(assemblyStageKey(pkg,index),null); + } + assert.equal(assemblyStageKey(pkg,0),'group-1'); + assert.equal(assemblyStageKey(pkg,20),null); + assert.equal(visibleAssemblyParts(pkg,20).size,11); + assert.equal(visibleAssemblyParts(pkg,21).size,12); +}); + +test('consecutive internal # steps share joins; minus restores local scope and plus starts isolation',()=>{ + const ordered=[item(1,1),item(2,1),item(3,1),item(3,2,{revealAll:true}),item(3,3,{revealAll:true}), + item(3,4),item(3,5,{isolated:true}),item(3,6,{isolated:true}),item(3,7),item(3,8,{revealAll:true})]; + const pkg=compile(ordered),at=id=>pkg.steps.findIndex(step=>step.id===`step-p-3-${id}`); + assert.equal(pkg.steps.filter(step=>step.type==='join').length,4); + assert.equal(visibleAssemblyParts(pkg,at(3)).size,5); + assert.deepEqual([...visibleAssemblyParts(pkg,at(4))],['p-3-1','p-3-2','p-3-3','p-3-4']); + assert.deepEqual([...visibleAssemblyParts(pkg,at(6))],['p-3-5','p-3-6']); + assert.equal(visibleAssemblyParts(pkg,at(7)).size,7); + const firstJoin=pkg.steps[3]; + assert.deepEqual(firstJoin.visibleParts,['p-3-1','p-1-1']); + assert.equal(firstJoin.parts.length,1,'current cover remains still while a prior group moves'); +}); + +test('scoped manifests reject absent scope, partial joins, future groups and wrong group members',()=>{ + const source=()=>compile([item(1,1),item(1,2),item(2,1,{revealAll:true})]); + for(const mutate of [ + pkg=>delete pkg.steps[0].visibleParts, + pkg=>pkg.steps[2].parts.pop(), + pkg=>pkg.steps[2].groupId='group-2', + pkg=>pkg.steps[0].visibleParts.push('p-2-1'), + ]) { + const pkg=source();mutate(pkg); + const raw={...pkg,files:[{path:'part.glb',bytes:1,sha256:'a'.repeat(64)}]}; + assert.throws(()=>validatePackage(raw,'assembly','https://example.com/manifest.json')); + } +}); diff --git a/生成装配步骤.command b/生成装配步骤.command index 8c95127..cf8fb91 100755 --- a/生成装配步骤.command +++ b/生成装配步骤.command @@ -8,14 +8,14 @@ else 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_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 +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")