diff --git a/.gitignore b/.gitignore index e84d74e..c69042b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,11 @@ node_modules/ /dist/ +/dist-dev/ dist.zip +dist-dev.zip vibemake-dist/ .DS_Store +sandbox/node_modules/ +# Generated simulation bundles and local upload/preview exports. +/play/ +/deliverables/ diff --git a/README.md b/README.md index 268530b..fb6433b 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,62 @@ # vibemake 网站(静态版) -纯静态页面,无需构建。three.js、urdf-loader、marked、DOMPurify 和字体都放在 vendor/(`node scripts/vendor.mjs` 下载),不依赖外部 CDN;3D 引擎只在需要的页面按需加载。 +主站使用静态页面,仿真运行器需要先构建。three.js、urdf-loader、marked、DOMPurify 和字体都放在 vendor/(`node scripts/vendor.mjs` 下载),不依赖外部 CDN;3D 引擎只在需要的页面按需加载。 ## 本地运行 +详情页的「行走演示」使用 `sandbox/` 中的运动运行器,首次启动先运行: + +```bash +npm ci +npm --prefix sandbox ci +npm run build:walking +``` + +开发环境部署执行 `npm run build:dev`,生成固定连接 dev 接口的 `dist-dev.zip`;线上部署执行 `npm run build`,生成按访问域名选择接口的 `dist.zip`。把压缩包内容直接解压到静态网站根目录。`dist/`、`dist-dev/`、`play/` 和 `deliverables/` 为本地产物,不提交 Git;生成仿真运行器所需的源码、素材和锁文件保存在 `sandbox/`。 + +生成 `/play/robots/index.html`(Robot Package 通用运行器)和 `/play/microduck/index.html`(旧版 Microduck 包)。两者由本站提供,按详情接口选择;关闭弹窗会释放仿真。修改沙盒后再次执行 `npm run build:walking`;`npm run build` 会自动构建并收录。默认暂停,点击开始后按住键盘 / 触摸方向键运动,松开停止。来源记录见 `sandbox/NOTICE`。 + +### 项目装配与行走资源 + +社区详情读取后端实际上传绑定: + +- `modelGlbUrl`:整机 GLB;保留源文件的材质、颜色与纹理。 +- `assemblyJsonUrl` + `modelPartsFiles`:装配步骤和零件清单,按 `relativePath` 对应文件的 `url`。不同批次上传的资源不共用目录,不能用步骤 JSON 的目录拼接零件地址。 +- `walkingResourcesBaseUrl` + `walkingResourcesFiles`:保持路径的运动文件夹;读取其中唯一的 `robot.json`。必需的是配套 MJCF、引用资源和基础 ONNX 策略,额外动作按配置显示。 +- 字段为空则隐藏对应入口;已删除按 Microban 项目编号注入本地样例的逻辑。 + +当前通用运行器支持 `schema: 1` / `adapter: generic`、单个主 ONNX 控制器及可选 oscillator 关节动作。加载时校验配置、资源路径 / 大小、模型关节和策略输入输出;仅上传任意 ONNX 或任意 ZIP 不代表可运行。未支持的控制器会明确报错,不套用其他机器人的动作。旧 `assemblyManifestUrl` / `walkingManifestUrl` 继续兼容。具体接口和本次验证见 [前台资源接口联调记录](docs/frontend-resource-integration.md)。 + +执行 `npm run package:experiences` 生成两个可上传 ZIP,输出到 `deliverables/experience-packages/`。装配样例属于 Microban,行走样例属于 Microduck。接口、格式与上传流程见 [后端接入说明](docs/experience-packages.txt)。 + +后台与社区下一版行走适配按 [最低必传项 + 可选功能规范](docs/admin-walking-upload-generic-spec.md) 和 [功能目录配置](docs/model-examples/walking-upload-profiles.json) 实施:基础行走只要求配套控制配置、物理模型及引用文件、行走策略;踢球等动作选填,前台按已发布功能展示。新 Robot Package 的基础行走与可选 oscillator 动作已接入;更复杂的技能运行器仍需扩展。旧 Microduck 的全部启动策略要求仅用于旧包兼容。 + +本地联调:`node scripts/experience-fixtures.mjs` 后访问 `/examples/experience-preview.html`,可填写清单地址或检查多零件步骤;此页面不随正式站点发布。协议回归:`npm run test:experiences`。 + +真实分件重组:`npm run package:assembly-parts` 使用用户提供的 `~/Downloads/glb分散零件/` 和 `~/Downloads/机器人.glb`,按参考模型恢复 275 个零件的位置,逐件核对三角面和变换误差,输出 `microban-parts-assembly.zip` 与 `microban-reassembled.glb`。可传入 `--parts` / `--reference` 更换输入路径(算法会严格检查当前导出格式)。预览 `/examples/experience-preview.html?assembly=parts`;支持逐件播放、暂停和进度定位,保留分件自带材质。 + +### 手机与较低配置设备 + +- 共用 `js/render-budget.js`:触屏或已知低核数 / 低内存设备默认 30 FPS,其他设备最多 60 FPS;限制 DPR 与总绘制像素,连续掉帧时逐级降低分辨率、关闭阴影,最低目标 24 FPS。设备信息仅作初始提示,实际帧耗时决定降档,不按 Windows / macOS 区分。 +- 详情静态模型、装配模型按需绘制;打开弹窗暂停底层模型,切到后台停止渲染与行走计算。暂停行走时保留相机操作,关闭弹窗释放 3D 资源 / 卸载仿真 iframe。 +- 旧 Microduck 行走策略使用单个 ONNX Worker;新通用运行器使用单线程 WASM 和串行控制调度,不积压或并行执行推理,物理步长和策略权重不变。平地显示由 131,072 个三角面降为 2 个;完整上游游戏仍保留地形网格。ORT 运行库作为独立同源 JS 输出,避免 Worker 载入含 DOM 操作的页面模块。 +- 手机弹窗使用可视高度和安全区,方向键与操作按钮至少 44 px;窄屏操作区分列,模型根据横竖屏重新构图。 +- 回归:`npm --prefix sandbox test`(含渲染调度、DPR 上限、持续降档和暂停恢复)。浏览器检查 320 / 390 px 竖屏及 844 px 横屏;视口检查不能代替真实 Android、iOS 和 Windows 低配硬件测试,目标帧率不是所有设备上的保证。 + 浏览器不允许 `file://` 读取 URDF,必须起一个本地服务器: ```bash cd ~/vibemake-site node scripts/server.mjs -# http://localhost:8091 后端接口数据(/api 转发到 dev 后端;线上也用这个服务器,按域名自动选 dev / 正式后端) -# http://127.0.0.1:8091 本地演示数据(最早的完整样子,作参考) +# http://localhost:8090 后端接口数据(/api 转发到 dev 后端;线上也用这个服务器,按域名自动选 dev / 正式后端) +# http://127.0.0.1:8090 本地演示数据(最早的完整样子,作参考) ``` +手机与电脑连接同一 Wi-Fi 后,用 `http://<电脑局域网 IP>:8090` 访问。本地 / 局域网下,社区 URDF、网格和贴图统一通过 `/__model_assets/` 同源读取,避免 OSS 仅允许 localhost 跨域时手机加载失败。代理仅允许 linkerbot bucket 的 URDF、experiences 与 project-resources 数据资源目录,保留缓存与流式传输,不修改模型文件;线上域名继续使用原 OSS 地址。回归检查:`node --test scripts/model-assets.test.mjs`。 + 页面路由(不带 .html):`/`、`/explore`、`/studio?robot=`、`/cad`、`/pcb`、`/project/<编号>`、`/workspace`、`/workspace/<编号>`;旧的 `xxx.html` 地址会 301 跳到新地址。`/cad` 和 `/pcb` 分别全屏嵌入 `https://cadworld-studio.robotquan.com/cad` 与 `https://cadworld-studio.robotquan.com/pcb`。 -线上部署用同一个 `server.mjs`(在 dist 里 `npm start`),nginx / 1Panel 只需把整个站点反向代理到它,见 dist/DEPLOY.md。 +CAD / PCB 仅电脑端开放:手机、平板及 820px 以下(含)的窄屏隐藏导航、菜单与页脚入口,直接访问时用 `location.replace('/')` 返回首页;通过检测后才加载编辑器 iframe。手机横屏仍按移动设备处理。 +线上部署使用构建后的静态文件,不需要启动 Node 服务;具体配置见 dist/DEPLOY.md。 ## 目录 @@ -121,7 +163,8 @@ robots/demo-*/ 早期用基础几何体生成的演示 URDF(已不在 ```bash npm install # 第一次打包前装一次(只是打包工具:模型压缩) -node scripts/build.mjs # 生成 dist/ 和 dist.zip;STL 网格会转成 Draco 压缩的 GLB(47 MB → 3 MB) +npm run build # 构建行走演示并生成 dist/ 和 dist.zip;STL 网格会转成 Draco 压缩的 GLB(47 MB → 3 MB) +npm run build:dev # 生成 dist/ 和 dist-dev.zip,固定 dev 接口并禁用本地演示数据模式 SITE_ROOT=dist PORT=8093 node scripts/server.mjs # 本地预览打包结果 ``` @@ -130,7 +173,7 @@ dist 里附带 `nginx.conf.example`(/api 转发、页面路由、缓存、gzip ## 接入后端(Community API) ```bash -node scripts/server.mjs # http://localhost:8091,/api 代理到 https://dev-vibemake-api.robotquan.com +node scripts/server.mjs # http://localhost:8090,/api 代理到 https://dev-vibemake-api.robotquan.com API_TARGET=http://localhost:8993 node scripts/server.mjs # 换成本机后端 ``` diff --git a/apple-touch-icon.png b/apple-touch-icon.png new file mode 100644 index 0000000..5fa6675 Binary files /dev/null and b/apple-touch-icon.png differ diff --git a/assets/brand/README.md b/assets/brand/README.md new file mode 100644 index 0000000..5b774af --- /dev/null +++ b/assets/brand/README.md @@ -0,0 +1,9 @@ +# make 品牌素材 + +来自用户提供的 `make-brand-two-sets`,PNG 按原文件复制,未修改颜色、透明背景或图案。 + +- 导航、页脚、启动页:本目录的完整三维机器人与四色 make Logo。通过 `srcset` 选择 256 / 384 / 512 / 768 像素宽度;导航显示桌面 112×42、窄屏 96×36,页脚 176×66,启动页 240×90。 +- 浏览器标签、收藏夹:网站根目录的 `favicon.svg` 与多尺寸 `favicon.ico`,使用简化机器人头像。 +- 手机桌面:根目录 `apple-touch-icon.png`(180×180),以及 `site.webmanifest` 引用的 192 / 512 像素图标。 + +网页 Logo 为位图,不能当作纯矢量无限放大;当前显示尺寸均低于相应资源分辨率。 diff --git a/assets/brand/make-web-256.png b/assets/brand/make-web-256.png new file mode 100644 index 0000000..0d5e990 Binary files /dev/null and b/assets/brand/make-web-256.png differ diff --git a/assets/brand/make-web-384.png b/assets/brand/make-web-384.png new file mode 100644 index 0000000..525a210 Binary files /dev/null and b/assets/brand/make-web-384.png differ diff --git a/assets/brand/make-web-512.png b/assets/brand/make-web-512.png new file mode 100644 index 0000000..8335640 Binary files /dev/null and b/assets/brand/make-web-512.png differ diff --git a/assets/brand/make-web-768.png b/assets/brand/make-web-768.png new file mode 100644 index 0000000..83c8b3e Binary files /dev/null and b/assets/brand/make-web-768.png differ diff --git a/assets/make-logo.webp b/assets/make-logo.webp new file mode 100644 index 0000000..06dd070 Binary files /dev/null and b/assets/make-logo.webp differ diff --git a/assets/models/microban-assembly.glb b/assets/models/microban-assembly.glb new file mode 100644 index 0000000..e6ef4c3 Binary files /dev/null and b/assets/models/microban-assembly.glb differ diff --git a/cad.html b/cad.html index e839817..dad28fc 100644 --- a/cad.html +++ b/cad.html @@ -4,7 +4,12 @@ - VibeMake CAD + + make CAD + + + +

三个机器人 · 新版上传预览

读取本次整理的上传文件,使用社区同一套模型、装配与运动播放器。

diff --git a/examples/duck-current-assembly.html b/examples/duck-current-assembly.html new file mode 100644 index 0000000..12654d3 --- /dev/null +++ b/examples/duck-current-assembly.html @@ -0,0 +1,101 @@ + + + + + 小鸭子 · 最新完整装配预览 + + + + +
+ ← 小鸭子项目 +

左腿 → 右腿 → 躯干 → 颈部 → 头部 · 239 步装配

+

使用本次压缩版整机及编号顺序,保留原材质与安装位置。选择步骤并拖动进度检查装入方向。

+ 正在加载模型… +
+
+ + + + + + + + +
+
+

+
+ + diff --git a/examples/duck-left-assembly.html b/examples/duck-left-assembly.html new file mode 100644 index 0000000..bea1821 --- /dev/null +++ b/examples/duck-left-assembly.html @@ -0,0 +1,88 @@ + + + + + 小鸭子 · 52 步装配预览 + + + + +
+ ← 小鸭子项目 +

左腿 · 52 步装配

+

当前上传文件的本地预览。选择任意步骤,拖动进度查看装入方向;后台需要上传新的步骤 JSON 后才会更新。

+ 正在加载模型… +
+
+ + + + + + +
+
+

+
+ + diff --git a/examples/duck-numbered-assembly.html b/examples/duck-numbered-assembly.html new file mode 100644 index 0000000..ca8072a --- /dev/null +++ b/examples/duck-numbered-assembly.html @@ -0,0 +1,88 @@ + + + + + 小鸭子 · 双腿和躯干装配预览 + + + + +
+ ← 小鸭子项目 +

左腿 → 右腿 → 躯干 · 149 步装配

+

合并 JSON 的本地预览,保留编号顺序;3-36、3-37 暂跳过。选择任意步骤,拖动进度查看装入方向;后台需要上传新的步骤 JSON 后才会更新。

+ 正在加载模型… +
+
+ + + + + + +
+
+

+
+ + diff --git a/examples/experience-preview.html b/examples/experience-preview.html new file mode 100644 index 0000000..ade06c5 --- /dev/null +++ b/examples/experience-preview.html @@ -0,0 +1,62 @@ + + + + + 资源包联调 · make + + + + +
+ ← 返回项目详情 +

资源包联调

+

使用与详情页相同的加载组件。后端返回两个清单地址即可显示入口;字段留空则隐藏。这里的行走资源是 Microduck,装配资源是 Microban,分别用于接口验证。

+
+ + +
+
+ +
+

多零件示例是测试积木,用于验证独立 GLB、重复实例、父子坐标与装配步骤,不代表机器人的真实安装工序。

+
+ diff --git a/examples/screw-assembly.html b/examples/screw-assembly.html new file mode 100644 index 0000000..ed0bc43 --- /dev/null +++ b/examples/screw-assembly.html @@ -0,0 +1,32 @@ + + + + + 小鸭子 · 扳手装配预览 + + + + +
+ ← 小鸭子项目 +

装配效果预览

+

一颗一颗,拧紧到位。

+

内六角扳手插入螺丝孔,沿安装轴顺时针旋转,拧紧后退出。使用你提供的模型与原始材质。

+
+ + +
+

点击「重播本步」可再次查看。拖拽调整视角,滚轮或双指缩放。

+

这里预览新的本地 JSON;后台已上传的旧步骤不会被替换。完整上传文件已整理到下载目录「小鸭子-扳手装配」。

+
+ + diff --git a/examples/upload-retest.html b/examples/upload-retest.html new file mode 100644 index 0000000..733096c --- /dev/null +++ b/examples/upload-retest.html @@ -0,0 +1,28 @@ + + +小鸭子上传前核验 · make + + + +
+

Microduck · 上传前本地核验

+

这是本次上传文件的本地预览,使用与社区详情相同的资源字段和播放器。文件尚未重新上传后台。整机按原运动学和原配色导出;运动资源保持原样。

+
查看后端 Microban 项目
+正在读取上传资料…
+
diff --git a/explore.html b/explore.html index 26c0b3e..f889666 100644 --- a/explore.html +++ b/explore.html @@ -4,9 +4,13 @@ + - 社区 · vibemake - + 社区 · make + + + + @@ -38,8 +42,10 @@ diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..89ef99e Binary files /dev/null and b/favicon.ico differ diff --git a/favicon.svg b/favicon.svg new file mode 100644 index 0000000..e204a46 --- /dev/null +++ b/favicon.svg @@ -0,0 +1 @@ +make robot diff --git a/icon-16.png b/icon-16.png new file mode 100644 index 0000000..e9933b8 Binary files /dev/null and b/icon-16.png differ diff --git a/icon-192.png b/icon-192.png new file mode 100644 index 0000000..95f0834 Binary files /dev/null and b/icon-192.png differ diff --git a/icon-32.png b/icon-32.png new file mode 100644 index 0000000..c651a05 Binary files /dev/null and b/icon-32.png differ diff --git a/icon-48.png b/icon-48.png new file mode 100644 index 0000000..5e29eaf Binary files /dev/null and b/icon-48.png differ diff --git a/icon-512.png b/icon-512.png new file mode 100644 index 0000000..1384c23 Binary files /dev/null and b/icon-512.png differ diff --git a/icon-64.png b/icon-64.png new file mode 100644 index 0000000..6725ddf Binary files /dev/null and b/icon-64.png differ diff --git a/index.html b/index.html index c2f7617..5390a74 100644 --- a/index.html +++ b/index.html @@ -4,10 +4,14 @@ + - vibemake — 开源机器人社区 + make — 开源机器人社区 - + + + + @@ -50,8 +54,10 @@ diff --git a/js/api.js b/js/api.js index 3b9fcb1..4c3b8fa 100644 --- a/js/api.js +++ b/js/api.js @@ -12,7 +12,10 @@ export const API_HOSTS = { 'dev-vibemake.robotquan.com': 'https://dev-vibemake-api.robotquan.com/api', 'vibemake.robotquan.com': 'https://vibemake-api.robotquan.com/api', }; +// 打包脚本只替换部署产物中的值;本地源码继续按域名选择环境。 +export const BUILD_ENV = 'auto'; function apiBase() { + if (BUILD_ENV === 'dev') return API_HOSTS['dev-vibemake.robotquan.com']; const host = location.hostname; if (API_HOSTS[host]) return API_HOSTS[host]; if (/^dev-/.test(host)) return 'https://dev-vibemake-api.robotquan.com/api'; diff --git a/js/assembly-explode.js b/js/assembly-explode.js new file mode 100644 index 0000000..440b938 --- /dev/null +++ b/js/assembly-explode.js @@ -0,0 +1,65 @@ +import { Box3, Matrix3, Matrix4, Vector3 } from '../vendor/three/build/three.module.min.js'; + +// Build once from assembled geometry. Only instance translations change during +// interaction; geometry, materials, rotations and the source JSON stay intact. +export function createExplodedLayout(config, instances) { + const records = config.parts.map((part) => { + const instance = instances.get(part.id); + instance.updateWorldMatrix(true, true); + // The first child is this part's GLB, excluding nested assembly parts/tools. + const bounds = new Box3().setFromObject(instance.children[0]); + if (bounds.isEmpty()) bounds.setFromCenterAndSize(instance.getWorldPosition(new Vector3()), new Vector3()); + return { part, instance, bounds, center: bounds.getCenter(new Vector3()), worldOffset: new Vector3() }; + }); + const originalBounds = new Box3(); + records.forEach(({ bounds }) => originalBounds.union(bounds)); + const center = originalBounds.getCenter(new Vector3()); + const size = originalBounds.getSize(new Vector3()); + const span = Math.max(size.x, size.y, size.z, 0.001); + const coincident = new Map(); + for (const record of records) { + const key = record.center.toArray().map((n) => Math.round(n / span * 1e6)).join(','); + if (!coincident.has(key)) coincident.set(key, []); + coincident.get(key).push(record); + record.worldOffset.copy(record.center).sub(center).multiplyScalar(0.85); + const insertion = new Vector3(...record.part.installOffset) + .applyMatrix3(new Matrix3().setFromMatrix4(record.instance.parent.matrixWorld)); + if (insertion.lengthSq() > 1e-14) { + const clearance = Math.min(span * 0.25, Math.max(span * 0.07, record.bounds.getSize(new Vector3()).length() * 0.35)); + record.worldOffset.addScaledVector(insertion.normalize(), clearance); + } + } + // Coincident pivots/centers must not remain stacked in the exploded view. + for (const group of coincident.values()) if (group.length > 1) { + group.sort((a, b) => a.part.id.localeCompare(b.part.id)); + group.forEach((record, i) => { + const angle = i * Math.PI * (3 - Math.sqrt(5)); + record.worldOffset.add(new Vector3(Math.cos(angle), (i / (group.length - 1) - 0.5) * 0.5, Math.sin(angle)).multiplyScalar(span * 0.09)); + }); + } + // Keep the lowest part on/above the original floor throughout the transition. + const lowest = Math.min(...records.map(({ bounds, worldOffset }) => bounds.min.y + worldOffset.y)); + const lift = Math.max(0, originalBounds.min.y - lowest); + records.forEach(({ worldOffset }) => { worldOffset.y += lift; }); + const byId = new Map(records.map((record) => [record.part.id, record])); + for (const record of records) { + const parentOffset = byId.get(record.part.parentId)?.worldOffset || new Vector3(); + const inverseParent = new Matrix3().setFromMatrix4(new Matrix4().copy(record.instance.parent.matrixWorld).invert()); + // Compensate the parent's displacement so nested parts don't move twice. + record.offset = record.worldOffset.clone().sub(parentOffset).applyMatrix3(inverseParent); + } + const clamp = (value) => Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0; + return { + records, + originalBounds, + apply(value) { + const amount = clamp(value); + for (const { part, instance, offset } of records) instance.position.fromArray(part.position).addScaledVector(offset, amount); + }, + boundsAt(value) { + const amount = clamp(value), bounds = new Box3(); + for (const record of records) bounds.union(record.bounds.clone().translate(record.worldOffset.clone().multiplyScalar(amount))); + return bounds; + }, + }; +} diff --git a/js/assembly-motion.js b/js/assembly-motion.js new file mode 100644 index 0000000..430d0a3 --- /dev/null +++ b/js/assembly-motion.js @@ -0,0 +1,116 @@ +// Same Three module as the import map; this math also runs in Node regression tests. +import { Vector3, Quaternion, Triangle, Box3 } from '../vendor/three/build/three.module.min.js'; + +const ease = (t) => t * t * (3 - 2 * t); +const clamp = (t) => Math.max(0, Math.min(1, t)); + +export function screwDuration(motion) { + return motion.approachDuration + motion.engageDuration + motion.tightenDuration + motion.retractDuration; +} + +// Legacy manifests did not declare the tool's working direction. Measure the +// outward normal at its declared tip once at load time, including GLB node +// transforms. This is the end-cap direction, not the long axis of an L-key. +export function inferToolTipAxis(template, tipPosition) { + template.updateMatrixWorld(true); + const tip = new Vector3(...tipPosition); + const outward = tip.clone().sub(new Box3().setFromObject(template).getCenter(new Vector3())); + const triangle = new Triangle(), nearest = new Vector3(), normal = new Vector3(); + let best = Infinity, axis; + template.traverse((mesh) => { + if (!mesh.isMesh) return; + const positions = mesh.geometry.getAttribute('position'), indices = mesh.geometry.index; + if (!positions) return; + const count = indices?.count ?? positions.count; + for (let i = 0; i + 2 < count; i += 3) { + [triangle.a, triangle.b, triangle.c].forEach((v, j) => v.fromBufferAttribute(positions, indices ? indices.getX(i + j) : i + j).applyMatrix4(mesh.matrixWorld)); + triangle.getNormal(normal); + if (normal.lengthSq() < 0.5) continue; + triangle.closestPointToPoint(tip, nearest); + const distance = nearest.distanceToSquared(tip); + if (distance >= best) continue; + best = distance; + axis = normal.clone(); + if (axis.dot(outward) < 0) axis.negate(); + } + }); + return axis?.toArray(); +} + +export function alignedToolQuaternion(motion, toolConfig) { + const rotation = new Quaternion(...motion.toolQuaternion); + if (toolConfig.tipAxis) { + const current = new Vector3(...toolConfig.tipAxis).applyQuaternion(rotation).normalize(); + const inward = new Vector3(...motion.axis).normalize(); + rotation.premultiply(new Quaternion().setFromUnitVectors(current, inward)).normalize(); + } + return rotation; +} + +// Coordinates: axis/socket are in the GLB part's local frame, installOffset is +// in its parent's frame. Clockwise is viewed from the tool looking into the hole. +// No geometry or material is modified. A child tool follows the screw rigidly. +export class ScrewTransition { + constructor(instance, part, tool, toolConfig, delay = 0) { + this.instance = instance; + this.part = part; + this.motion = part.installation; + this.tool = tool; + this.delay = delay; + this.elapsed = 0; + this.duration = delay + screwDuration(this.motion); + this.target = new Vector3(...part.position); + this.rotation = new Quaternion(...part.quaternion); + this.axis = new Vector3(...this.motion.axis).normalize(); + this.socket = new Vector3(...this.motion.socketPosition); + this.startOffset = new Vector3(...part.installOffset); + this.seatOffset = this.axis.clone().multiplyScalar(-this.motion.travel) + .multiply(new Vector3(...part.scale)).applyQuaternion(this.rotation); + this.spin = new Quaternion(); + 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)); + instance.add(tool); + this.sample(0); + } + + sample(elapsed) { + const { instance, motion: m, tool } = this; + const t = elapsed - this.delay; + this.phase = t < 0 ? 'waiting' : 'done'; + instance.visible = t >= 0; + tool.visible = false; + instance.position.copy(this.target); + instance.quaternion.copy(this.rotation); + if (t < 0) return; + if (elapsed >= this.duration) return; // exact final pose, no residual rotation + const engageStart = m.approachDuration; + const tightenStart = engageStart + m.engageDuration; + const retractStart = tightenStart + m.tightenDuration; + if (t < engageStart) { + this.phase = 'approach'; + this.offset.lerpVectors(this.startOffset, this.seatOffset, ease(clamp(t / engageStart))); + } else { + this.phase = t < tightenStart ? 'engage' : t < retractStart ? 'tighten' : 'retract'; + const progress = ease(clamp((t - tightenStart) / m.tightenDuration)); + this.offset.copy(this.seatOffset).multiplyScalar(1 - progress); + const angle = (m.direction === 'clockwise' ? 1 : -1) * Math.PI * 2 * m.turns * progress; + this.spin.setFromAxisAngle(this.axis, angle); + if (progress < 1) instance.quaternion.copy(this.rotation).multiply(this.spin); + // Rotate around the socket axis even when the GLB origin is not on it. + this.pivotOffset.copy(this.socket).applyQuaternion(this.spin).negate().add(this.socket) + .multiply(instance.scale).applyQuaternion(this.rotation); + if (progress < 1) this.offset.add(this.pivotOffset); + tool.visible = true; + let clearance = 0; + if (t < tightenStart) clearance = m.toolClearance * (1 - ease(clamp((t - engageStart) / m.engageDuration))); + if (t >= retractStart) clearance = m.toolClearance * ease(clamp((t - retractStart) / m.retractDuration)); + tool.position.copy(this.toolDock).addScaledVector(this.axis, -clearance); + } + instance.position.add(this.offset); + } + + update(dt) { this.elapsed += dt; this.sample(this.elapsed); } + dispose() { this.tool.removeFromParent(); } +} diff --git a/js/assembly-viewer.js b/js/assembly-viewer.js new file mode 100644 index 0000000..03f820a --- /dev/null +++ b/js/assembly-viewer.js @@ -0,0 +1,449 @@ +import * as THREE from 'three'; +import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; +import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js'; +import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; +import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js'; +import { RenderBudget, RenderLoop } from './render-budget.js'; +import { readLimited, validateEmbeddedGlb, visibleAssemblyParts } from './experience-packages.js'; +import { modelAssetUrl } from './model-assets.js'; +import { ScrewTransition, screwDuration, inferToolTipAxis } from './assembly-motion.js'; +import { createExplodedLayout } from './assembly-explode.js'; + +function disposeObject(root) { + const resources = new Set(); + for (const item of [root].flat()) item.traverse((object) => { + if (object.geometry) resources.add(object.geometry); + 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); + } + }); + resources.forEach((resource) => resource.dispose()); +} + +export class AssemblyViewer { + constructor(container) { + this.container = container; + this.disposed = false; + this.budget = new RenderBudget(); + this.renderer = new THREE.WebGLRenderer({ antialias: this.budget.antialias, alpha: true, powerPreference: 'low-power' }); + const renderer = this.renderer; + renderer.outputColorSpace = THREE.SRGBColorSpace; + renderer.toneMapping = THREE.AgXToneMapping; + renderer.toneMappingExposure = 1.05; + renderer.shadowMap.enabled = this.budget.shadows; + renderer.shadowMap.type = THREE.PCFSoftShadowMap; + // The model and lights are static: orbiting does not change its shadow. + renderer.shadowMap.autoUpdate = false; + renderer.domElement.setAttribute('aria-label', '装配模型,可拖拽旋转和缩放'); + renderer.domElement.style.visibility = 'hidden'; + container.prepend(renderer.domElement); + + this.scene = new THREE.Scene(); + this.camera = new THREE.PerspectiveCamera(32, 1, 0.01, 50); + this.createEnvironment(); + + this.scene.add(new THREE.HemisphereLight(0xffffff, 0x343840, 0.45)); + const key = new THREE.DirectionalLight(0xffecd9, 2.5); + key.position.set(3, 4, -2); + key.castShadow = true; + key.shadow.mapSize.set(1024, 1024); + Object.assign(key.shadow.camera, { left: -1.5, right: 1.5, top: 1.5, bottom: -1.5, near: 0.1, far: 10 }); + key.shadow.normalBias = 0.008; + key.shadow.bias = -0.0002; + this.scene.add(key); + const fill = new THREE.DirectionalLight(0xdce7ff, 0.7); + fill.position.set(-2, 2, 3); + this.scene.add(fill); + + const ground = new THREE.Mesh(new THREE.PlaneGeometry(200, 200), new THREE.ShadowMaterial({ opacity: 0.25 })); + ground.rotation.x = -Math.PI / 2; + ground.position.y = -0.002; + ground.receiveShadow = true; + this.scene.add(ground); + const grid = new THREE.GridHelper(6, 60, 0x626a75, 0x626a75); + grid.material.transparent = true; + grid.material.opacity = 0.1; + grid.material.depthWrite = false; + grid.position.y = -0.004; + this.scene.add(grid); + + this.controls = new OrbitControls(this.camera, renderer.domElement); + Object.assign(this.controls, { + enableDamping: true, dampingFactor: 0.075, minDistance: 0.65, maxDistance: 7, + maxPolarAngle: Math.PI * 0.49, autoRotateSpeed: 0.8, + }); + this.loop = new RenderLoop({ + budget: this.budget, + render: (dt) => this.render(dt), + onQuality: () => this.resize(false), + }); + this.controls.addEventListener('change', () => this.loop.invalidate()); + this.controls.addEventListener('start', () => { if (this.explosionTransition) this.explosionTransition.moveCamera = false; }); + this.resizeObserver = new ResizeObserver(() => this.resize()); + this.resizeObserver.observe(container); + this.resize(); + this.onVisibility = () => this.loop.setActive(!document.hidden && !this.contextLost && !this.paused && this.inView !== false); + this.intersectionObserver = new IntersectionObserver(([entry]) => { this.inView = entry.isIntersecting; this.onVisibility(); }); + this.intersectionObserver.observe(container); + document.addEventListener('visibilitychange', this.onVisibility); + renderer.domElement.addEventListener('webglcontextlost', (event) => { + event.preventDefault(); + this.contextLost = true; + this.onVisibility(); + }); + renderer.domElement.addEventListener('webglcontextrestored', () => { + if (this.disposed) return; + this.contextLost = false; + this.createEnvironment(); + renderer.shadowMap.needsUpdate = true; + this.onVisibility(); + }); + this.onVisibility(); + } + + createEnvironment() { + this.environment?.dispose(); + const room = new RoomEnvironment(this.renderer); + const pmrem = new THREE.PMREMGenerator(this.renderer); + this.environment = pmrem.fromScene(room, 0.04); + this.scene.environment = this.environment.texture; + room.dispose(); + pmrem.dispose(); + } + + async loadGlb(url, signal, displayQuaternion = [0, 0, 0, 1]) { + const response = await fetch(modelAssetUrl(url), { signal, credentials: 'omit' }); + if (!response.ok) throw new Error(`整机模型请求失败(HTTP ${response.status})`); + const data = await readLimited(response); + await this.load({ + files: new Map([['whole.glb', { url, bytes: data.length, data }]]), displayQuaternion, + parts: [{ id: 'whole', file: 'whole.glb', parentId: null, position: [0, 0, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [0, 0, 0] }], steps: [], + }, signal); + } + + setPaused(paused) { this.paused = paused; this.onVisibility(); } + + async load(config, signal, onProgress) { + this.config = config; + this.templates = new Map(); + this.parts = new Map(); + const queue = [...new Set([...config.parts, ...(config.tools || [])].map((part) => part.file))]; + const count = queue.length; + let completed = 0; + // Compressed uploads use the same local decoder as the main model viewer. + // One decoder worker keeps assembly loading within mobile memory budgets. + const draco = new DRACOLoader().setDecoderPath('/vendor/three/examples/jsm/libs/draco/gltf/').setWorkerLimit(1); + const loader = new GLTFLoader().setDRACOLoader(draco); + // 同一个 GLB 可用于多个螺丝 / 零件实例,只下载和解析一次;限制并行解析数量。 + const worker = async () => { + for (let path = queue.shift(); path; path = queue.shift()) { + signal.throwIfAborted(); + if (this.disposed) throw new DOMException('预览已关闭', 'AbortError'); + const file = config.files.get(path); + let bytes = file.data; + if (!bytes) { + const response = await fetch(modelAssetUrl(file.url), { signal, credentials: 'omit' }); + if (!response.ok) throw new Error(`零件请求失败(HTTP ${response.status}):${path}`); + bytes = await readLimited(response, file.bytes); + } + if (bytes.length !== file.bytes) throw new Error(`零件大小与清单不一致:${path}`); + if (file.sha256 && globalThis.crypto?.subtle) { + const digest = await crypto.subtle.digest('SHA-256', bytes); + const hash = [...new Uint8Array(digest)].map((x) => x.toString(16).padStart(2, '0')).join(''); + if (hash !== file.sha256) throw new Error(`零件内容与步骤版本不一致:${path}`); + } + validateEmbeddedGlb(bytes.buffer); + signal.throwIfAborted(); + const gltf = await loader.parseAsync(bytes.buffer, new URL('.', file.url).href); + if (this.disposed || signal.aborted) { + disposeObject(gltf.scene); + throw new DOMException('预览已关闭', 'AbortError'); + } + file.data = undefined; + this.templates.set(path, gltf.scene); + onProgress?.(Math.round(++completed / count * 100)); + } + }; + // Let in-flight parses settle before terminating the shared decoder worker. + try { + const results = await Promise.allSettled(Array.from({ length: Math.min(2, count) }, worker)); + const failed = results.find(result => result.status === 'rejected'); + if (failed) throw failed.reason; + } finally { draco.dispose(); } + signal.throwIfAborted(); + this.toolConfigs = new Map((config.tools || []).map((tool) => [tool.id, { + ...tool, tipAxis: tool.tipAxis || inferToolTipAxis(this.templates.get(tool.file), tool.tipPosition), + }])); + const display = new THREE.Group(); + display.quaternion.fromArray(config.displayQuaternion); + for (const part of config.parts) { + const instance = new THREE.Group(); + instance.name = part.id; + instance.add(this.templates.get(part.file).clone(true)); + instance.position.fromArray(part.position); + instance.quaternion.fromArray(part.quaternion); + instance.scale.fromArray(part.scale); + this.parts.set(part.id, instance); + } + for (const part of config.parts) (part.parentId ? this.parts.get(part.parentId) : display).add(this.parts.get(part.id)); + const model = new THREE.Group(); + model.add(display); + model.updateMatrixWorld(true); + const bounds = new THREE.Box3().setFromObject(model); + const size = bounds.getSize(new THREE.Vector3()); + const center = bounds.getCenter(new THREE.Vector3()); + const dimension = Math.max(size.x, size.y, size.z); + if (!Number.isFinite(dimension) || dimension <= 0) throw new Error('装配包没有可显示的几何体'); + const scale = 1 / dimension; + model.scale.setScalar(scale); + model.position.set(-center.x * scale, -bounds.min.y * scale, -center.z * scale); + this.scene.add(model); + this.model = model; + this.modelSize = size.multiplyScalar(scale); + model.updateMatrixWorld(true); + this.assembledBounds = new THREE.Box3().setFromObject(model); + this.exploded = false; + this.explosionAmount = 0; + this.explosionTarget = 0; + this.explodedLayout = null; + this.explosionTransition = null; + + model.traverse((object) => { + if (!object.isMesh) return; + object.castShadow = true; + object.receiveShadow = true; + // 直接使用 GLTFLoader 读取的原始材质,不覆盖任何材质参数。 + }); + this.resetView(); + this.renderer.shadowMap.needsUpdate = true; + this.loop.invalidate(); + this.renderer.domElement.style.visibility = 'visible'; + this.stepIndex = null; + this.installed = visibleAssemblyParts(config, null); + this.transitions = []; + } + + setStep(index, animate = true) { + if (!this.config || this.disposed) return; + const installed = visibleAssemblyParts(this.config, index); + const wasExploded = this.exploded || this.explosionAmount > 0; + this.exploded = false; + this.explosionAmount = 0; + this.explosionTarget = 0; + this.explosionTransition = null; + for (const transition of this.transitions || []) transition.dispose?.(); + this.transitions = []; + this.animationPaused = false; + const motion = animate && !matchMedia('(prefers-reduced-motion: reduce)').matches; + const activeParts = new Set(index === null ? [] : this.config.steps[index].parts); + const screwDelays = new Map(); + const byId = new Map(this.config.parts.map((part) => [part.id, part])); + let screwDelay = 0; + for (const id of activeParts) { + const installation = byId.get(id).installation; + if (installation?.type === 'screw') { + screwDelays.set(id, screwDelay); + screwDelay += screwDuration(installation); + } + } + for (const part of this.config.parts) { + const instance = this.parts.get(part.id); + instance.visible = installed.has(part.id); + instance.position.fromArray(part.position); + instance.quaternion.fromArray(part.quaternion); + if (instance.visible && activeParts.has(part.id) && motion) { + if (part.installation?.type === 'screw') { + const toolConfig = this.toolConfigs.get(part.installation.toolId); + const tool = new THREE.Group(); + tool.name = `assembly-tool-${toolConfig.id}`; + tool.add(this.templates.get(toolConfig.file).clone(true)); + this.transitions.push(new ScrewTransition(instance, part, tool, toolConfig, screwDelays.get(part.id))); + // One tool works on one fastener at a time; ordinary parts keep sliding in. + continue; + } + const target = instance.position.clone(); + instance.position.add(new THREE.Vector3(...part.installOffset)); + this.transitions.push({ instance, from: instance.position.clone(), target, elapsed: 0, duration: 0.55 }); + } + } + this.installed = installed; + this.stepIndex = index; + if (wasExploded || (this.focusedPartId && (index === null || !screwDelays.size))) this.resetView(); + this.renderer.shadowMap.needsUpdate = true; + this.notifyMotion(); + this.loop.invalidate(); + } + + setAnimationPaused(paused) { this.animationPaused = paused; this.loop.invalidate(); } + + setExploded(enabled, amount = 0.65, animate = true) { + if (!this.model || this.config.parts.length < 2 || this.disposed) return; + if (this.stepIndex !== null) this.setStep(null, false); + if (!this.explodedLayout) this.explodedLayout = createExplodedLayout(this.config, this.parts); + this.exploded = enabled; + this.focusedPartId = null; + this.controls.maxPolarAngle = Math.PI * 0.49; + this.explosionTarget = enabled ? Math.max(0, Math.min(1, Number.isFinite(amount) ? amount : 0.65)) : 0; + const frame = this.frameForBounds(this.explodedLayout.boundsAt(this.explosionTarget)); + const motion = animate && !matchMedia('(prefers-reduced-motion: reduce)').matches; + if (motion) { + this.explosionTransition = { from: this.explosionAmount, target: this.explosionTarget, elapsed: 0, + camera: this.camera.position.clone(), focus: this.controls.target.clone(), frame, moveCamera: true }; + } else { + this.explosionTransition = null; + this.explosionAmount = this.explosionTarget; + this.explodedLayout.apply(this.explosionAmount); + this.camera.position.copy(frame.position); + this.controls.target.copy(frame.target); + } + this.renderer.shadowMap.needsUpdate = true; + this.loop.invalidate(); + } + + notifyMotion() { + const active = this.transitions?.find((transition) => transition.phase && !['waiting', 'done'].includes(transition.phase)); + const key = active ? `${active.part.id}:${active.phase}` : ''; + if (key === this.motionKey) return; + this.motionKey = key; + if (active && this.focusedPartId && this.focusedPartId !== active.part.id) this.focusPart(active.part.id); + const screws = active && Number.isInteger(this.stepIndex) ? this.config.steps[this.stepIndex].parts + .filter((id) => this.config.parts.find((part) => part.id === id)?.installation) : []; + this.onMotionChange?.(active ? { partId: active.part.id, phase: active.phase, + index: screws.indexOf(active.part.id) + 1, count: screws.length } : null); + } + + focusPart(id) { + const part = this.config?.parts.find((part) => part.id === id); + const instance = this.parts?.get(id); + if (!part?.installation || !instance) return; + this.focusedPartId = id; + this.model.updateMatrixWorld(true); + const { socketPosition, axis, toolId } = part.installation; + const tool = this.config.tools.find((tool) => tool.id === toolId); + const toolSize = new THREE.Box3().setFromObject(this.templates.get(tool.file)).getSize(new THREE.Vector3()).length(); + // Frame the final socket, so the camera doesn't chase the approaching tool. + const finalMatrix = new THREE.Matrix4().compose(new THREE.Vector3(...part.position), + new THREE.Quaternion(...part.quaternion), new THREE.Vector3(...part.scale)).premultiply(instance.parent.matrixWorld); + const position = new THREE.Vector3(), rotation = new THREE.Quaternion(), worldScale = new THREE.Vector3(); + finalMatrix.decompose(position, rotation, worldScale); + const scale = worldScale.x; + const outward = new THREE.Vector3(...axis).negate().applyQuaternion(rotation); + const side = new THREE.Vector3(1, 0, 0).applyQuaternion(rotation); + if (Math.abs(side.dot(outward)) > 0.95) side.set(0, 1, 0).applyQuaternion(rotation); + side.addScaledVector(outward, -side.dot(outward)).normalize(); + const head = new THREE.Vector3(...socketPosition).applyMatrix4(finalMatrix); + this.controls.minDistance = 0.03; + this.controls.maxPolarAngle = Math.PI * 0.95; + this.controls.target.copy(head).addScaledVector(outward, toolSize * scale * 0.35); + const aspectFit = Math.max(1, 1 / this.camera.aspect); + this.camera.position.copy(this.controls.target).addScaledVector(outward, toolSize * scale * 2 * aspectFit) + .addScaledVector(side, toolSize * scale * 2.3 * aspectFit); + this.controls.update(); + this.loop.invalidate(); + } + + frameForBounds(bounds) { + const size = bounds.getSize(new THREE.Vector3()); + const target = bounds.getCenter(new THREE.Vector3()); + const fov = THREE.MathUtils.degToRad(this.camera.fov); + // 按实际观察方向投影包围盒,兼顾厚模型与竖屏,避免保守球体取景把细长模型缩得过小。 + const direction = new THREE.Vector3(1, 0.16, -0.65).normalize(); + const right = new THREE.Vector3().crossVectors(this.camera.up, direction).normalize(); + const up = new THREE.Vector3().crossVectors(direction, right); + const tanY = Math.tan(fov / 2), tanX = tanY * this.camera.aspect; + let distance = 0; + for (const x of [-1, 1]) for (const y of [-1, 1]) for (const z of [-1, 1]) { + const corner = new THREE.Vector3(x * size.x, y * size.y, z * size.z).multiplyScalar(0.5); + const depth = corner.dot(direction); + distance = Math.max(distance, depth + Math.abs(corner.dot(right)) / tanX * 1.3, depth + Math.abs(corner.dot(up)) / tanY * 1.3); + } + this.controls.maxDistance = Math.max(7, distance * 2); + return { target, position: direction.multiplyScalar(distance).add(target) }; + } + + resetView() { + if (!this.assembledBounds) return; + this.focusedPartId = null; + this.controls.maxPolarAngle = Math.PI * 0.49; + const bounds = this.exploded ? this.explodedLayout.boundsAt(this.explosionTarget) : this.assembledBounds; + const frame = this.frameForBounds(bounds); + if (this.explosionTransition) { + // Resizing/control-bar changes may happen after the toggle's first frame. + this.explosionTransition.frame = frame; + return; + } + this.controls.target.copy(frame.target); + this.camera.position.copy(frame.position); + this.controls.update(); + this.loop.invalidate(); + } + + setAutoRotate(enabled) { this.controls.autoRotate = enabled; this.loop.invalidate(); } + + resize(refit = true) { + const { clientWidth: width, clientHeight: height } = this.container; + if (!width || !height || this.disposed) return; + this.renderer.setPixelRatio(this.budget.pixelRatio(width, height)); + this.renderer.shadowMap.enabled = this.budget.shadows; + this.renderer.setSize(width, height); + this.camera.aspect = width / height; + this.camera.updateProjectionMatrix(); + if (refit) { + if (this.focusedPartId) this.focusPart(this.focusedPartId); + else this.resetView(); + } + this.loop?.invalidate(); + } + + render(dt) { + if (this.disposed) return; + if (this.explosionTransition) { + const transition = this.explosionTransition; + transition.elapsed += dt; + const t = Math.min(1, transition.elapsed / 0.6), eased = t * t * (3 - 2 * t); + this.explosionAmount = THREE.MathUtils.lerp(transition.from, transition.target, eased); + this.explodedLayout.apply(this.explosionAmount); + if (transition.moveCamera) { + this.camera.position.lerpVectors(transition.camera, transition.frame.position, eased); + this.controls.target.lerpVectors(transition.focus, transition.frame.target, eased); + } + this.renderer.shadowMap.needsUpdate = true; + if (t === 1) this.explosionTransition = null; + } + const wasAnimating = this.transitions?.length > 0; + if (!this.animationPaused) for (const transition of this.transitions || []) { + if (transition.update) transition.update(dt); + else { + transition.elapsed += dt; + const t = Math.min(1, transition.elapsed / transition.duration); + transition.instance.position.lerpVectors(transition.from, transition.target, 1 - (1 - t) ** 3); + } + if (transition.elapsed >= transition.duration) transition.dispose?.(); + this.renderer.shadowMap.needsUpdate = true; + } + this.transitions = (this.transitions || []).filter((transition) => transition.elapsed < transition.duration); + this.notifyMotion(); + if (wasAnimating && !this.transitions.length) this.onAnimationEnd?.(); + const moving = this.controls.update(dt); + this.renderer.render(this.scene, this.camera); + return moving || this.controls.autoRotate || !!this.explosionTransition || (!this.animationPaused && this.transitions.length > 0); + } + + dispose() { + if (this.disposed) return; + this.disposed = true; + this.loop.dispose(); + document.removeEventListener('visibilitychange', this.onVisibility); + this.resizeObserver.disconnect(); + this.intersectionObserver.disconnect(); + this.controls.dispose(); + disposeObject([this.scene, ...this.templates?.values() || []]); + this.templates?.clear(); + this.scene.traverse((object) => object.shadow?.dispose()); + this.environment.dispose(); + this.renderer.dispose(); + this.renderer.forceContextLoss(); + this.renderer.domElement.remove(); + } +} diff --git a/js/assembly.js b/js/assembly.js new file mode 100644 index 0000000..fb7529b --- /dev/null +++ b/js/assembly.js @@ -0,0 +1,224 @@ +import { icon } from './layout.js'; +import { assemblySource, loadProjectAssembly } from './project-resources.js'; + +export const getAssemblyModel = (project) => assemblySource(project); + +let activeDialog; + +export function openAssemblyPreview(project, { initialStep = null, focusPartId = null } = {}) { + const model = getAssemblyModel(project); + if (!model || activeDialog) return; + const previousFocus = document.activeElement; + const previousOverflow = document.body.style.overflow; + const dialog = document.createElement('dialog'); + activeDialog = dialog; + dialog.className = 'assembly-dialog'; + dialog.setAttribute('aria-label', `${project.name} 装配模型`); + dialog.innerHTML = ` + +
+
+ +
+ 正在加载装配模型准备模型与材质… + +
+ + +
+ + + + + + +
+
`; + document.body.append(dialog); + dialog.showModal(); + document.body.style.overflow = 'hidden'; + + const find = (selector) => dialog.querySelector(selector); + const controller = new AbortController(); + let preview; + let loading = false; + let config; + let stepIndex = null; + let playing = false; + let playTimer; + let activeScrew; + let exploded = false; + const updateExplosionUI = (enabled) => { + exploded = enabled; + find('.assembly-viewport').classList.toggle('is-exploded', enabled); + find('.assembly-explosion').hidden = !enabled; + find('[data-explode]').textContent = 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); + }; + const showStep = (index, animate = true) => { + stepIndex = index; + updateExplosionUI(false); + preview.setStep(index, animate); + find('[data-play]').textContent = preview.transitions.length ? '暂停装配' : '播放装配'; + find('[data-play]').setAttribute('aria-pressed', String(preview.transitions.length > 0)); + 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-rotate]').hidden = index !== null; + find('[data-explode]').hidden = index !== null || config.parts.length < 2; + find('[data-steps]').textContent = index === null ? '逐步装配' : '查看整体'; + if (index !== null) { + preview.setAutoRotate(false); + find('[data-rotate]').setAttribute('aria-pressed', 'false'); + } + 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]').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; + } + }; + find('[data-explode]').addEventListener('click', () => { + stopPlayback(); + updateExplosionUI(!exploded); + preview.setExploded(exploded, Number(find('[data-explosion]').value) / 100); + }); + find('[data-explosion]').addEventListener('input', (event) => { + const amount = Number(event.target.value); + find('[data-explosion-value]').textContent = `${amount}%`; + preview.setExploded(true, amount / 100, false); + }); + find('[data-steps]').addEventListener('click', () => { stopPlayback(); showStep(stepIndex === null ? 0 : null); }); + find('[data-prev]').addEventListener('click', () => { stopPlayback(); showStep(Math.max(0, stepIndex - 1)); }); + find('[data-next]').addEventListener('click', () => { stopPlayback(); showStep(Math.min(config.steps.length - 1, stepIndex + 1)); }); + 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); + playing = true; + preview.setAnimationPaused(false); + find('[data-play]').textContent = '暂停装配'; + find('[data-play]').setAttribute('aria-pressed', 'true'); + 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) { + if (stepIndex === config.steps.length - 1) { stopPlayback(); return; } + showStep(stepIndex + 1); + } + playTimer = setTimeout(advance, 700); + }; + playTimer = setTimeout(advance, 700); + }); + const visibility = () => { if (document.hidden) stopPlayback(); }; + document.addEventListener('visibilitychange', visibility); + const setEnabled = (enabled) => { + dialog.querySelectorAll('[data-reset], [data-rotate], [data-explode]').forEach((b) => { b.disabled = !enabled; }); + }; + + dialog.addEventListener('close', () => { + stopPlayback(); + document.removeEventListener('visibilitychange', visibility); + controller.abort(); + preview?.dispose(); + document.body.style.overflow = previousOverflow; + dialog.remove(); + activeDialog = null; + previousFocus?.focus({ preventScroll: true }); + }, { once: true }); + find('[data-close]').addEventListener('click', () => dialog.close()); + // 只有整个手势都在弹窗外才关闭,避免旋转模型时拖出窗口误关。 + let outside = false; + dialog.addEventListener('pointerdown', (e) => { outside = e.target === dialog; }); + dialog.addEventListener('click', (e) => { if (outside && e.target === dialog) dialog.close(); }); + + find('[data-reset]').addEventListener('click', () => preview?.resetView()); + find('[data-rotate]').addEventListener('click', (e) => { + const button = e.currentTarget; + const enabled = button.getAttribute('aria-pressed') !== 'true'; + preview?.setAutoRotate(enabled); + button.setAttribute('aria-pressed', String(enabled)); + }); + + async function load() { + if (loading || controller.signal.aborted) return; + loading = true; + const overlay = find('.assembly-loading'); + overlay.hidden = false; + overlay.classList.remove('is-error'); + find('[data-retry]').hidden = true; + find('[data-progress]').textContent = '准备模型与材质…'; + overlay.querySelector('strong').textContent = '正在加载装配模型'; + setEnabled(false); + try { + find('[data-progress]').textContent = '读取装配清单…'; + const [{ AssemblyViewer }, pkg] = await Promise.all([import('./assembly-viewer.js'), loadProjectAssembly(project, controller.signal)]); + config = pkg; + if (controller.signal.aborted) return; + preview = new AssemblyViewer(find('.assembly-scene')); + preview.onMotionChange = (motion) => { + activeScrew = motion?.partId; + find('[data-focus]').hidden = !motion; + if (motion) { + const phase = { approach: '螺丝就位', engage: '插入扳手', tighten: '拧紧螺丝', retract: '退出扳手' }[motion.phase]; + find('[data-motion-label]').textContent = `${phase} · ${motion.index} / ${motion.count}`; + } + }; + await preview.load(config, controller.signal, (percent) => { + find('[data-progress]').textContent = percent < 100 ? `读取模型 ${percent}%` : '正在还原材质…'; + }); + if (controller.signal.aborted) return; + preview.onAnimationEnd = () => { if (!playing) stopPlayback(); }; + overlay.hidden = true; + setEnabled(true); + find('[data-steps]').hidden = config.steps.length === 0; + find('[data-explode]').hidden = config.parts.length < 2; + find('[data-seek]').max = String(Math.max(0, config.steps.length - 1)); + if (Number.isInteger(initialStep) && initialStep >= 0 && initialStep < config.steps.length) { + showStep(initialStep, false); + if (focusPartId) preview.focusPart(focusPartId); + showStep(initialStep); + } + } catch (err) { + preview?.dispose(); + preview = null; + if (controller.signal.aborted) return; + console.error('装配模型加载失败', err); + overlay.classList.add('is-error'); + overlay.querySelector('strong').textContent = '模型暂时无法加载'; + find('[data-progress]').textContent = err.message || '请重试,或关闭后重新打开。'; + find('[data-retry]').hidden = false; + } finally { + loading = false; + } + } + find('[data-retry]').addEventListener('click', load); + load(); + return dialog; +} diff --git a/js/auth.js b/js/auth.js index 7950937..c2abdb7 100644 --- a/js/auth.js +++ b/js/auth.js @@ -32,7 +32,7 @@ export function openLogin() { if (loginOpen) return loginOpen; loginOpen = new Promise((resolve) => { const m = openModal({ - title: '登录 vibemake', + title: '登录 make', body: `