Merge remote-tracking branch 'origin/main'
This commit is contained in:
@@ -401,3 +401,124 @@ build 返回 WalkingEditorBuild(draftRevision、sourceVersion、checkId、capa
|
||||
### 工程文件夹入口与页面命名补充
|
||||
|
||||
后台入口统一命名为“装配与仿真”。行走表单支持直接选择工程根文件夹,不要求压缩为 ZIP;目录文件复用上述批量签名/直传/确认接口,无需新增解压接口。去掉所选外层目录名,保留包内子路径;原路径保留在 originalPath。识别根 robot.json,绑定明确的 model 路径;只有唯一 primary ONNX 时自动绑定基础策略,多个 primary 时由用户选择。已有基础绑定保留,额外动作默认关闭。所有目录资源均可上传,服务端应从这些资源按 MJCF/配置的真实引用解析基础依赖闭包,未绑定且未被引用的素材不进入发布版本。目录不含 robot.json 时提示补充,不能冒充已完成配置。ZIP 继续作为可选导入。
|
||||
|
||||
## 2026-11-02:点击编排与组件总装
|
||||
|
||||
后台装配编辑器默认显示空场景。直接装配时,点击右侧零件即追加一个步骤;再次点击已编排零件只定位预览,不重复安装。仅已编排零件写入公开流程,未使用的 GLB 仍留在项目零件库。当前实现保留已有装配 JSON 中的工具、安装动画等扩展字段及其文件校验记录。
|
||||
|
||||
新建流程会用零件 GLB 内部节点名匹配整机 GLB 的唯一同名节点,并核对局部包围范围(整机与分件可经过不同顶点去重,不要求顶点数量相同)。最终外层变换为 `整机节点世界矩阵 × 零件节点世界矩阵的逆矩阵`。节点重名、几何不匹配或多节点变换不一致时不猜测位置;界面提示该零件待匹配。已有流程的最终位姿保持不变。
|
||||
|
||||
组件模式由管理员主动选择,普通模式不自动生成组件。上传接口仍是 `assembly-json`,公开 JSON 保持 `schemaVersion: 1`、`kind: assembly` 和原有 `files / parts / steps`;新增可选字段:
|
||||
|
||||
```json
|
||||
{
|
||||
"componentPlan": {
|
||||
"version": 1,
|
||||
"components": [
|
||||
{ "id": "head", "name": "头部", "parts": ["head-shell", "head-cover"] },
|
||||
{ "id": "body", "name": "躯干", "parts": ["body-shell"] }
|
||||
],
|
||||
"connections": [
|
||||
{ "id": "head-body", "name": "头部连接躯干", "members": ["head", "body"], "installOffset": [0, 0.08, 0] }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `steps` 仍只记录每个零件一次,保留原始点击顺序;`components` 的排列决定组件制作顺序。组件内部按 `steps` 中的相对顺序播放。
|
||||
- 播放头部的步骤时只显示头部累计装好的零件;进入躯干阶段后收起头部,只显示躯干进度。坐标始终沿用整机位置,收起不改变数据或删除模型。
|
||||
- `connections` 依次连接已完成组件,也可引用更早连接的 `id`,形成多层总装。每完成一个组件,就立即插入所有依赖已就绪的连接,再开始下一组件。例如:头部零件 → 躯干零件 → 头部与躯干拼接 → 左腿零件 → 加装左腿。第一个成员为基体,其余成员沿同一个世界坐标偏移刚性进入,保留内部相对位姿,不再逐件重装或播放螺丝动画。
|
||||
- 每个零件只能归属一个组件,每个组件或连接结果只能被后续连接消费一次;禁止自引用、循环、引用未来节点和重复消费。保存时要求当前工作区先命名为组件,并把所有组件连成一个总装根节点。
|
||||
- 后台预览支持空场景、前后一步、进度拖动、播放到当前步骤、重播当前步骤和查看整体。未显示的零件不提前解析渲染;浏览器预览可缩小解码贴图,上传原字节和校验值保持不变。
|
||||
- “预览到此步”固定目标,从第一阶段依次播放直到该阶段;“重播本步”只播放当前阶段。前进由真实模型动画完成事件触发,不用独立定时器跳步,支持暂停和继续。
|
||||
- 组件工作区的“拼接已有组件”支持将当前未命名零件直接保存为组件并新增连接;已被消费的组件不重复列出,后续选择它已完成的总装。步骤列表包含零件安装和组件拼接,可点击定位任意阶段。
|
||||
|
||||
**前台交接状态:** 本仓库已实现组件编排、JSON 生成、回读和后台预览。当前 `vibemake-site/js/experience-packages.js` 的旧播放器只累加 `steps.parts`,还没有读取 `componentPlan`,因此不能据此宣称社区前台已实现组件收起和连接。前台接入时可对照本仓库 `src/utils/assemblyWorkflow.ts` 中 `assemblyStages()` 的阶段规则:每阶段包含明确的 `parts`(可见集合)、`entering`(本步进入集合)、`offset`(组件连接的世界偏移)。前台需在校验原有零件步骤后编译组件阶段,按每阶段的可见集合替换显示状态,而不是继续累加全部历史零件。
|
||||
|
||||
## 2026-11-02:工具拧入、工作端校准与直接定义组件
|
||||
|
||||
- 顶部撤销、重做使用带文字的按钮。普通装配选好零件后可直接点击“定义为组件”,在对话框勾选成员、填写名称;确认后进入组件列表并保留已有步骤顺序。
|
||||
- 模型下方直接显示当前步骤的六个进入方向、毫米距离和“使用工具拧入”。组件连接阶段也可在这里设置整体进入方向和距离;工具只用于单个零件的安装步骤。
|
||||
- 工具下拉框来自当前项目已上传的 GLB 清单。已经作为装配零件选中的文件须先从流程移除才能用作工具;工具进入独立工具库,不自动生成“安装工具”的步骤。工具文件仍通过 `model-parts` 上传,无新增后端接口。
|
||||
- 新工具首次使用先校准工作端:在工具模型的工作端端面中心点击,获取包含内部节点变换的 GLB 场景根坐标与端面法向;可在校准窗口微调毫米坐标、选择六向或反转。工作轴表示从工具尖端朝螺孔内的方向。已有工具复用原校准,未声明工作轴的旧工具可从工作端附近端面测量。
|
||||
- 螺丝头采用几何主轴、端面法向与两端宽度识别。只在能区分宽头和窄杆时自动配置;不能区分时明确提示,可指定局部拧入轴,或在零件模型上点选螺丝头。不可静默把未知零件当成螺丝或把工具默认成 +Z。
|
||||
- `socketPosition`、`axis` 使用螺丝 GLB 场景根坐标,`tipPosition`、`tipAxis` 使用工具 GLB 场景根坐标;`installOffset` 仍使用螺丝父坐标。计算进入偏移时包含螺丝自身旋转和等比缩放。工具对齐、插入、旋转与退出沿用前台 `js/assembly-motion.js` 的四阶段规则。
|
||||
- 保存时自动写入根节点 `tools: [{id, file, tipPosition, tipAxis}]` 和零件上的 `installation: {type: "screw", toolId, axis, socketPosition, toolQuaternion, direction, turns, travel, approachDuration, engageDuration, tightenDuration, retractDuration, toolClearance}`。工具路径、字节数和 SHA-256 自动列入 `files`。工具 GLB 与原零件 GLB 保持原字节;关闭某颗零件的工具效果会移除该零件的 `installation`,已校准工具保留以便复用。
|
||||
- 旋转圈数为 1–20 整数,拧入行程为 0.01–100 毫米;动画各阶段范围与现有前台校验一致。螺丝及其父节点须等比缩放。旋转以插入点为轴心,工具临时挂在螺丝下,拧入完成后精确恢复原最终位置和方向。
|
||||
- 改动工具、圈数、行程、转角或螺丝头校准后需“应用工具并预览”;未完成的工具配置会阻止保存,避免保存旧参数。播放步骤按实际工具动画时长等待;支持暂停,切换步骤和查看整体时清理临时工具。
|
||||
|
||||
验证:使用当前小鸭子 165 颗杯头螺丝的原始 GLB 核对识别方向与插入点,全部通过,最大插入点差异约 0.000419 毫米。另有六个方向、父级旋转与缩放下的工作端/插入点重合测试,以及工具保存、回读、关闭效果测试。此处描述的是视觉对齐与动画格式,并未增加工具碰撞检测。
|
||||
|
||||
## 2026-11-02:独立组装与继续拼装
|
||||
|
||||
每个零件安装步骤可设置“本步展示”。独立组装只显示当前组件的进度;从续装切回独立组装时,以本步零件开始新场景。继续拼装明确选择一个更早的步骤为基准:保留基准阶段的全部已安装零件,仅把本步 `parts` 作为新增安装集合。后续选择新零件时沿用当前续装进度,也可切回独立组装。组件拼接阶段本身保留基体,不显示这个切换。
|
||||
|
||||
字段仍由后台生成,通过现有 `assembly-json` 接口上传原 JSON;不增加文件上传接口:
|
||||
|
||||
```json
|
||||
{
|
||||
"steps": [
|
||||
{ "id": "install-leg", "label": "安装腿", "parts": ["leg"],
|
||||
"scene": { "mode": "continue", "base": { "kind": "connection", "id": "body-head" } } }
|
||||
],
|
||||
"sceneSequence": [
|
||||
{ "kind": "step", "id": "body-step-1", "componentId": "body" },
|
||||
{ "kind": "step", "id": "body-step-2", "componentId": "body" },
|
||||
{ "kind": "step", "id": "body-step-3", "componentId": "body" },
|
||||
{ "kind": "step", "id": "head-step", "componentId": "head" },
|
||||
{ "kind": "connection", "id": "body-head" },
|
||||
{ "kind": "step", "id": "install-leg" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
上例为字段片段,省略其余原有零件、步骤与组件定义。`scene.mode` 为 `independent` 或 `continue`;后者必须有 `base`。引用使用稳定编号,不使用页面上的第几步:`kind=step` 引用 `steps.id`,`kind=connection` 引用 `componentPlan.connections.id`;可选的 `componentId` 区分一个多零件步骤拆到多个组件时的阶段。组件重命名不改引用;分组变化时只在目标阶段唯一的情况下重新匹配。
|
||||
|
||||
- `sceneSequence` 固定包含零件和组件拼接的播放顺序。旧 JSON 没有这些字段时沿用旧的组件规则;启用新标记后保存完整顺序,保证“躯干三步 → 独立的头 → 头躯干拼接 → 在总装上装腿”不会被按类型重新排序。
|
||||
- 续装阶段的可见集合为 `基准.parts ∪ 本步.entering`,进入集合只有本步零件。后续未单独指定方式的同一工作区步骤沿用续装上下文;保存时补成明确 `scene`。总装后再接独立制作的组件时,基体包含已经续装的零件,避免腿等附件消失。
|
||||
- 尚未分组但已经续装到总装的零件可以直接保存,无需再命名为组件或添加一次重复拼接。独立零件仍要求完成组件定义;依赖必须指向更早阶段,禁止缺失、自引用、向未来引用和循环。删除基准及会间接移除基准的操作会被拦截,先修改依赖步骤再删除。
|
||||
- 新标记、基准和顺序随保存、回读、撤销与重做保留。模型最终位姿、材质、原文件和校验值不变。步骤列表用“独立组装”或“继续拼装 · 接第 N 步”显示规则。
|
||||
|
||||
前台需同步读取 `scene` 与 `sceneSequence`,或对照 `assemblyWorkflow.ts` 编译完整阶段;只累加旧 `steps.parts` 的播放器无法还原独立场景与续装分支。本次实现范围是后台编辑、预览、JSON 和回读。
|
||||
|
||||
## 2026-11-02:整机参考与当前装配双视窗
|
||||
|
||||
编辑器左侧固定为整机参考,使用同一零件库的最终安装位姿;右侧固定为当前步骤的装配进度,最右边保留零件、步骤和组件列表。底部播放控制与安装设置保持在一屏内。工具文件不作为整机零件显示,未能定位的零件沿用原有警告。
|
||||
|
||||
左侧支持点击模型零件隐藏,以及通过“显隐”搜索、查看已隐藏项、逐个恢复、全部显示或全部隐藏。“恢复整机参考”恢复左侧完整显示并重置参考视角;两边可分别旋转、缩放和重置视角。显隐为临时参考状态,不修改步骤、位姿、资源、JSON 或编辑历史,右侧安装、撤销和播放不清空左侧显隐选择。为双视窗控制浏览器预览占用,参考视图降低渲染像素与解码贴图预算,原文件、原材质参数与上传字节保持不变。
|
||||
|
||||
## 2026-11-03:独立组件库与总装步骤分开
|
||||
|
||||
编辑器增加显式的“步骤编排 / 组件制作”操作切换。旧版“直接装配 / 组件装配”的既有时间线、连接与 JSON 保留兼容;新组件库独立于旧 `componentPlan`。创建组件、创建子组件、修改内部步骤不会自动加入或重排项目总装。总装通过“加入总装步骤”显式引用顶层组件;组件通过“加入当前组件”显式引用直接子组件。空组件允许先保存,作为待制作的部位。名称在同一级唯一,可以分别命名躯干、躯干1、躯干2。
|
||||
|
||||
内部 Assembly 新增 `componentLibrary: { version: 1, components: [{ id, name, parentId, parts, steps }] }`:
|
||||
|
||||
- `id` 稳定,重命名不改编号;`parentId` 为 null 或同库上级 ID,只表达目录归属,不自动生成步骤。
|
||||
- `parts` 只记录这个组件直接拥有的零件实例;不同组件不能拥有同一个实例。上级引用子组件不重复取得零件所有权。
|
||||
- `steps` 是组件自己的有序安装步骤。可使用现有方向、工具、独立/续装场景;引用直接子组件时,步骤额外携带 `componentId`、完整叶子 `parts` 快照和 `installOffset`。子组件内部步骤不展开到上级或总装时间线。
|
||||
- 根 `steps` 仍仅为总装顺序。引用组件时必须选择顶层组件,叶子零件不允许重复进入总装。组件引用整体平移,不再次播放内部螺丝工具效果;安装方向/距离只修改该引用的偏移,不修改内部零件参数。
|
||||
- 组件引用只同步叶子清单,不插入或移动外部步骤。保存校验层级/引用循环、零件重复归属、未知组件、错误上级、重复使用、失效引用与内部步骤数据。删除有子组件或被步骤引用的组件会被拦截。撤销/重做同时覆盖库和总装。
|
||||
|
||||
当前单人上传继续使用 `/resources/assembly-json/signature` 与 `PUT /resources/assembly-json`,原文件、哈希与工具文件不变。公开 JSON 根 `parts/steps` 只包含总装使用的实例/步骤;`componentLibrary` 扩展保存上述目录、内部步骤,并有 `parts` 数组保存尚未进入总装的实例定义(同公开 part 结构,使用 `file` 而非内部 `assetId`)。回读合并根 `parts` 与库 `parts` 并验证文件哈希。因此只有组件库时根 `parts/steps` 可以为空,仍可以重新打开继续制作;既有总装的步骤、顺序不会因创建组件而改变。前台应以非空且有效的总装步骤决定播放入口,不能仅凭有 assembly URL 就展示可播放;组件库本身不应作为公开播放序列,后续播放器需支持引用级 `installOffset`。
|
||||
|
||||
**协同接口尚未实现,不能把本次 UI 视为已支持安全的多人同时保存。** 当前后端只原样存 JSON 并替换项目级绑定,没有组件 revision、共享零件实例清单版本、占用事务或条件更新。前端当前归属检查仅针对加载的快照;整个库仍随项目 JSON 一并保存,不是组件级云端增量更新。
|
||||
|
||||
后端联调下一步应提供:共享零件实例固定 ID 与 catalogRevision;组件独立的 revision/版本快照;保存请求包含 expectedRevision、catalogRevision、requestId 和组件步骤;在同一个事务内校验版本、权限、零件唯一归属、引用依赖并提交,冲突返回明确的组件/零件和最新版本。总装应独立保存并引用固定组件版本,组件保存不直接替换已发布总装。现有 JSON 上传/导入、零件增删、清除也必须遵循同样的版本规则;前端提交前先 GET 不能替代后端原子校验。接入之前不开放“多人协同已启用”的提示,也不自动合并或覆盖冲突内容。
|
||||
|
||||
## 2026-11-03:统一选择与分段标记(当前交互,以本节为准)
|
||||
|
||||
删除“直接装配 / 组件装配”以及“完成并命名 / 拼接已有组件 / 连接所选组件”的重复入口。现在只有“创建组件 → 步骤编排”:组件制作独立于总装,保留父子组件;编排侧栏仅有“组件与零件”和“步骤”两页,组件树与零件列表同屏,支持统一搜索。勾选组件即追加一个组件步骤并自动勾选所有叶子零件;取消组件选择撤销对应步骤,成员也取消选中。已有散件/组件的任何叶子交集都会阻止再次选中,部分重叠以半选状态提示。零件随组件选中时不能单独移除;应先取消组件,或回到原组件修改内容。
|
||||
|
||||
总装可选择任意层级的组件,也可单独选择组件中的某个零件;只要同一总装实例不重复即可。目录归属和实际选中是两种关系:同一零件仍只能由一个组件直接拥有;总装引用或选择成员不再次取得其所有权。制作某个组件时只允许选择其直接子组件与未被其他组件占用的零件。上述总装规则替代上一节“只可引用顶层组件”和“总装不能选择已归属组件的散件”。
|
||||
|
||||
拼装采用稀疏分段:
|
||||
|
||||
- 第一步开始展示;未标记的后续步骤默认 `上一阶段.parts ∪ 本步.parts`,进入集合只有本步选择的零件/组件。不要求每步填写展示方式。
|
||||
- “新拼装”在当前步骤写 `scene: {mode:"independent"}`,从本步进入集合重新开始;后面未标记步骤继续在此基础累加,直到下一显式标记。
|
||||
- “继续拼装”可选择更早步骤,写 `scene: {mode:"continue",base:{kind:"step",id}}`;从该进度加装本步内容,后续步骤自动继承。取消标记即恢复接上一步。
|
||||
- 用户主动标记的步骤额外有 `sceneMarker:true`,保存后保持;默认继承步骤没有 `scene`、没有 `sceneMarker`,保存时不再逐步物化。旧版自动生成的相邻 continue 可在首次编辑时清理,新版用户标记不清理。
|
||||
- 引用/删除保护只针对显式续装基准。删除普通中间步骤会自动重新接上有效的上一阶段;移动带标记的步骤保留标记,失效/向未来引用阻止保存。回看旧步骤后再选择零件,仍追加到末尾并继承末尾进度。
|
||||
|
||||
旧 `componentPlan` 的分组与嵌套连接在本地编辑时整理为组件库层级,原分组内部步骤保留,连接作为上级组件中的子组件选择。主流程引用完成的组件,不再把内部准备和总装都作为重复叶子安装。原文件、零件编号、最终位姿、工具配置保留,旧服务器 JSON 在保存前不改动;存在无法唯一转换的引用时应保留原文件并提示问题。新 JSON 仍由现有原样存储接口保存,协同版本/占用事务仍待后端实现。
|
||||
|
||||
播放器需按本节默认累加、稀疏 scene 标记和组件引用整体 offset 编译阶段;不要把所有未标记步骤当成“独立新场景”,也不要将组件内部步骤追加到总装。可对照 `assemblyStages()`。已覆盖混合选择去重、分段继承和接回旧进度、稀疏保存回读、预览暂停恢复、旧组件整理、父子组件存储和工具配置的自动化检查。
|
||||
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Files: docs/assets/js/ASCIIMathML.js
|
||||
|
||||
Copyright (c) 2014 Peter Jipsen and other ASCIIMathML.js contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Files: docs/assets/css/pygments/*
|
||||
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <http://unlicense.org>
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
Draco glTF decoders copied unchanged from three 0.180.0 examples/jsm/libs/draco/gltf.
|
||||
Upstream: https://github.com/google/draco
|
||||
License: Apache-2.0 (DRACO-LICENSE.txt).
|
||||
Three.js integration license: THREE-LICENSE.txt.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License
|
||||
|
||||
Copyright © 2010-2025 three.js authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Vendored
+33
File diff suppressed because one or more lines are too long
BIN
Binary file not shown.
+116
@@ -0,0 +1,116 @@
|
||||
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.arrayIteratorImpl=function(h){var n=0;return function(){return n<h.length?{done:!1,value:h[n++]}:{done:!0}}};$jscomp.arrayIterator=function(h){return{next:$jscomp.arrayIteratorImpl(h)}};$jscomp.makeIterator=function(h){var n="undefined"!=typeof Symbol&&Symbol.iterator&&h[Symbol.iterator];return n?n.call(h):$jscomp.arrayIterator(h)};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;
|
||||
$jscomp.ISOLATE_POLYFILLS=!1;$jscomp.FORCE_POLYFILL_PROMISE=!1;$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1;$jscomp.getGlobal=function(h){h=["object"==typeof globalThis&&globalThis,h,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var n=0;n<h.length;++n){var k=h[n];if(k&&k.Math==Math)return k}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);
|
||||
$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(h,n,k){if(h==Array.prototype||h==Object.prototype)return h;h[n]=k.value;return h};$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";
|
||||
var $jscomp$lookupPolyfilledValue=function(h,n){var k=$jscomp.propertyToPolyfillSymbol[n];if(null==k)return h[n];k=h[k];return void 0!==k?k:h[n]};$jscomp.polyfill=function(h,n,k,p){n&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(h,n,k,p):$jscomp.polyfillUnisolated(h,n,k,p))};
|
||||
$jscomp.polyfillUnisolated=function(h,n,k,p){k=$jscomp.global;h=h.split(".");for(p=0;p<h.length-1;p++){var l=h[p];if(!(l in k))return;k=k[l]}h=h[h.length-1];p=k[h];n=n(p);n!=p&&null!=n&&$jscomp.defineProperty(k,h,{configurable:!0,writable:!0,value:n})};
|
||||
$jscomp.polyfillIsolated=function(h,n,k,p){var l=h.split(".");h=1===l.length;p=l[0];p=!h&&p in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var y=0;y<l.length-1;y++){var f=l[y];if(!(f in p))return;p=p[f]}l=l[l.length-1];k=$jscomp.IS_SYMBOL_NATIVE&&"es6"===k?p[l]:null;n=n(k);null!=n&&(h?$jscomp.defineProperty($jscomp.polyfills,l,{configurable:!0,writable:!0,value:n}):n!==k&&(void 0===$jscomp.propertyToPolyfillSymbol[l]&&(k=1E9*Math.random()>>>0,$jscomp.propertyToPolyfillSymbol[l]=$jscomp.IS_SYMBOL_NATIVE?
|
||||
$jscomp.global.Symbol(l):$jscomp.POLYFILL_PREFIX+k+"$"+l),$jscomp.defineProperty(p,$jscomp.propertyToPolyfillSymbol[l],{configurable:!0,writable:!0,value:n})))};
|
||||
$jscomp.polyfill("Promise",function(h){function n(){this.batch_=null}function k(f){return f instanceof l?f:new l(function(q,u){q(f)})}if(h&&(!($jscomp.FORCE_POLYFILL_PROMISE||$jscomp.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION&&"undefined"===typeof $jscomp.global.PromiseRejectionEvent)||!$jscomp.global.Promise||-1===$jscomp.global.Promise.toString().indexOf("[native code]")))return h;n.prototype.asyncExecute=function(f){if(null==this.batch_){this.batch_=[];var q=this;this.asyncExecuteFunction(function(){q.executeBatch_()})}this.batch_.push(f)};
|
||||
var p=$jscomp.global.setTimeout;n.prototype.asyncExecuteFunction=function(f){p(f,0)};n.prototype.executeBatch_=function(){for(;this.batch_&&this.batch_.length;){var f=this.batch_;this.batch_=[];for(var q=0;q<f.length;++q){var u=f[q];f[q]=null;try{u()}catch(A){this.asyncThrow_(A)}}}this.batch_=null};n.prototype.asyncThrow_=function(f){this.asyncExecuteFunction(function(){throw f;})};var l=function(f){this.state_=0;this.result_=void 0;this.onSettledCallbacks_=[];this.isRejectionHandled_=!1;var q=this.createResolveAndReject_();
|
||||
try{f(q.resolve,q.reject)}catch(u){q.reject(u)}};l.prototype.createResolveAndReject_=function(){function f(A){return function(F){u||(u=!0,A.call(q,F))}}var q=this,u=!1;return{resolve:f(this.resolveTo_),reject:f(this.reject_)}};l.prototype.resolveTo_=function(f){if(f===this)this.reject_(new TypeError("A Promise cannot resolve to itself"));else if(f instanceof l)this.settleSameAsPromise_(f);else{a:switch(typeof f){case "object":var q=null!=f;break a;case "function":q=!0;break a;default:q=!1}q?this.resolveToNonPromiseObj_(f):
|
||||
this.fulfill_(f)}};l.prototype.resolveToNonPromiseObj_=function(f){var q=void 0;try{q=f.then}catch(u){this.reject_(u);return}"function"==typeof q?this.settleSameAsThenable_(q,f):this.fulfill_(f)};l.prototype.reject_=function(f){this.settle_(2,f)};l.prototype.fulfill_=function(f){this.settle_(1,f)};l.prototype.settle_=function(f,q){if(0!=this.state_)throw Error("Cannot settle("+f+", "+q+"): Promise already settled in state"+this.state_);this.state_=f;this.result_=q;2===this.state_&&this.scheduleUnhandledRejectionCheck_();
|
||||
this.executeOnSettledCallbacks_()};l.prototype.scheduleUnhandledRejectionCheck_=function(){var f=this;p(function(){if(f.notifyUnhandledRejection_()){var q=$jscomp.global.console;"undefined"!==typeof q&&q.error(f.result_)}},1)};l.prototype.notifyUnhandledRejection_=function(){if(this.isRejectionHandled_)return!1;var f=$jscomp.global.CustomEvent,q=$jscomp.global.Event,u=$jscomp.global.dispatchEvent;if("undefined"===typeof u)return!0;"function"===typeof f?f=new f("unhandledrejection",{cancelable:!0}):
|
||||
"function"===typeof q?f=new q("unhandledrejection",{cancelable:!0}):(f=$jscomp.global.document.createEvent("CustomEvent"),f.initCustomEvent("unhandledrejection",!1,!0,f));f.promise=this;f.reason=this.result_;return u(f)};l.prototype.executeOnSettledCallbacks_=function(){if(null!=this.onSettledCallbacks_){for(var f=0;f<this.onSettledCallbacks_.length;++f)y.asyncExecute(this.onSettledCallbacks_[f]);this.onSettledCallbacks_=null}};var y=new n;l.prototype.settleSameAsPromise_=function(f){var q=this.createResolveAndReject_();
|
||||
f.callWhenSettled_(q.resolve,q.reject)};l.prototype.settleSameAsThenable_=function(f,q){var u=this.createResolveAndReject_();try{f.call(q,u.resolve,u.reject)}catch(A){u.reject(A)}};l.prototype.then=function(f,q){function u(w,B){return"function"==typeof w?function(R){try{A(w(R))}catch(Z){F(Z)}}:B}var A,F,v=new l(function(w,B){A=w;F=B});this.callWhenSettled_(u(f,A),u(q,F));return v};l.prototype.catch=function(f){return this.then(void 0,f)};l.prototype.callWhenSettled_=function(f,q){function u(){switch(A.state_){case 1:f(A.result_);
|
||||
break;case 2:q(A.result_);break;default:throw Error("Unexpected state: "+A.state_);}}var A=this;null==this.onSettledCallbacks_?y.asyncExecute(u):this.onSettledCallbacks_.push(u);this.isRejectionHandled_=!0};l.resolve=k;l.reject=function(f){return new l(function(q,u){u(f)})};l.race=function(f){return new l(function(q,u){for(var A=$jscomp.makeIterator(f),F=A.next();!F.done;F=A.next())k(F.value).callWhenSettled_(q,u)})};l.all=function(f){var q=$jscomp.makeIterator(f),u=q.next();return u.done?k([]):new l(function(A,
|
||||
F){function v(R){return function(Z){w[R]=Z;B--;0==B&&A(w)}}var w=[],B=0;do w.push(void 0),B++,k(u.value).callWhenSettled_(v(w.length-1),F),u=q.next();while(!u.done)})};return l},"es6","es3");$jscomp.owns=function(h,n){return Object.prototype.hasOwnProperty.call(h,n)};$jscomp.assign=$jscomp.TRUST_ES6_POLYFILLS&&"function"==typeof Object.assign?Object.assign:function(h,n){for(var k=1;k<arguments.length;k++){var p=arguments[k];if(p)for(var l in p)$jscomp.owns(p,l)&&(h[l]=p[l])}return h};
|
||||
$jscomp.polyfill("Object.assign",function(h){return h||$jscomp.assign},"es6","es3");$jscomp.checkStringArgs=function(h,n,k){if(null==h)throw new TypeError("The 'this' value for String.prototype."+k+" must not be null or undefined");if(n instanceof RegExp)throw new TypeError("First argument to String.prototype."+k+" must not be a regular expression");return h+""};
|
||||
$jscomp.polyfill("String.prototype.startsWith",function(h){return h?h:function(n,k){var p=$jscomp.checkStringArgs(this,n,"startsWith");n+="";var l=p.length,y=n.length;k=Math.max(0,Math.min(k|0,p.length));for(var f=0;f<y&&k<l;)if(p[k++]!=n[f++])return!1;return f>=y}},"es6","es3");
|
||||
$jscomp.polyfill("Array.prototype.copyWithin",function(h){function n(k){k=Number(k);return Infinity===k||-Infinity===k?k:k|0}return h?h:function(k,p,l){var y=this.length;k=n(k);p=n(p);l=void 0===l?y:n(l);k=0>k?Math.max(y+k,0):Math.min(k,y);p=0>p?Math.max(y+p,0):Math.min(p,y);l=0>l?Math.max(y+l,0):Math.min(l,y);if(k<p)for(;p<l;)p in this?this[k++]=this[p++]:(delete this[k++],p++);else for(l=Math.min(l,y+p-k),k+=l-p;l>p;)--l in this?this[--k]=this[l]:delete this[--k];return this}},"es6","es3");
|
||||
$jscomp.typedArrayCopyWithin=function(h){return h?h:Array.prototype.copyWithin};$jscomp.polyfill("Int8Array.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");$jscomp.polyfill("Uint8Array.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");$jscomp.polyfill("Uint8ClampedArray.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");$jscomp.polyfill("Int16Array.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");
|
||||
$jscomp.polyfill("Uint16Array.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");$jscomp.polyfill("Int32Array.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");$jscomp.polyfill("Uint32Array.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");$jscomp.polyfill("Float32Array.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");$jscomp.polyfill("Float64Array.prototype.copyWithin",$jscomp.typedArrayCopyWithin,"es6","es5");
|
||||
var DracoDecoderModule=function(){var h="undefined"!==typeof document&&document.currentScript?document.currentScript.src:void 0;"undefined"!==typeof __filename&&(h=h||__filename);return function(n){function k(e){return a.locateFile?a.locateFile(e,U):U+e}function p(e,b){if(e){var c=ia;var d=e+b;for(b=e;c[b]&&!(b>=d);)++b;if(16<b-e&&c.buffer&&ra)c=ra.decode(c.subarray(e,b));else{for(d="";e<b;){var g=c[e++];if(g&128){var t=c[e++]&63;if(192==(g&224))d+=String.fromCharCode((g&31)<<6|t);else{var aa=c[e++]&
|
||||
63;g=224==(g&240)?(g&15)<<12|t<<6|aa:(g&7)<<18|t<<12|aa<<6|c[e++]&63;65536>g?d+=String.fromCharCode(g):(g-=65536,d+=String.fromCharCode(55296|g>>10,56320|g&1023))}}else d+=String.fromCharCode(g)}c=d}}else c="";return c}function l(){var e=ja.buffer;a.HEAP8=W=new Int8Array(e);a.HEAP16=new Int16Array(e);a.HEAP32=ca=new Int32Array(e);a.HEAPU8=ia=new Uint8Array(e);a.HEAPU16=new Uint16Array(e);a.HEAPU32=Y=new Uint32Array(e);a.HEAPF32=new Float32Array(e);a.HEAPF64=new Float64Array(e)}function y(e){if(a.onAbort)a.onAbort(e);
|
||||
e="Aborted("+e+")";da(e);sa=!0;e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info.");ka(e);throw e;}function f(e){try{if(e==P&&ea)return new Uint8Array(ea);if(ma)return ma(e);throw"both async and sync fetching of the wasm failed";}catch(b){y(b)}}function q(){if(!ea&&(ta||fa)){if("function"==typeof fetch&&!P.startsWith("file://"))return fetch(P,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load wasm binary file at '"+P+"'";return e.arrayBuffer()}).catch(function(){return f(P)});
|
||||
if(na)return new Promise(function(e,b){na(P,function(c){e(new Uint8Array(c))},b)})}return Promise.resolve().then(function(){return f(P)})}function u(e){for(;0<e.length;)e.shift()(a)}function A(e){this.excPtr=e;this.ptr=e-24;this.set_type=function(b){Y[this.ptr+4>>2]=b};this.get_type=function(){return Y[this.ptr+4>>2]};this.set_destructor=function(b){Y[this.ptr+8>>2]=b};this.get_destructor=function(){return Y[this.ptr+8>>2]};this.set_refcount=function(b){ca[this.ptr>>2]=b};this.set_caught=function(b){W[this.ptr+
|
||||
12>>0]=b?1:0};this.get_caught=function(){return 0!=W[this.ptr+12>>0]};this.set_rethrown=function(b){W[this.ptr+13>>0]=b?1:0};this.get_rethrown=function(){return 0!=W[this.ptr+13>>0]};this.init=function(b,c){this.set_adjusted_ptr(0);this.set_type(b);this.set_destructor(c);this.set_refcount(0);this.set_caught(!1);this.set_rethrown(!1)};this.add_ref=function(){ca[this.ptr>>2]+=1};this.release_ref=function(){var b=ca[this.ptr>>2];ca[this.ptr>>2]=b-1;return 1===b};this.set_adjusted_ptr=function(b){Y[this.ptr+
|
||||
16>>2]=b};this.get_adjusted_ptr=function(){return Y[this.ptr+16>>2]};this.get_exception_ptr=function(){if(ua(this.get_type()))return Y[this.excPtr>>2];var b=this.get_adjusted_ptr();return 0!==b?b:this.excPtr}}function F(){function e(){if(!la&&(la=!0,a.calledRun=!0,!sa)){va=!0;u(oa);wa(a);if(a.onRuntimeInitialized)a.onRuntimeInitialized();if(a.postRun)for("function"==typeof a.postRun&&(a.postRun=[a.postRun]);a.postRun.length;)xa.unshift(a.postRun.shift());u(xa)}}if(!(0<ba)){if(a.preRun)for("function"==
|
||||
typeof a.preRun&&(a.preRun=[a.preRun]);a.preRun.length;)ya.unshift(a.preRun.shift());u(ya);0<ba||(a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1);e()},1)):e())}}function v(){}function w(e){return(e||v).__cache__}function B(e,b){var c=w(b),d=c[e];if(d)return d;d=Object.create((b||v).prototype);d.ptr=e;return c[e]=d}function R(e){if("string"===typeof e){for(var b=0,c=0;c<e.length;++c){var d=e.charCodeAt(c);127>=d?b++:2047>=d?b+=2:55296<=d&&57343>=
|
||||
d?(b+=4,++c):b+=3}b=Array(b+1);c=0;d=b.length;if(0<d){d=c+d-1;for(var g=0;g<e.length;++g){var t=e.charCodeAt(g);if(55296<=t&&57343>=t){var aa=e.charCodeAt(++g);t=65536+((t&1023)<<10)|aa&1023}if(127>=t){if(c>=d)break;b[c++]=t}else{if(2047>=t){if(c+1>=d)break;b[c++]=192|t>>6}else{if(65535>=t){if(c+2>=d)break;b[c++]=224|t>>12}else{if(c+3>=d)break;b[c++]=240|t>>18;b[c++]=128|t>>12&63}b[c++]=128|t>>6&63}b[c++]=128|t&63}}b[c]=0}e=r.alloc(b,W);r.copy(b,W,e);return e}return e}function Z(e){if("object"===
|
||||
typeof e){var b=r.alloc(e,W);r.copy(e,W,b);return b}return e}function X(){throw"cannot construct a VoidPtr, no constructor in IDL";}function S(){this.ptr=za();w(S)[this.ptr]=this}function Q(){this.ptr=Aa();w(Q)[this.ptr]=this}function V(){this.ptr=Ba();w(V)[this.ptr]=this}function x(){this.ptr=Ca();w(x)[this.ptr]=this}function D(){this.ptr=Da();w(D)[this.ptr]=this}function G(){this.ptr=Ea();w(G)[this.ptr]=this}function H(){this.ptr=Fa();w(H)[this.ptr]=this}function E(){this.ptr=Ga();w(E)[this.ptr]=
|
||||
this}function T(){this.ptr=Ha();w(T)[this.ptr]=this}function C(){throw"cannot construct a Status, no constructor in IDL";}function I(){this.ptr=Ia();w(I)[this.ptr]=this}function J(){this.ptr=Ja();w(J)[this.ptr]=this}function K(){this.ptr=Ka();w(K)[this.ptr]=this}function L(){this.ptr=La();w(L)[this.ptr]=this}function M(){this.ptr=Ma();w(M)[this.ptr]=this}function N(){this.ptr=Na();w(N)[this.ptr]=this}function O(){this.ptr=Oa();w(O)[this.ptr]=this}function z(){this.ptr=Pa();w(z)[this.ptr]=this}function m(){this.ptr=
|
||||
Qa();w(m)[this.ptr]=this}n=void 0===n?{}:n;var a="undefined"!=typeof n?n:{},wa,ka;a.ready=new Promise(function(e,b){wa=e;ka=b});var Ra=!1,Sa=!1;a.onRuntimeInitialized=function(){Ra=!0;if(Sa&&"function"===typeof a.onModuleLoaded)a.onModuleLoaded(a)};a.onModuleParsed=function(){Sa=!0;if(Ra&&"function"===typeof a.onModuleLoaded)a.onModuleLoaded(a)};a.isVersionSupported=function(e){if("string"!==typeof e)return!1;e=e.split(".");return 2>e.length||3<e.length?!1:1==e[0]&&0<=e[1]&&5>=e[1]?!0:0!=e[0]||10<
|
||||
e[1]?!1:!0};var Ta=Object.assign({},a),ta="object"==typeof window,fa="function"==typeof importScripts,Ua="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,U="";if(Ua){var Va=require("fs"),pa=require("path");U=fa?pa.dirname(U)+"/":__dirname+"/";var Wa=function(e,b){e=e.startsWith("file://")?new URL(e):pa.normalize(e);return Va.readFileSync(e,b?void 0:"utf8")};var ma=function(e){e=Wa(e,!0);e.buffer||(e=new Uint8Array(e));return e};var na=function(e,
|
||||
b,c){e=e.startsWith("file://")?new URL(e):pa.normalize(e);Va.readFile(e,function(d,g){d?c(d):b(g.buffer)})};1<process.argv.length&&process.argv[1].replace(/\\/g,"/");process.argv.slice(2);a.inspect=function(){return"[Emscripten Module object]"}}else if(ta||fa)fa?U=self.location.href:"undefined"!=typeof document&&document.currentScript&&(U=document.currentScript.src),h&&(U=h),U=0!==U.indexOf("blob:")?U.substr(0,U.replace(/[?#].*/,"").lastIndexOf("/")+1):"",Wa=function(e){var b=new XMLHttpRequest;b.open("GET",
|
||||
e,!1);b.send(null);return b.responseText},fa&&(ma=function(e){var b=new XMLHttpRequest;b.open("GET",e,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),na=function(e,b,c){var d=new XMLHttpRequest;d.open("GET",e,!0);d.responseType="arraybuffer";d.onload=function(){200==d.status||0==d.status&&d.response?b(d.response):c()};d.onerror=c;d.send(null)};a.print||console.log.bind(console);var da=a.printErr||console.warn.bind(console);Object.assign(a,Ta);Ta=null;var ea;a.wasmBinary&&
|
||||
(ea=a.wasmBinary);"object"!=typeof WebAssembly&&y("no native wasm support detected");var ja,sa=!1,ra="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,W,ia,ca,Y,ya=[],oa=[],xa=[],va=!1,ba=0,qa=null,ha=null;var P="draco_decoder_gltf.wasm";P.startsWith("data:application/octet-stream;base64,")||(P=k(P));var pd=0,qd={b:function(e,b,c){(new A(e)).init(b,c);pd++;throw e;},a:function(){y("")},d:function(e,b,c){ia.copyWithin(e,b,b+c)},c:function(e){var b=ia.length;e>>>=0;if(2147483648<e)return!1;
|
||||
for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,e+100663296);var g=Math;d=Math.max(e,d);g=g.min.call(g,2147483648,d+(65536-d%65536)%65536);a:{d=ja.buffer;try{ja.grow(g-d.byteLength+65535>>>16);l();var t=1;break a}catch(aa){}t=void 0}if(t)return!0}return!1}};(function(){function e(g,t){a.asm=g.exports;ja=a.asm.e;l();oa.unshift(a.asm.f);ba--;a.monitorRunDependencies&&a.monitorRunDependencies(ba);0==ba&&(null!==qa&&(clearInterval(qa),qa=null),ha&&(g=ha,ha=null,g()))}function b(g){e(g.instance)}
|
||||
function c(g){return q().then(function(t){return WebAssembly.instantiate(t,d)}).then(function(t){return t}).then(g,function(t){da("failed to asynchronously prepare wasm: "+t);y(t)})}var d={a:qd};ba++;a.monitorRunDependencies&&a.monitorRunDependencies(ba);if(a.instantiateWasm)try{return a.instantiateWasm(d,e)}catch(g){da("Module.instantiateWasm callback failed with error: "+g),ka(g)}(function(){return ea||"function"!=typeof WebAssembly.instantiateStreaming||P.startsWith("data:application/octet-stream;base64,")||
|
||||
P.startsWith("file://")||Ua||"function"!=typeof fetch?c(b):fetch(P,{credentials:"same-origin"}).then(function(g){return WebAssembly.instantiateStreaming(g,d).then(b,function(t){da("wasm streaming compile failed: "+t);da("falling back to ArrayBuffer instantiation");return c(b)})})})().catch(ka);return{}})();var Xa=a._emscripten_bind_VoidPtr___destroy___0=function(){return(Xa=a._emscripten_bind_VoidPtr___destroy___0=a.asm.h).apply(null,arguments)},za=a._emscripten_bind_DecoderBuffer_DecoderBuffer_0=
|
||||
function(){return(za=a._emscripten_bind_DecoderBuffer_DecoderBuffer_0=a.asm.i).apply(null,arguments)},Ya=a._emscripten_bind_DecoderBuffer_Init_2=function(){return(Ya=a._emscripten_bind_DecoderBuffer_Init_2=a.asm.j).apply(null,arguments)},Za=a._emscripten_bind_DecoderBuffer___destroy___0=function(){return(Za=a._emscripten_bind_DecoderBuffer___destroy___0=a.asm.k).apply(null,arguments)},Aa=a._emscripten_bind_AttributeTransformData_AttributeTransformData_0=function(){return(Aa=a._emscripten_bind_AttributeTransformData_AttributeTransformData_0=
|
||||
a.asm.l).apply(null,arguments)},$a=a._emscripten_bind_AttributeTransformData_transform_type_0=function(){return($a=a._emscripten_bind_AttributeTransformData_transform_type_0=a.asm.m).apply(null,arguments)},ab=a._emscripten_bind_AttributeTransformData___destroy___0=function(){return(ab=a._emscripten_bind_AttributeTransformData___destroy___0=a.asm.n).apply(null,arguments)},Ba=a._emscripten_bind_GeometryAttribute_GeometryAttribute_0=function(){return(Ba=a._emscripten_bind_GeometryAttribute_GeometryAttribute_0=
|
||||
a.asm.o).apply(null,arguments)},bb=a._emscripten_bind_GeometryAttribute___destroy___0=function(){return(bb=a._emscripten_bind_GeometryAttribute___destroy___0=a.asm.p).apply(null,arguments)},Ca=a._emscripten_bind_PointAttribute_PointAttribute_0=function(){return(Ca=a._emscripten_bind_PointAttribute_PointAttribute_0=a.asm.q).apply(null,arguments)},cb=a._emscripten_bind_PointAttribute_size_0=function(){return(cb=a._emscripten_bind_PointAttribute_size_0=a.asm.r).apply(null,arguments)},db=a._emscripten_bind_PointAttribute_GetAttributeTransformData_0=
|
||||
function(){return(db=a._emscripten_bind_PointAttribute_GetAttributeTransformData_0=a.asm.s).apply(null,arguments)},eb=a._emscripten_bind_PointAttribute_attribute_type_0=function(){return(eb=a._emscripten_bind_PointAttribute_attribute_type_0=a.asm.t).apply(null,arguments)},fb=a._emscripten_bind_PointAttribute_data_type_0=function(){return(fb=a._emscripten_bind_PointAttribute_data_type_0=a.asm.u).apply(null,arguments)},gb=a._emscripten_bind_PointAttribute_num_components_0=function(){return(gb=a._emscripten_bind_PointAttribute_num_components_0=
|
||||
a.asm.v).apply(null,arguments)},hb=a._emscripten_bind_PointAttribute_normalized_0=function(){return(hb=a._emscripten_bind_PointAttribute_normalized_0=a.asm.w).apply(null,arguments)},ib=a._emscripten_bind_PointAttribute_byte_stride_0=function(){return(ib=a._emscripten_bind_PointAttribute_byte_stride_0=a.asm.x).apply(null,arguments)},jb=a._emscripten_bind_PointAttribute_byte_offset_0=function(){return(jb=a._emscripten_bind_PointAttribute_byte_offset_0=a.asm.y).apply(null,arguments)},kb=a._emscripten_bind_PointAttribute_unique_id_0=
|
||||
function(){return(kb=a._emscripten_bind_PointAttribute_unique_id_0=a.asm.z).apply(null,arguments)},lb=a._emscripten_bind_PointAttribute___destroy___0=function(){return(lb=a._emscripten_bind_PointAttribute___destroy___0=a.asm.A).apply(null,arguments)},Da=a._emscripten_bind_AttributeQuantizationTransform_AttributeQuantizationTransform_0=function(){return(Da=a._emscripten_bind_AttributeQuantizationTransform_AttributeQuantizationTransform_0=a.asm.B).apply(null,arguments)},mb=a._emscripten_bind_AttributeQuantizationTransform_InitFromAttribute_1=
|
||||
function(){return(mb=a._emscripten_bind_AttributeQuantizationTransform_InitFromAttribute_1=a.asm.C).apply(null,arguments)},nb=a._emscripten_bind_AttributeQuantizationTransform_quantization_bits_0=function(){return(nb=a._emscripten_bind_AttributeQuantizationTransform_quantization_bits_0=a.asm.D).apply(null,arguments)},ob=a._emscripten_bind_AttributeQuantizationTransform_min_value_1=function(){return(ob=a._emscripten_bind_AttributeQuantizationTransform_min_value_1=a.asm.E).apply(null,arguments)},pb=
|
||||
a._emscripten_bind_AttributeQuantizationTransform_range_0=function(){return(pb=a._emscripten_bind_AttributeQuantizationTransform_range_0=a.asm.F).apply(null,arguments)},qb=a._emscripten_bind_AttributeQuantizationTransform___destroy___0=function(){return(qb=a._emscripten_bind_AttributeQuantizationTransform___destroy___0=a.asm.G).apply(null,arguments)},Ea=a._emscripten_bind_AttributeOctahedronTransform_AttributeOctahedronTransform_0=function(){return(Ea=a._emscripten_bind_AttributeOctahedronTransform_AttributeOctahedronTransform_0=
|
||||
a.asm.H).apply(null,arguments)},rb=a._emscripten_bind_AttributeOctahedronTransform_InitFromAttribute_1=function(){return(rb=a._emscripten_bind_AttributeOctahedronTransform_InitFromAttribute_1=a.asm.I).apply(null,arguments)},sb=a._emscripten_bind_AttributeOctahedronTransform_quantization_bits_0=function(){return(sb=a._emscripten_bind_AttributeOctahedronTransform_quantization_bits_0=a.asm.J).apply(null,arguments)},tb=a._emscripten_bind_AttributeOctahedronTransform___destroy___0=function(){return(tb=
|
||||
a._emscripten_bind_AttributeOctahedronTransform___destroy___0=a.asm.K).apply(null,arguments)},Fa=a._emscripten_bind_PointCloud_PointCloud_0=function(){return(Fa=a._emscripten_bind_PointCloud_PointCloud_0=a.asm.L).apply(null,arguments)},ub=a._emscripten_bind_PointCloud_num_attributes_0=function(){return(ub=a._emscripten_bind_PointCloud_num_attributes_0=a.asm.M).apply(null,arguments)},vb=a._emscripten_bind_PointCloud_num_points_0=function(){return(vb=a._emscripten_bind_PointCloud_num_points_0=a.asm.N).apply(null,
|
||||
arguments)},wb=a._emscripten_bind_PointCloud___destroy___0=function(){return(wb=a._emscripten_bind_PointCloud___destroy___0=a.asm.O).apply(null,arguments)},Ga=a._emscripten_bind_Mesh_Mesh_0=function(){return(Ga=a._emscripten_bind_Mesh_Mesh_0=a.asm.P).apply(null,arguments)},xb=a._emscripten_bind_Mesh_num_faces_0=function(){return(xb=a._emscripten_bind_Mesh_num_faces_0=a.asm.Q).apply(null,arguments)},yb=a._emscripten_bind_Mesh_num_attributes_0=function(){return(yb=a._emscripten_bind_Mesh_num_attributes_0=
|
||||
a.asm.R).apply(null,arguments)},zb=a._emscripten_bind_Mesh_num_points_0=function(){return(zb=a._emscripten_bind_Mesh_num_points_0=a.asm.S).apply(null,arguments)},Ab=a._emscripten_bind_Mesh___destroy___0=function(){return(Ab=a._emscripten_bind_Mesh___destroy___0=a.asm.T).apply(null,arguments)},Ha=a._emscripten_bind_Metadata_Metadata_0=function(){return(Ha=a._emscripten_bind_Metadata_Metadata_0=a.asm.U).apply(null,arguments)},Bb=a._emscripten_bind_Metadata___destroy___0=function(){return(Bb=a._emscripten_bind_Metadata___destroy___0=
|
||||
a.asm.V).apply(null,arguments)},Cb=a._emscripten_bind_Status_code_0=function(){return(Cb=a._emscripten_bind_Status_code_0=a.asm.W).apply(null,arguments)},Db=a._emscripten_bind_Status_ok_0=function(){return(Db=a._emscripten_bind_Status_ok_0=a.asm.X).apply(null,arguments)},Eb=a._emscripten_bind_Status_error_msg_0=function(){return(Eb=a._emscripten_bind_Status_error_msg_0=a.asm.Y).apply(null,arguments)},Fb=a._emscripten_bind_Status___destroy___0=function(){return(Fb=a._emscripten_bind_Status___destroy___0=
|
||||
a.asm.Z).apply(null,arguments)},Ia=a._emscripten_bind_DracoFloat32Array_DracoFloat32Array_0=function(){return(Ia=a._emscripten_bind_DracoFloat32Array_DracoFloat32Array_0=a.asm._).apply(null,arguments)},Gb=a._emscripten_bind_DracoFloat32Array_GetValue_1=function(){return(Gb=a._emscripten_bind_DracoFloat32Array_GetValue_1=a.asm.$).apply(null,arguments)},Hb=a._emscripten_bind_DracoFloat32Array_size_0=function(){return(Hb=a._emscripten_bind_DracoFloat32Array_size_0=a.asm.aa).apply(null,arguments)},Ib=
|
||||
a._emscripten_bind_DracoFloat32Array___destroy___0=function(){return(Ib=a._emscripten_bind_DracoFloat32Array___destroy___0=a.asm.ba).apply(null,arguments)},Ja=a._emscripten_bind_DracoInt8Array_DracoInt8Array_0=function(){return(Ja=a._emscripten_bind_DracoInt8Array_DracoInt8Array_0=a.asm.ca).apply(null,arguments)},Jb=a._emscripten_bind_DracoInt8Array_GetValue_1=function(){return(Jb=a._emscripten_bind_DracoInt8Array_GetValue_1=a.asm.da).apply(null,arguments)},Kb=a._emscripten_bind_DracoInt8Array_size_0=
|
||||
function(){return(Kb=a._emscripten_bind_DracoInt8Array_size_0=a.asm.ea).apply(null,arguments)},Lb=a._emscripten_bind_DracoInt8Array___destroy___0=function(){return(Lb=a._emscripten_bind_DracoInt8Array___destroy___0=a.asm.fa).apply(null,arguments)},Ka=a._emscripten_bind_DracoUInt8Array_DracoUInt8Array_0=function(){return(Ka=a._emscripten_bind_DracoUInt8Array_DracoUInt8Array_0=a.asm.ga).apply(null,arguments)},Mb=a._emscripten_bind_DracoUInt8Array_GetValue_1=function(){return(Mb=a._emscripten_bind_DracoUInt8Array_GetValue_1=
|
||||
a.asm.ha).apply(null,arguments)},Nb=a._emscripten_bind_DracoUInt8Array_size_0=function(){return(Nb=a._emscripten_bind_DracoUInt8Array_size_0=a.asm.ia).apply(null,arguments)},Ob=a._emscripten_bind_DracoUInt8Array___destroy___0=function(){return(Ob=a._emscripten_bind_DracoUInt8Array___destroy___0=a.asm.ja).apply(null,arguments)},La=a._emscripten_bind_DracoInt16Array_DracoInt16Array_0=function(){return(La=a._emscripten_bind_DracoInt16Array_DracoInt16Array_0=a.asm.ka).apply(null,arguments)},Pb=a._emscripten_bind_DracoInt16Array_GetValue_1=
|
||||
function(){return(Pb=a._emscripten_bind_DracoInt16Array_GetValue_1=a.asm.la).apply(null,arguments)},Qb=a._emscripten_bind_DracoInt16Array_size_0=function(){return(Qb=a._emscripten_bind_DracoInt16Array_size_0=a.asm.ma).apply(null,arguments)},Rb=a._emscripten_bind_DracoInt16Array___destroy___0=function(){return(Rb=a._emscripten_bind_DracoInt16Array___destroy___0=a.asm.na).apply(null,arguments)},Ma=a._emscripten_bind_DracoUInt16Array_DracoUInt16Array_0=function(){return(Ma=a._emscripten_bind_DracoUInt16Array_DracoUInt16Array_0=
|
||||
a.asm.oa).apply(null,arguments)},Sb=a._emscripten_bind_DracoUInt16Array_GetValue_1=function(){return(Sb=a._emscripten_bind_DracoUInt16Array_GetValue_1=a.asm.pa).apply(null,arguments)},Tb=a._emscripten_bind_DracoUInt16Array_size_0=function(){return(Tb=a._emscripten_bind_DracoUInt16Array_size_0=a.asm.qa).apply(null,arguments)},Ub=a._emscripten_bind_DracoUInt16Array___destroy___0=function(){return(Ub=a._emscripten_bind_DracoUInt16Array___destroy___0=a.asm.ra).apply(null,arguments)},Na=a._emscripten_bind_DracoInt32Array_DracoInt32Array_0=
|
||||
function(){return(Na=a._emscripten_bind_DracoInt32Array_DracoInt32Array_0=a.asm.sa).apply(null,arguments)},Vb=a._emscripten_bind_DracoInt32Array_GetValue_1=function(){return(Vb=a._emscripten_bind_DracoInt32Array_GetValue_1=a.asm.ta).apply(null,arguments)},Wb=a._emscripten_bind_DracoInt32Array_size_0=function(){return(Wb=a._emscripten_bind_DracoInt32Array_size_0=a.asm.ua).apply(null,arguments)},Xb=a._emscripten_bind_DracoInt32Array___destroy___0=function(){return(Xb=a._emscripten_bind_DracoInt32Array___destroy___0=
|
||||
a.asm.va).apply(null,arguments)},Oa=a._emscripten_bind_DracoUInt32Array_DracoUInt32Array_0=function(){return(Oa=a._emscripten_bind_DracoUInt32Array_DracoUInt32Array_0=a.asm.wa).apply(null,arguments)},Yb=a._emscripten_bind_DracoUInt32Array_GetValue_1=function(){return(Yb=a._emscripten_bind_DracoUInt32Array_GetValue_1=a.asm.xa).apply(null,arguments)},Zb=a._emscripten_bind_DracoUInt32Array_size_0=function(){return(Zb=a._emscripten_bind_DracoUInt32Array_size_0=a.asm.ya).apply(null,arguments)},$b=a._emscripten_bind_DracoUInt32Array___destroy___0=
|
||||
function(){return($b=a._emscripten_bind_DracoUInt32Array___destroy___0=a.asm.za).apply(null,arguments)},Pa=a._emscripten_bind_MetadataQuerier_MetadataQuerier_0=function(){return(Pa=a._emscripten_bind_MetadataQuerier_MetadataQuerier_0=a.asm.Aa).apply(null,arguments)},ac=a._emscripten_bind_MetadataQuerier_HasEntry_2=function(){return(ac=a._emscripten_bind_MetadataQuerier_HasEntry_2=a.asm.Ba).apply(null,arguments)},bc=a._emscripten_bind_MetadataQuerier_GetIntEntry_2=function(){return(bc=a._emscripten_bind_MetadataQuerier_GetIntEntry_2=
|
||||
a.asm.Ca).apply(null,arguments)},cc=a._emscripten_bind_MetadataQuerier_GetIntEntryArray_3=function(){return(cc=a._emscripten_bind_MetadataQuerier_GetIntEntryArray_3=a.asm.Da).apply(null,arguments)},dc=a._emscripten_bind_MetadataQuerier_GetDoubleEntry_2=function(){return(dc=a._emscripten_bind_MetadataQuerier_GetDoubleEntry_2=a.asm.Ea).apply(null,arguments)},ec=a._emscripten_bind_MetadataQuerier_GetStringEntry_2=function(){return(ec=a._emscripten_bind_MetadataQuerier_GetStringEntry_2=a.asm.Fa).apply(null,
|
||||
arguments)},fc=a._emscripten_bind_MetadataQuerier_NumEntries_1=function(){return(fc=a._emscripten_bind_MetadataQuerier_NumEntries_1=a.asm.Ga).apply(null,arguments)},gc=a._emscripten_bind_MetadataQuerier_GetEntryName_2=function(){return(gc=a._emscripten_bind_MetadataQuerier_GetEntryName_2=a.asm.Ha).apply(null,arguments)},hc=a._emscripten_bind_MetadataQuerier___destroy___0=function(){return(hc=a._emscripten_bind_MetadataQuerier___destroy___0=a.asm.Ia).apply(null,arguments)},Qa=a._emscripten_bind_Decoder_Decoder_0=
|
||||
function(){return(Qa=a._emscripten_bind_Decoder_Decoder_0=a.asm.Ja).apply(null,arguments)},ic=a._emscripten_bind_Decoder_DecodeArrayToPointCloud_3=function(){return(ic=a._emscripten_bind_Decoder_DecodeArrayToPointCloud_3=a.asm.Ka).apply(null,arguments)},jc=a._emscripten_bind_Decoder_DecodeArrayToMesh_3=function(){return(jc=a._emscripten_bind_Decoder_DecodeArrayToMesh_3=a.asm.La).apply(null,arguments)},kc=a._emscripten_bind_Decoder_GetAttributeId_2=function(){return(kc=a._emscripten_bind_Decoder_GetAttributeId_2=
|
||||
a.asm.Ma).apply(null,arguments)},lc=a._emscripten_bind_Decoder_GetAttributeIdByName_2=function(){return(lc=a._emscripten_bind_Decoder_GetAttributeIdByName_2=a.asm.Na).apply(null,arguments)},mc=a._emscripten_bind_Decoder_GetAttributeIdByMetadataEntry_3=function(){return(mc=a._emscripten_bind_Decoder_GetAttributeIdByMetadataEntry_3=a.asm.Oa).apply(null,arguments)},nc=a._emscripten_bind_Decoder_GetAttribute_2=function(){return(nc=a._emscripten_bind_Decoder_GetAttribute_2=a.asm.Pa).apply(null,arguments)},
|
||||
oc=a._emscripten_bind_Decoder_GetAttributeByUniqueId_2=function(){return(oc=a._emscripten_bind_Decoder_GetAttributeByUniqueId_2=a.asm.Qa).apply(null,arguments)},pc=a._emscripten_bind_Decoder_GetMetadata_1=function(){return(pc=a._emscripten_bind_Decoder_GetMetadata_1=a.asm.Ra).apply(null,arguments)},qc=a._emscripten_bind_Decoder_GetAttributeMetadata_2=function(){return(qc=a._emscripten_bind_Decoder_GetAttributeMetadata_2=a.asm.Sa).apply(null,arguments)},rc=a._emscripten_bind_Decoder_GetFaceFromMesh_3=
|
||||
function(){return(rc=a._emscripten_bind_Decoder_GetFaceFromMesh_3=a.asm.Ta).apply(null,arguments)},sc=a._emscripten_bind_Decoder_GetTriangleStripsFromMesh_2=function(){return(sc=a._emscripten_bind_Decoder_GetTriangleStripsFromMesh_2=a.asm.Ua).apply(null,arguments)},tc=a._emscripten_bind_Decoder_GetTrianglesUInt16Array_3=function(){return(tc=a._emscripten_bind_Decoder_GetTrianglesUInt16Array_3=a.asm.Va).apply(null,arguments)},uc=a._emscripten_bind_Decoder_GetTrianglesUInt32Array_3=function(){return(uc=
|
||||
a._emscripten_bind_Decoder_GetTrianglesUInt32Array_3=a.asm.Wa).apply(null,arguments)},vc=a._emscripten_bind_Decoder_GetAttributeFloat_3=function(){return(vc=a._emscripten_bind_Decoder_GetAttributeFloat_3=a.asm.Xa).apply(null,arguments)},wc=a._emscripten_bind_Decoder_GetAttributeFloatForAllPoints_3=function(){return(wc=a._emscripten_bind_Decoder_GetAttributeFloatForAllPoints_3=a.asm.Ya).apply(null,arguments)},xc=a._emscripten_bind_Decoder_GetAttributeIntForAllPoints_3=function(){return(xc=a._emscripten_bind_Decoder_GetAttributeIntForAllPoints_3=
|
||||
a.asm.Za).apply(null,arguments)},yc=a._emscripten_bind_Decoder_GetAttributeInt8ForAllPoints_3=function(){return(yc=a._emscripten_bind_Decoder_GetAttributeInt8ForAllPoints_3=a.asm._a).apply(null,arguments)},zc=a._emscripten_bind_Decoder_GetAttributeUInt8ForAllPoints_3=function(){return(zc=a._emscripten_bind_Decoder_GetAttributeUInt8ForAllPoints_3=a.asm.$a).apply(null,arguments)},Ac=a._emscripten_bind_Decoder_GetAttributeInt16ForAllPoints_3=function(){return(Ac=a._emscripten_bind_Decoder_GetAttributeInt16ForAllPoints_3=
|
||||
a.asm.ab).apply(null,arguments)},Bc=a._emscripten_bind_Decoder_GetAttributeUInt16ForAllPoints_3=function(){return(Bc=a._emscripten_bind_Decoder_GetAttributeUInt16ForAllPoints_3=a.asm.bb).apply(null,arguments)},Cc=a._emscripten_bind_Decoder_GetAttributeInt32ForAllPoints_3=function(){return(Cc=a._emscripten_bind_Decoder_GetAttributeInt32ForAllPoints_3=a.asm.cb).apply(null,arguments)},Dc=a._emscripten_bind_Decoder_GetAttributeUInt32ForAllPoints_3=function(){return(Dc=a._emscripten_bind_Decoder_GetAttributeUInt32ForAllPoints_3=
|
||||
a.asm.db).apply(null,arguments)},Ec=a._emscripten_bind_Decoder_GetAttributeDataArrayForAllPoints_5=function(){return(Ec=a._emscripten_bind_Decoder_GetAttributeDataArrayForAllPoints_5=a.asm.eb).apply(null,arguments)},Fc=a._emscripten_bind_Decoder_SkipAttributeTransform_1=function(){return(Fc=a._emscripten_bind_Decoder_SkipAttributeTransform_1=a.asm.fb).apply(null,arguments)},Gc=a._emscripten_bind_Decoder_GetEncodedGeometryType_Deprecated_1=function(){return(Gc=a._emscripten_bind_Decoder_GetEncodedGeometryType_Deprecated_1=
|
||||
a.asm.gb).apply(null,arguments)},Hc=a._emscripten_bind_Decoder_DecodeBufferToPointCloud_2=function(){return(Hc=a._emscripten_bind_Decoder_DecodeBufferToPointCloud_2=a.asm.hb).apply(null,arguments)},Ic=a._emscripten_bind_Decoder_DecodeBufferToMesh_2=function(){return(Ic=a._emscripten_bind_Decoder_DecodeBufferToMesh_2=a.asm.ib).apply(null,arguments)},Jc=a._emscripten_bind_Decoder___destroy___0=function(){return(Jc=a._emscripten_bind_Decoder___destroy___0=a.asm.jb).apply(null,arguments)},Kc=a._emscripten_enum_draco_AttributeTransformType_ATTRIBUTE_INVALID_TRANSFORM=
|
||||
function(){return(Kc=a._emscripten_enum_draco_AttributeTransformType_ATTRIBUTE_INVALID_TRANSFORM=a.asm.kb).apply(null,arguments)},Lc=a._emscripten_enum_draco_AttributeTransformType_ATTRIBUTE_NO_TRANSFORM=function(){return(Lc=a._emscripten_enum_draco_AttributeTransformType_ATTRIBUTE_NO_TRANSFORM=a.asm.lb).apply(null,arguments)},Mc=a._emscripten_enum_draco_AttributeTransformType_ATTRIBUTE_QUANTIZATION_TRANSFORM=function(){return(Mc=a._emscripten_enum_draco_AttributeTransformType_ATTRIBUTE_QUANTIZATION_TRANSFORM=
|
||||
a.asm.mb).apply(null,arguments)},Nc=a._emscripten_enum_draco_AttributeTransformType_ATTRIBUTE_OCTAHEDRON_TRANSFORM=function(){return(Nc=a._emscripten_enum_draco_AttributeTransformType_ATTRIBUTE_OCTAHEDRON_TRANSFORM=a.asm.nb).apply(null,arguments)},Oc=a._emscripten_enum_draco_GeometryAttribute_Type_INVALID=function(){return(Oc=a._emscripten_enum_draco_GeometryAttribute_Type_INVALID=a.asm.ob).apply(null,arguments)},Pc=a._emscripten_enum_draco_GeometryAttribute_Type_POSITION=function(){return(Pc=a._emscripten_enum_draco_GeometryAttribute_Type_POSITION=
|
||||
a.asm.pb).apply(null,arguments)},Qc=a._emscripten_enum_draco_GeometryAttribute_Type_NORMAL=function(){return(Qc=a._emscripten_enum_draco_GeometryAttribute_Type_NORMAL=a.asm.qb).apply(null,arguments)},Rc=a._emscripten_enum_draco_GeometryAttribute_Type_COLOR=function(){return(Rc=a._emscripten_enum_draco_GeometryAttribute_Type_COLOR=a.asm.rb).apply(null,arguments)},Sc=a._emscripten_enum_draco_GeometryAttribute_Type_TEX_COORD=function(){return(Sc=a._emscripten_enum_draco_GeometryAttribute_Type_TEX_COORD=
|
||||
a.asm.sb).apply(null,arguments)},Tc=a._emscripten_enum_draco_GeometryAttribute_Type_GENERIC=function(){return(Tc=a._emscripten_enum_draco_GeometryAttribute_Type_GENERIC=a.asm.tb).apply(null,arguments)},Uc=a._emscripten_enum_draco_EncodedGeometryType_INVALID_GEOMETRY_TYPE=function(){return(Uc=a._emscripten_enum_draco_EncodedGeometryType_INVALID_GEOMETRY_TYPE=a.asm.ub).apply(null,arguments)},Vc=a._emscripten_enum_draco_EncodedGeometryType_POINT_CLOUD=function(){return(Vc=a._emscripten_enum_draco_EncodedGeometryType_POINT_CLOUD=
|
||||
a.asm.vb).apply(null,arguments)},Wc=a._emscripten_enum_draco_EncodedGeometryType_TRIANGULAR_MESH=function(){return(Wc=a._emscripten_enum_draco_EncodedGeometryType_TRIANGULAR_MESH=a.asm.wb).apply(null,arguments)},Xc=a._emscripten_enum_draco_DataType_DT_INVALID=function(){return(Xc=a._emscripten_enum_draco_DataType_DT_INVALID=a.asm.xb).apply(null,arguments)},Yc=a._emscripten_enum_draco_DataType_DT_INT8=function(){return(Yc=a._emscripten_enum_draco_DataType_DT_INT8=a.asm.yb).apply(null,arguments)},Zc=
|
||||
a._emscripten_enum_draco_DataType_DT_UINT8=function(){return(Zc=a._emscripten_enum_draco_DataType_DT_UINT8=a.asm.zb).apply(null,arguments)},$c=a._emscripten_enum_draco_DataType_DT_INT16=function(){return($c=a._emscripten_enum_draco_DataType_DT_INT16=a.asm.Ab).apply(null,arguments)},ad=a._emscripten_enum_draco_DataType_DT_UINT16=function(){return(ad=a._emscripten_enum_draco_DataType_DT_UINT16=a.asm.Bb).apply(null,arguments)},bd=a._emscripten_enum_draco_DataType_DT_INT32=function(){return(bd=a._emscripten_enum_draco_DataType_DT_INT32=
|
||||
a.asm.Cb).apply(null,arguments)},cd=a._emscripten_enum_draco_DataType_DT_UINT32=function(){return(cd=a._emscripten_enum_draco_DataType_DT_UINT32=a.asm.Db).apply(null,arguments)},dd=a._emscripten_enum_draco_DataType_DT_INT64=function(){return(dd=a._emscripten_enum_draco_DataType_DT_INT64=a.asm.Eb).apply(null,arguments)},ed=a._emscripten_enum_draco_DataType_DT_UINT64=function(){return(ed=a._emscripten_enum_draco_DataType_DT_UINT64=a.asm.Fb).apply(null,arguments)},fd=a._emscripten_enum_draco_DataType_DT_FLOAT32=
|
||||
function(){return(fd=a._emscripten_enum_draco_DataType_DT_FLOAT32=a.asm.Gb).apply(null,arguments)},gd=a._emscripten_enum_draco_DataType_DT_FLOAT64=function(){return(gd=a._emscripten_enum_draco_DataType_DT_FLOAT64=a.asm.Hb).apply(null,arguments)},hd=a._emscripten_enum_draco_DataType_DT_BOOL=function(){return(hd=a._emscripten_enum_draco_DataType_DT_BOOL=a.asm.Ib).apply(null,arguments)},id=a._emscripten_enum_draco_DataType_DT_TYPES_COUNT=function(){return(id=a._emscripten_enum_draco_DataType_DT_TYPES_COUNT=
|
||||
a.asm.Jb).apply(null,arguments)},jd=a._emscripten_enum_draco_StatusCode_OK=function(){return(jd=a._emscripten_enum_draco_StatusCode_OK=a.asm.Kb).apply(null,arguments)},kd=a._emscripten_enum_draco_StatusCode_DRACO_ERROR=function(){return(kd=a._emscripten_enum_draco_StatusCode_DRACO_ERROR=a.asm.Lb).apply(null,arguments)},ld=a._emscripten_enum_draco_StatusCode_IO_ERROR=function(){return(ld=a._emscripten_enum_draco_StatusCode_IO_ERROR=a.asm.Mb).apply(null,arguments)},md=a._emscripten_enum_draco_StatusCode_INVALID_PARAMETER=
|
||||
function(){return(md=a._emscripten_enum_draco_StatusCode_INVALID_PARAMETER=a.asm.Nb).apply(null,arguments)},nd=a._emscripten_enum_draco_StatusCode_UNSUPPORTED_VERSION=function(){return(nd=a._emscripten_enum_draco_StatusCode_UNSUPPORTED_VERSION=a.asm.Ob).apply(null,arguments)},od=a._emscripten_enum_draco_StatusCode_UNKNOWN_VERSION=function(){return(od=a._emscripten_enum_draco_StatusCode_UNKNOWN_VERSION=a.asm.Pb).apply(null,arguments)};a._malloc=function(){return(a._malloc=a.asm.Qb).apply(null,arguments)};
|
||||
a._free=function(){return(a._free=a.asm.Rb).apply(null,arguments)};var ua=function(){return(ua=a.asm.Sb).apply(null,arguments)};a.___start_em_js=11660;a.___stop_em_js=11758;var la;ha=function b(){la||F();la||(ha=b)};if(a.preInit)for("function"==typeof a.preInit&&(a.preInit=[a.preInit]);0<a.preInit.length;)a.preInit.pop()();F();v.prototype=Object.create(v.prototype);v.prototype.constructor=v;v.prototype.__class__=v;v.__cache__={};a.WrapperObject=v;a.getCache=w;a.wrapPointer=B;a.castObject=function(b,
|
||||
c){return B(b.ptr,c)};a.NULL=B(0);a.destroy=function(b){if(!b.__destroy__)throw"Error: Cannot destroy object. (Did you create it yourself?)";b.__destroy__();delete w(b.__class__)[b.ptr]};a.compare=function(b,c){return b.ptr===c.ptr};a.getPointer=function(b){return b.ptr};a.getClass=function(b){return b.__class__};var r={buffer:0,size:0,pos:0,temps:[],needed:0,prepare:function(){if(r.needed){for(var b=0;b<r.temps.length;b++)a._free(r.temps[b]);r.temps.length=0;a._free(r.buffer);r.buffer=0;r.size+=
|
||||
r.needed;r.needed=0}r.buffer||(r.size+=128,r.buffer=a._malloc(r.size),r.buffer||y(void 0));r.pos=0},alloc:function(b,c){r.buffer||y(void 0);b=b.length*c.BYTES_PER_ELEMENT;b=b+7&-8;r.pos+b>=r.size?(0<b||y(void 0),r.needed+=b,c=a._malloc(b),r.temps.push(c)):(c=r.buffer+r.pos,r.pos+=b);return c},copy:function(b,c,d){d>>>=0;switch(c.BYTES_PER_ELEMENT){case 2:d>>>=1;break;case 4:d>>>=2;break;case 8:d>>>=3}for(var g=0;g<b.length;g++)c[d+g]=b[g]}};X.prototype=Object.create(v.prototype);X.prototype.constructor=
|
||||
X;X.prototype.__class__=X;X.__cache__={};a.VoidPtr=X;X.prototype.__destroy__=X.prototype.__destroy__=function(){Xa(this.ptr)};S.prototype=Object.create(v.prototype);S.prototype.constructor=S;S.prototype.__class__=S;S.__cache__={};a.DecoderBuffer=S;S.prototype.Init=S.prototype.Init=function(b,c){var d=this.ptr;r.prepare();"object"==typeof b&&(b=Z(b));c&&"object"===typeof c&&(c=c.ptr);Ya(d,b,c)};S.prototype.__destroy__=S.prototype.__destroy__=function(){Za(this.ptr)};Q.prototype=Object.create(v.prototype);
|
||||
Q.prototype.constructor=Q;Q.prototype.__class__=Q;Q.__cache__={};a.AttributeTransformData=Q;Q.prototype.transform_type=Q.prototype.transform_type=function(){return $a(this.ptr)};Q.prototype.__destroy__=Q.prototype.__destroy__=function(){ab(this.ptr)};V.prototype=Object.create(v.prototype);V.prototype.constructor=V;V.prototype.__class__=V;V.__cache__={};a.GeometryAttribute=V;V.prototype.__destroy__=V.prototype.__destroy__=function(){bb(this.ptr)};x.prototype=Object.create(v.prototype);x.prototype.constructor=
|
||||
x;x.prototype.__class__=x;x.__cache__={};a.PointAttribute=x;x.prototype.size=x.prototype.size=function(){return cb(this.ptr)};x.prototype.GetAttributeTransformData=x.prototype.GetAttributeTransformData=function(){return B(db(this.ptr),Q)};x.prototype.attribute_type=x.prototype.attribute_type=function(){return eb(this.ptr)};x.prototype.data_type=x.prototype.data_type=function(){return fb(this.ptr)};x.prototype.num_components=x.prototype.num_components=function(){return gb(this.ptr)};x.prototype.normalized=
|
||||
x.prototype.normalized=function(){return!!hb(this.ptr)};x.prototype.byte_stride=x.prototype.byte_stride=function(){return ib(this.ptr)};x.prototype.byte_offset=x.prototype.byte_offset=function(){return jb(this.ptr)};x.prototype.unique_id=x.prototype.unique_id=function(){return kb(this.ptr)};x.prototype.__destroy__=x.prototype.__destroy__=function(){lb(this.ptr)};D.prototype=Object.create(v.prototype);D.prototype.constructor=D;D.prototype.__class__=D;D.__cache__={};a.AttributeQuantizationTransform=
|
||||
D;D.prototype.InitFromAttribute=D.prototype.InitFromAttribute=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return!!mb(c,b)};D.prototype.quantization_bits=D.prototype.quantization_bits=function(){return nb(this.ptr)};D.prototype.min_value=D.prototype.min_value=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return ob(c,b)};D.prototype.range=D.prototype.range=function(){return pb(this.ptr)};D.prototype.__destroy__=D.prototype.__destroy__=function(){qb(this.ptr)};G.prototype=
|
||||
Object.create(v.prototype);G.prototype.constructor=G;G.prototype.__class__=G;G.__cache__={};a.AttributeOctahedronTransform=G;G.prototype.InitFromAttribute=G.prototype.InitFromAttribute=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return!!rb(c,b)};G.prototype.quantization_bits=G.prototype.quantization_bits=function(){return sb(this.ptr)};G.prototype.__destroy__=G.prototype.__destroy__=function(){tb(this.ptr)};H.prototype=Object.create(v.prototype);H.prototype.constructor=H;H.prototype.__class__=
|
||||
H;H.__cache__={};a.PointCloud=H;H.prototype.num_attributes=H.prototype.num_attributes=function(){return ub(this.ptr)};H.prototype.num_points=H.prototype.num_points=function(){return vb(this.ptr)};H.prototype.__destroy__=H.prototype.__destroy__=function(){wb(this.ptr)};E.prototype=Object.create(v.prototype);E.prototype.constructor=E;E.prototype.__class__=E;E.__cache__={};a.Mesh=E;E.prototype.num_faces=E.prototype.num_faces=function(){return xb(this.ptr)};E.prototype.num_attributes=E.prototype.num_attributes=
|
||||
function(){return yb(this.ptr)};E.prototype.num_points=E.prototype.num_points=function(){return zb(this.ptr)};E.prototype.__destroy__=E.prototype.__destroy__=function(){Ab(this.ptr)};T.prototype=Object.create(v.prototype);T.prototype.constructor=T;T.prototype.__class__=T;T.__cache__={};a.Metadata=T;T.prototype.__destroy__=T.prototype.__destroy__=function(){Bb(this.ptr)};C.prototype=Object.create(v.prototype);C.prototype.constructor=C;C.prototype.__class__=C;C.__cache__={};a.Status=C;C.prototype.code=
|
||||
C.prototype.code=function(){return Cb(this.ptr)};C.prototype.ok=C.prototype.ok=function(){return!!Db(this.ptr)};C.prototype.error_msg=C.prototype.error_msg=function(){return p(Eb(this.ptr))};C.prototype.__destroy__=C.prototype.__destroy__=function(){Fb(this.ptr)};I.prototype=Object.create(v.prototype);I.prototype.constructor=I;I.prototype.__class__=I;I.__cache__={};a.DracoFloat32Array=I;I.prototype.GetValue=I.prototype.GetValue=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return Gb(c,
|
||||
b)};I.prototype.size=I.prototype.size=function(){return Hb(this.ptr)};I.prototype.__destroy__=I.prototype.__destroy__=function(){Ib(this.ptr)};J.prototype=Object.create(v.prototype);J.prototype.constructor=J;J.prototype.__class__=J;J.__cache__={};a.DracoInt8Array=J;J.prototype.GetValue=J.prototype.GetValue=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return Jb(c,b)};J.prototype.size=J.prototype.size=function(){return Kb(this.ptr)};J.prototype.__destroy__=J.prototype.__destroy__=function(){Lb(this.ptr)};
|
||||
K.prototype=Object.create(v.prototype);K.prototype.constructor=K;K.prototype.__class__=K;K.__cache__={};a.DracoUInt8Array=K;K.prototype.GetValue=K.prototype.GetValue=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return Mb(c,b)};K.prototype.size=K.prototype.size=function(){return Nb(this.ptr)};K.prototype.__destroy__=K.prototype.__destroy__=function(){Ob(this.ptr)};L.prototype=Object.create(v.prototype);L.prototype.constructor=L;L.prototype.__class__=L;L.__cache__={};a.DracoInt16Array=
|
||||
L;L.prototype.GetValue=L.prototype.GetValue=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return Pb(c,b)};L.prototype.size=L.prototype.size=function(){return Qb(this.ptr)};L.prototype.__destroy__=L.prototype.__destroy__=function(){Rb(this.ptr)};M.prototype=Object.create(v.prototype);M.prototype.constructor=M;M.prototype.__class__=M;M.__cache__={};a.DracoUInt16Array=M;M.prototype.GetValue=M.prototype.GetValue=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return Sb(c,b)};
|
||||
M.prototype.size=M.prototype.size=function(){return Tb(this.ptr)};M.prototype.__destroy__=M.prototype.__destroy__=function(){Ub(this.ptr)};N.prototype=Object.create(v.prototype);N.prototype.constructor=N;N.prototype.__class__=N;N.__cache__={};a.DracoInt32Array=N;N.prototype.GetValue=N.prototype.GetValue=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return Vb(c,b)};N.prototype.size=N.prototype.size=function(){return Wb(this.ptr)};N.prototype.__destroy__=N.prototype.__destroy__=function(){Xb(this.ptr)};
|
||||
O.prototype=Object.create(v.prototype);O.prototype.constructor=O;O.prototype.__class__=O;O.__cache__={};a.DracoUInt32Array=O;O.prototype.GetValue=O.prototype.GetValue=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return Yb(c,b)};O.prototype.size=O.prototype.size=function(){return Zb(this.ptr)};O.prototype.__destroy__=O.prototype.__destroy__=function(){$b(this.ptr)};z.prototype=Object.create(v.prototype);z.prototype.constructor=z;z.prototype.__class__=z;z.__cache__={};a.MetadataQuerier=
|
||||
z;z.prototype.HasEntry=z.prototype.HasEntry=function(b,c){var d=this.ptr;r.prepare();b&&"object"===typeof b&&(b=b.ptr);c=c&&"object"===typeof c?c.ptr:R(c);return!!ac(d,b,c)};z.prototype.GetIntEntry=z.prototype.GetIntEntry=function(b,c){var d=this.ptr;r.prepare();b&&"object"===typeof b&&(b=b.ptr);c=c&&"object"===typeof c?c.ptr:R(c);return bc(d,b,c)};z.prototype.GetIntEntryArray=z.prototype.GetIntEntryArray=function(b,c,d){var g=this.ptr;r.prepare();b&&"object"===typeof b&&(b=b.ptr);c=c&&"object"===
|
||||
typeof c?c.ptr:R(c);d&&"object"===typeof d&&(d=d.ptr);cc(g,b,c,d)};z.prototype.GetDoubleEntry=z.prototype.GetDoubleEntry=function(b,c){var d=this.ptr;r.prepare();b&&"object"===typeof b&&(b=b.ptr);c=c&&"object"===typeof c?c.ptr:R(c);return dc(d,b,c)};z.prototype.GetStringEntry=z.prototype.GetStringEntry=function(b,c){var d=this.ptr;r.prepare();b&&"object"===typeof b&&(b=b.ptr);c=c&&"object"===typeof c?c.ptr:R(c);return p(ec(d,b,c))};z.prototype.NumEntries=z.prototype.NumEntries=function(b){var c=this.ptr;
|
||||
b&&"object"===typeof b&&(b=b.ptr);return fc(c,b)};z.prototype.GetEntryName=z.prototype.GetEntryName=function(b,c){var d=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);return p(gc(d,b,c))};z.prototype.__destroy__=z.prototype.__destroy__=function(){hc(this.ptr)};m.prototype=Object.create(v.prototype);m.prototype.constructor=m;m.prototype.__class__=m;m.__cache__={};a.Decoder=m;m.prototype.DecodeArrayToPointCloud=m.prototype.DecodeArrayToPointCloud=function(b,c,d){var g=
|
||||
this.ptr;r.prepare();"object"==typeof b&&(b=Z(b));c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return B(ic(g,b,c,d),C)};m.prototype.DecodeArrayToMesh=m.prototype.DecodeArrayToMesh=function(b,c,d){var g=this.ptr;r.prepare();"object"==typeof b&&(b=Z(b));c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return B(jc(g,b,c,d),C)};m.prototype.GetAttributeId=m.prototype.GetAttributeId=function(b,c){var d=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&
|
||||
(c=c.ptr);return kc(d,b,c)};m.prototype.GetAttributeIdByName=m.prototype.GetAttributeIdByName=function(b,c){var d=this.ptr;r.prepare();b&&"object"===typeof b&&(b=b.ptr);c=c&&"object"===typeof c?c.ptr:R(c);return lc(d,b,c)};m.prototype.GetAttributeIdByMetadataEntry=m.prototype.GetAttributeIdByMetadataEntry=function(b,c,d){var g=this.ptr;r.prepare();b&&"object"===typeof b&&(b=b.ptr);c=c&&"object"===typeof c?c.ptr:R(c);d=d&&"object"===typeof d?d.ptr:R(d);return mc(g,b,c,d)};m.prototype.GetAttribute=
|
||||
m.prototype.GetAttribute=function(b,c){var d=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);return B(nc(d,b,c),x)};m.prototype.GetAttributeByUniqueId=m.prototype.GetAttributeByUniqueId=function(b,c){var d=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);return B(oc(d,b,c),x)};m.prototype.GetMetadata=m.prototype.GetMetadata=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return B(pc(c,b),T)};m.prototype.GetAttributeMetadata=m.prototype.GetAttributeMetadata=
|
||||
function(b,c){var d=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);return B(qc(d,b,c),T)};m.prototype.GetFaceFromMesh=m.prototype.GetFaceFromMesh=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!rc(g,b,c,d)};m.prototype.GetTriangleStripsFromMesh=m.prototype.GetTriangleStripsFromMesh=function(b,c){var d=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);
|
||||
return sc(d,b,c)};m.prototype.GetTrianglesUInt16Array=m.prototype.GetTrianglesUInt16Array=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!tc(g,b,c,d)};m.prototype.GetTrianglesUInt32Array=m.prototype.GetTrianglesUInt32Array=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!uc(g,b,c,d)};m.prototype.GetAttributeFloat=m.prototype.GetAttributeFloat=
|
||||
function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!vc(g,b,c,d)};m.prototype.GetAttributeFloatForAllPoints=m.prototype.GetAttributeFloatForAllPoints=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!wc(g,b,c,d)};m.prototype.GetAttributeIntForAllPoints=m.prototype.GetAttributeIntForAllPoints=function(b,c,d){var g=this.ptr;
|
||||
b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!xc(g,b,c,d)};m.prototype.GetAttributeInt8ForAllPoints=m.prototype.GetAttributeInt8ForAllPoints=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!yc(g,b,c,d)};m.prototype.GetAttributeUInt8ForAllPoints=m.prototype.GetAttributeUInt8ForAllPoints=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=
|
||||
b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!zc(g,b,c,d)};m.prototype.GetAttributeInt16ForAllPoints=m.prototype.GetAttributeInt16ForAllPoints=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!Ac(g,b,c,d)};m.prototype.GetAttributeUInt16ForAllPoints=m.prototype.GetAttributeUInt16ForAllPoints=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&
|
||||
(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!Bc(g,b,c,d)};m.prototype.GetAttributeInt32ForAllPoints=m.prototype.GetAttributeInt32ForAllPoints=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);return!!Cc(g,b,c,d)};m.prototype.GetAttributeUInt32ForAllPoints=m.prototype.GetAttributeUInt32ForAllPoints=function(b,c,d){var g=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===
|
||||
typeof d&&(d=d.ptr);return!!Dc(g,b,c,d)};m.prototype.GetAttributeDataArrayForAllPoints=m.prototype.GetAttributeDataArrayForAllPoints=function(b,c,d,g,t){var aa=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);d&&"object"===typeof d&&(d=d.ptr);g&&"object"===typeof g&&(g=g.ptr);t&&"object"===typeof t&&(t=t.ptr);return!!Ec(aa,b,c,d,g,t)};m.prototype.SkipAttributeTransform=m.prototype.SkipAttributeTransform=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);Fc(c,
|
||||
b)};m.prototype.GetEncodedGeometryType_Deprecated=m.prototype.GetEncodedGeometryType_Deprecated=function(b){var c=this.ptr;b&&"object"===typeof b&&(b=b.ptr);return Gc(c,b)};m.prototype.DecodeBufferToPointCloud=m.prototype.DecodeBufferToPointCloud=function(b,c){var d=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===typeof c&&(c=c.ptr);return B(Hc(d,b,c),C)};m.prototype.DecodeBufferToMesh=m.prototype.DecodeBufferToMesh=function(b,c){var d=this.ptr;b&&"object"===typeof b&&(b=b.ptr);c&&"object"===
|
||||
typeof c&&(c=c.ptr);return B(Ic(d,b,c),C)};m.prototype.__destroy__=m.prototype.__destroy__=function(){Jc(this.ptr)};(function(){function b(){a.ATTRIBUTE_INVALID_TRANSFORM=Kc();a.ATTRIBUTE_NO_TRANSFORM=Lc();a.ATTRIBUTE_QUANTIZATION_TRANSFORM=Mc();a.ATTRIBUTE_OCTAHEDRON_TRANSFORM=Nc();a.INVALID=Oc();a.POSITION=Pc();a.NORMAL=Qc();a.COLOR=Rc();a.TEX_COORD=Sc();a.GENERIC=Tc();a.INVALID_GEOMETRY_TYPE=Uc();a.POINT_CLOUD=Vc();a.TRIANGULAR_MESH=Wc();a.DT_INVALID=Xc();a.DT_INT8=Yc();a.DT_UINT8=Zc();a.DT_INT16=
|
||||
$c();a.DT_UINT16=ad();a.DT_INT32=bd();a.DT_UINT32=cd();a.DT_INT64=dd();a.DT_UINT64=ed();a.DT_FLOAT32=fd();a.DT_FLOAT64=gd();a.DT_BOOL=hd();a.DT_TYPES_COUNT=id();a.OK=jd();a.DRACO_ERROR=kd();a.IO_ERROR=ld();a.INVALID_PARAMETER=md();a.UNSUPPORTED_VERSION=nd();a.UNKNOWN_VERSION=od()}va?b():oa.unshift(b)})();if("function"===typeof a.onModuleParsed)a.onModuleParsed();a.Decoder.prototype.GetEncodedGeometryType=function(b){if(b.__class__&&b.__class__===a.DecoderBuffer)return a.Decoder.prototype.GetEncodedGeometryType_Deprecated(b);
|
||||
if(8>b.byteLength)return a.INVALID_GEOMETRY_TYPE;switch(b[7]){case 0:return a.POINT_CLOUD;case 1:return a.TRIANGULAR_MESH;default:return a.INVALID_GEOMETRY_TYPE}};return n.ready}}();"object"===typeof exports&&"object"===typeof module?module.exports=DracoDecoderModule:"function"===typeof define&&define.amd?define([],function(){return DracoDecoderModule}):"object"===typeof exports&&(exports.DracoDecoderModule=DracoDecoderModule);
|
||||
@@ -95,12 +95,51 @@ export interface AssemblyPart {
|
||||
quaternion: Quaternion;
|
||||
scale: Vector3;
|
||||
installOffset: Vector3;
|
||||
installation?: ScrewInstallation;
|
||||
}
|
||||
|
||||
export interface AssemblyTool {
|
||||
id: string; assetId: string; name?: string; tipPosition: Vector3; tipAxis?: Vector3;
|
||||
}
|
||||
export interface ScrewInstallation {
|
||||
type: 'screw'; toolId: string; axis: Vector3; socketPosition: Vector3; toolQuaternion: Quaternion;
|
||||
direction: 'clockwise' | 'counterclockwise'; turns: number; travel: number;
|
||||
approachDuration: number; engageDuration: number; tightenDuration: number; retractDuration: number; toolClearance: number;
|
||||
}
|
||||
|
||||
/** 使用稳定的步骤/连接编号,组件重命名、分组后仍能定位同一进度。 */
|
||||
export type AssemblyStageRef = { kind: 'step'; id: string; componentId?: string } | { kind: 'connection'; id: string };
|
||||
export type AssemblyStepScene = { mode: 'independent' } | { mode: 'continue'; base: AssemblyStageRef };
|
||||
export interface AssemblyStep {
|
||||
id: string;
|
||||
label: string;
|
||||
parts: string[];
|
||||
scene?: AssemblyStepScene;
|
||||
/** 用户主动设置的分段起点;后续步骤不需要此字段。 */
|
||||
sceneMarker?: true;
|
||||
/** 主动引用组件库中的组件;parts 是其叶子零件快照,不包含组件内部步骤。 */
|
||||
componentId?: string;
|
||||
/** 组件引用的整体进入偏移,保留组件内部的工具与零件设置。 */
|
||||
installOffset?: Vector3;
|
||||
}
|
||||
|
||||
export interface AssemblyLibraryComponent {
|
||||
id: string;
|
||||
name: string;
|
||||
parentId: string | null;
|
||||
/** 仅直接归属的零件,子组件由 steps.componentId 引用。 */
|
||||
parts: string[];
|
||||
steps: AssemblyStep[];
|
||||
}
|
||||
export interface AssemblyComponentLibrary {
|
||||
version: 1;
|
||||
components: AssemblyLibraryComponent[];
|
||||
}
|
||||
|
||||
export interface AssemblyComponentPlan {
|
||||
version: 1;
|
||||
components: { id: string; name: string; parts: string[] }[];
|
||||
connections: { id: string; name: string; members: string[]; installOffset: Vector3 }[];
|
||||
}
|
||||
|
||||
export interface ExperienceDraftContent {
|
||||
@@ -115,8 +154,14 @@ export interface ExperienceDraftContent {
|
||||
displayQuaternion: Quaternion;
|
||||
parts: AssemblyPart[];
|
||||
steps: AssemblyStep[];
|
||||
/** 显式的播放顺序;老流程缺省时沿用组件制作和依赖就绪顺序。 */
|
||||
sceneSequence?: AssemblyStageRef[];
|
||||
/** 编辑器分组,不写入公开 manifest;服务端保存后原样返回。 */
|
||||
editorGroups?: { id: string; name: string; parts: string[] }[];
|
||||
componentPlan?: AssemblyComponentPlan;
|
||||
/** 独立组件库。内部步骤不会自动加入总装时间线。 */
|
||||
componentLibrary?: AssemblyComponentLibrary;
|
||||
tools?: AssemblyTool[];
|
||||
} | null;
|
||||
walking: {
|
||||
enabled: boolean;
|
||||
|
||||
@@ -26,6 +26,9 @@ export default function StepPanel({ project, onChanged }: {
|
||||
const [error, setError] = useState('');
|
||||
const locked = useRef(false);
|
||||
const mounted = useRef(true);
|
||||
const projectPath = useRef(window.location.pathname);
|
||||
// 路由 transition 可能晚于地址栏更新卸载面板,不能只依赖 unmount 标记。
|
||||
const isCurrentProject = () => mounted.current && window.location.pathname === projectPath.current;
|
||||
const busy = stage !== 'idle';
|
||||
|
||||
useEffect(() => {
|
||||
@@ -34,34 +37,35 @@ export default function StepPanel({ project, onChanged }: {
|
||||
}, []);
|
||||
|
||||
const selectFile = (next: File | null) => {
|
||||
if (locked.current || !mounted.current) return;
|
||||
if (locked.current || !isCurrentProject()) return;
|
||||
setFile(next);
|
||||
setBatch(null);
|
||||
setError('');
|
||||
};
|
||||
|
||||
const upload = async () => {
|
||||
if (locked.current || !file || checkStepFile(file).length) return;
|
||||
if (locked.current || !isCurrentProject() || !file || checkStepFile(file).length) return;
|
||||
locked.current = true;
|
||||
setError('');
|
||||
let pending = batch;
|
||||
try {
|
||||
if (!pending) {
|
||||
pending = await api.uploadStep(project.projectCode, file, (next) => {
|
||||
if (mounted.current) setStage(next);
|
||||
if (isCurrentProject()) setStage(next);
|
||||
});
|
||||
if (!mounted.current) return;
|
||||
if (!isCurrentProject()) return;
|
||||
setBatch(pending);
|
||||
}
|
||||
if (!isCurrentProject()) return;
|
||||
setStage('binding');
|
||||
const updated = await api.confirmStep(project.projectCode, pending);
|
||||
if (!mounted.current) return;
|
||||
if (!isCurrentProject()) return;
|
||||
setFile(null);
|
||||
setBatch(null);
|
||||
message.success('STEP 已绑定');
|
||||
onChanged(updated);
|
||||
} catch (e) {
|
||||
if (!mounted.current) return;
|
||||
if (!isCurrentProject()) return;
|
||||
if (e instanceof AdminApiError && RESET_BATCH_CODES.has(e.code)) {
|
||||
setBatch(null);
|
||||
setError(`${errorText(e)}。已上传文件不可用,请重新上传。`);
|
||||
@@ -78,7 +82,7 @@ export default function StepPanel({ project, onChanged }: {
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
if (locked.current) return;
|
||||
if (locked.current || !isCurrentProject()) return;
|
||||
locked.current = true;
|
||||
setStage('removing');
|
||||
setError('');
|
||||
@@ -86,11 +90,11 @@ export default function StepPanel({ project, onChanged }: {
|
||||
setBatch(null);
|
||||
try {
|
||||
await api.removeStep(project.projectCode);
|
||||
if (!mounted.current) return;
|
||||
if (!isCurrentProject()) return;
|
||||
message.success('已移除 STEP 绑定');
|
||||
onChanged({ ...project, stepMainUrl: null, stepFileName: null, stepSizeBytes: null });
|
||||
} catch (e) {
|
||||
if (!mounted.current) return;
|
||||
if (!isCurrentProject()) return;
|
||||
setError(`${errorText(e)}。请刷新确认当前绑定状态后再操作。`);
|
||||
onChanged();
|
||||
} finally {
|
||||
|
||||
@@ -1,210 +1,214 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Collapse, Empty, Input, InputNumber, Modal, Popconfirm, Segmented, Select, Space, Tag, Tooltip, Typography } from 'antd';
|
||||
import { ArrowDownOutlined, ArrowUpOutlined, CopyOutlined, DeleteOutlined, HolderOutlined, PlayCircleOutlined, PlusOutlined, RedoOutlined, UndoOutlined } from '@ant-design/icons';
|
||||
import type { AssemblyPart } from '@/api/experience-types';
|
||||
import { assemblyManifest, assemblyProblems, copyAssembly, entryOffset, newEditorId, sourcePart, type Assembly, type AssemblySession, type EntrySide } from '@/utils/assemblyEditor';
|
||||
import { App, Button, Collapse, ConfigProvider, Empty, Input, Modal, Popconfirm, Segmented, Select, Slider, Space, Tabs, Tag, theme, Tooltip, Typography } from 'antd';
|
||||
import { ArrowDownOutlined, ArrowLeftOutlined, ArrowRightOutlined, ArrowUpOutlined, DeleteOutlined, HolderOutlined, PauseOutlined, PlayCircleOutlined, PlusOutlined, RedoOutlined, UndoOutlined } from '@ant-design/icons';
|
||||
import type { AssemblyPart, AssemblyStageRef } from '@/api/experience-types';
|
||||
import { assemblyManifest, copyAssembly, type Assembly, type AssemblySession } from '@/utils/assemblyEditor';
|
||||
import { assemblyStages, installedParts, installPart, removeWorkflowPart, removeWorkflowStep, setStepScene, workflowForSave } from '@/utils/assemblyWorkflow';
|
||||
import { createLibraryComponent, deleteLibraryComponent, editLibraryComponent, insertLibraryComponent, libraryComponentAssembly, libraryComponentPath, libraryComponents, libraryOwner } from '@/utils/assemblyLibrary';
|
||||
import { removeRedundantSceneMarkers, simplifyAssembly } from '@/utils/assemblySimplify';
|
||||
import { errorText } from '@/utils/format';
|
||||
import AssemblyViewport from './AssemblyViewport';
|
||||
import AssemblyStepSettings from './AssemblyStepSettings';
|
||||
import AssemblySceneSettings from './AssemblySceneSettings';
|
||||
import AssemblyReference from './AssemblyReference';
|
||||
import AssemblyLibraryPanel from './AssemblyLibraryPanel';
|
||||
import './assembly-editor.css';
|
||||
|
||||
const sides: { value: EntrySide; label: string }[] = [
|
||||
{ value: 'x+', label: 'X 正侧 → 原位' }, { value: 'x-', label: 'X 负侧 → 原位' },
|
||||
{ value: 'y+', label: 'Y 正侧 → 原位' }, { value: 'y-', label: 'Y 负侧 → 原位' },
|
||||
{ value: 'z+', label: 'Z 正侧 → 原位' }, { value: 'z-', label: 'Z 负侧 → 原位' },
|
||||
];
|
||||
export default function AssemblyEditor({ initial, onSave, onClose, saveHint = '保存后自动生成步骤数据。上传、检查并发布后,前台才会更新。' }: {
|
||||
export default function AssemblyEditor({ initial, onSave, onClose, saveHint = '保存后自动生成步骤 JSON。' }: {
|
||||
saveHint?: string; initial: AssemblySession; onSave: (session: AssemblySession) => void; onClose: () => void;
|
||||
}) {
|
||||
const { message, modal } = App.useApp();
|
||||
const [history, setHistory] = useState<{ past: Assembly[]; current: Assembly; future: Assembly[] }>({ past: [], current: copyAssembly(initial.assembly), future: [] });
|
||||
const assembly = history.current;
|
||||
const [selected, setSelected] = useState<string[]>([]), [search, setSearch] = useState('');
|
||||
const [side, setSide] = useState<EntrySide>('y+'), [distance, setDistance] = useState<number | null>(80), [label, setLabel] = useState('');
|
||||
const [groupName, setGroupName] = useState(''), [activeStep, setActiveStep] = useState<string | null>(null);
|
||||
const [preview, setPreview] = useState<number | null>(null), [replay, setReplay] = useState(0), [fit, setFit] = useState(0);
|
||||
const [selectionPreview, setSelectionPreview] = useState(false), [playing, setPlaying] = useState(false);
|
||||
const [tool, setTool] = useState<'select' | 'translate' | 'rotate'>('select'), [referenceVisible, setReferenceVisible] = useState(false);
|
||||
const [libraryOpen, setLibraryOpen] = useState(false), [libraryIds, setLibraryIds] = useState<string[]>([]);
|
||||
const dragging = useRef<string | null>(null), changed = useRef(false);
|
||||
const copiedOffsets = useRef(new Map<string, AssemblyPart['installOffset'][]>());
|
||||
const problems = useMemo(() => assemblyProblems(assembly), [assembly]);
|
||||
const assigned = new Set(assembly.steps.flatMap((s) => s.parts));
|
||||
const filtered = assembly.parts.filter((p) => p.name.toLowerCase().includes(search.toLowerCase()));
|
||||
const selectedPart = selected.length === 1 ? assembly.parts.find((p) => p.id === selected[0]) : null;
|
||||
const currentStep = assembly.steps.find((s) => s.id === activeStep);
|
||||
const available = initial.sources.filter((s) => s.asset.type === 'part-glb' && !assembly.parts.some((p) => p.assetId === s.asset.assetId));
|
||||
const previewAssembly = useMemo(() => !selectionPreview ? assembly : {
|
||||
...assembly,
|
||||
parts: assembly.parts.map((p) => selected.includes(p.id) && distance !== null && distance > 0 ? { ...p, installOffset: entryOffset(side, distance) } : p),
|
||||
steps: [{ id: 'preview-base', label: '已安装零件', parts: assembly.parts.filter((p) => !selected.includes(p.id)).map((p) => p.id) }, { id: 'preview-selection', label: '所选零件进入预览', parts: selected }],
|
||||
}, [assembly, selectionPreview, selected, side, distance]);
|
||||
const finalAssembly = selectionPreview ? { ...assembly, parts: previewAssembly.parts } : assembly;
|
||||
useEffect(() => { const ids = new Set(assembly.parts.map((p) => p.id)); setSelected((old) => old.every((id) => ids.has(id)) ? old : old.filter((id) => ids.has(id))); }, [assembly.parts]);
|
||||
useEffect(() => {
|
||||
if (!playing) return;
|
||||
const timer = setTimeout(() => {
|
||||
if (preview === null || preview >= assembly.steps.length - 1) setPlaying(false);
|
||||
else { setPreview(preview + 1); setReplay((n) => n + 1); }
|
||||
}, 1200);
|
||||
return () => clearTimeout(timer);
|
||||
}, [playing, preview, assembly.steps.length]);
|
||||
|
||||
const commit = (update: (draft: Assembly) => void) => {
|
||||
setPlaying(false);
|
||||
changed.current = true;
|
||||
setHistory((h) => { const next = copyAssembly(h.current); update(next); return { past: [...h.past.slice(-99), h.current], current: next, future: [] }; });
|
||||
const [history, setHistory] = useState<{ past: Assembly[]; current: Assembly; future: Assembly[] }>(() => ({ past: [], current: removeRedundantSceneMarkers(simplifyAssembly(initial.assembly)), future: [] }));
|
||||
const [operation, setOperation] = useState<'steps' | 'components'>('steps');
|
||||
const [libraryId, setLibraryId] = useState<string | null>(null);
|
||||
const [libraryDialog, setLibraryDialog] = useState<{ kind: 'create' | 'rename'; parentId: string | null; id?: string } | null>(null), [libraryName, setLibraryName] = useState('');
|
||||
// 兼容正在热更新的旧编辑会话,旧分组只在本地整理,不自动上传。
|
||||
const document = useMemo(() => simplifyAssembly(history.current), [history.current]);
|
||||
const libraryMode = operation === 'components', libraryComponent = libraryComponents(document).find(c => c.id === libraryId);
|
||||
const assembly = useMemo(() => libraryMode ? libraryComponentAssembly(document, libraryComponent?.id ?? null) : document, [document, libraryMode, libraryComponent?.id]);
|
||||
const latestAssembly = useRef(assembly); latestAssembly.current = assembly;
|
||||
const baseCatalog = initial.catalog ?? initial.assembly.parts;
|
||||
const catalog = useMemo(() => baseCatalog.filter(p => !assembly.tools?.some(t => t.assetId === p.assetId)), [baseCatalog, assembly.tools]);
|
||||
const [search, setSearch] = useState(''), [tab, setTab] = useState('choose'), [partFilter, setPartFilter] = useState('all');
|
||||
const [cursor, setCursor] = useState(-1), [replay, setReplay] = useState(0), [fit, setFit] = useState(0), [whole, setWhole] = useState(false);
|
||||
const [playing, setPlaying] = useState(false), playUntil = useRef(-1);
|
||||
const [motionPaused, setMotionPaused] = useState(false), [toolPending, setToolPending] = useState(false);
|
||||
const [focusPartId, setFocusPartId] = useState<string>();
|
||||
const changed = useRef(false), dragging = useRef<string>();
|
||||
const installed = installedParts(assembly);
|
||||
const stages = useMemo(() => assemblyStages(assembly).map(s => libraryMode ? { ...s, scope: libraryComponent?.name ?? '组件工作区' } : s), [assembly, libraryMode, libraryComponent?.name]);
|
||||
const stage = stages[cursor], currentStepId = stage?.ref.kind === 'step' ? stage.ref.id : null;
|
||||
const filtered = catalog.filter(p => (partFilter === 'all' || installed.has(p.id) === (partFilter === 'selected'))
|
||||
&& `${p.name} ${initial.sources.find(s => s.asset.assetId === p.assetId)?.asset.relativePath ?? ''}`.toLowerCase().includes(search.trim().toLowerCase()));
|
||||
const saveProblem = useMemo(() => {
|
||||
if (toolPending) return '请完成当前工具配置后再保存。';
|
||||
if (!document.steps.length && !libraryComponents(document).length) return '先创建组件,或直接选择零件开始编排。';
|
||||
try { workflowForSave(document); return ''; } catch (cause) { return errorText(cause); }
|
||||
}, [document, toolPending]);
|
||||
const renderAssembly = useMemo(() => ({ ...assembly, parts: catalog.map(p => assembly.parts.find(v => v.id === p.id) ?? p) }), [assembly, catalog]);
|
||||
const commitDocument = (next: Assembly) => {
|
||||
if (next.sceneSequence) next.sceneSequence = assemblyStages(next).map(s => structuredClone(s.ref));
|
||||
changed.current = true; setPlaying(false); setMotionPaused(false);
|
||||
setHistory(h => ({ past: [...h.past.slice(-49), h.current], current: next, future: [] }));
|
||||
};
|
||||
const fullView = () => { setPlaying(false); setSelectionPreview(false); setPreview(null); };
|
||||
const undo = () => { fullView(); setHistory((h) => !h.past.length ? h : { past: h.past.slice(0, -1), current: h.past[h.past.length - 1], future: [h.current, ...h.future] }); };
|
||||
const redo = () => { fullView(); setHistory((h) => !h.future.length ? h : { past: [...h.past, h.current], current: h.future[0], future: h.future.slice(1) }); };
|
||||
const pick = (id: string, additive = true) => { fullView(); setSelected((old) => additive ? old.includes(id) ? old.filter((v) => v !== id) : [...old, id] : [id]); };
|
||||
const validOffset = () => {
|
||||
if (distance === null || !Number.isFinite(distance) || distance <= 0) { message.warning('请填写大于 0 的进入距离(毫米)'); return null; }
|
||||
return entryOffset(side, distance);
|
||||
const commit = (next: Assembly) => {
|
||||
const full = libraryMode ? editLibraryComponent(document, libraryId!, next) : next;
|
||||
commitDocument(full); latestAssembly.current = next;
|
||||
};
|
||||
const addStep = () => {
|
||||
if (!selected.length) { message.info('先点击模型或勾选左侧零件,可以一次选择多个。'); return; }
|
||||
if (selected.some((id) => assigned.has(id))) { message.warning('所选零件已有步骤。请先选“尚未安排”,或使用“替换此步零件”重新安排。'); return; }
|
||||
const offset = validOffset(); if (!offset) return;
|
||||
const id = newEditorId('step');
|
||||
commit((a) => {
|
||||
a.steps.push({ id, label: label.trim() || `安装步骤 ${a.steps.length + 1}`, parts: [...selected] });
|
||||
a.parts.forEach((p) => { if (selected.includes(p.id)) p.installOffset = [...offset]; });
|
||||
});
|
||||
setActiveStep(id); setSelectionPreview(false); setPreview(assembly.steps.length); setReplay((n) => n + 1); setLabel(''); setTool('select');
|
||||
const update = (fn: (draft: Assembly) => void) => { const next = copyAssembly(latestAssembly.current); fn(next); commit(next); };
|
||||
const navigate = (index: number) => { setPlaying(false); setMotionPaused(false); setCursor(Math.max(-1, Math.min(index, stages.length - 1))); setReplay(n => n + 1); };
|
||||
useEffect(() => { if (cursor >= stages.length) setCursor(stages.length - 1); }, [stages.length, cursor]);
|
||||
const previewComplete = (completedCursor: number, completedReplay: number) => {
|
||||
if (!playing || completedCursor !== cursor || completedReplay !== replay) return;
|
||||
if (cursor >= playUntil.current || cursor >= stages.length - 1) setPlaying(false);
|
||||
else { setCursor(i => i + 1); setReplay(n => n + 1); }
|
||||
};
|
||||
const selectStep = (id: string) => {
|
||||
const index = assembly.steps.findIndex((s) => s.id === id), step = assembly.steps[index]; if (!step) return;
|
||||
setPlaying(false); setSelectionPreview(false);
|
||||
setActiveStep(id); setSelected([...step.parts]); setPreview(index); setReplay((n) => n + 1); setTool('select');
|
||||
const offset = assembly.parts.find((p) => p.id === step.parts[0])?.installOffset;
|
||||
if (offset && offset.filter((v) => v !== 0).length === 1) {
|
||||
const axis = offset.findIndex((v) => v !== 0); setSide(`${['x', 'y', 'z'][axis]}${offset[axis] < 0 ? '-' : '+'}` as EntrySide); setDistance(Math.abs(offset[axis]) * 1000);
|
||||
}
|
||||
const play = (until: number) => {
|
||||
if (!stages.length) return;
|
||||
if (playing) { setPlaying(false); setMotionPaused(true); return; }
|
||||
if (motionPaused) { setMotionPaused(false); setPlaying(true); return; }
|
||||
setMotionPaused(false); playUntil.current = until; setCursor(0); setReplay(n => n + 1); setPlaying(true);
|
||||
};
|
||||
const pickPart = (part: AssemblyPart) => {
|
||||
try {
|
||||
if (toolPending) throw new Error('请先完成当前工具配置。');
|
||||
if (libraryMode && !libraryComponent) throw new Error('请先创建或选择要编辑的组件。');
|
||||
setFocusPartId(part.id);
|
||||
const existing = assembly.steps.find(s => s.parts.includes(part.id));
|
||||
if (existing) { navigate(stages.findIndex(s => s.ref.id === existing.id)); return; }
|
||||
const owner = libraryOwner(document, part.id);
|
||||
if (libraryMode && owner && owner.id !== libraryId) throw new Error(`零件已属于“${libraryComponentPath(document, owner.id)}”,不能重复归属。请选择子组件,或编辑原组件。`);
|
||||
if (libraryMode && !owner && document.steps.some(s => !s.componentId && s.parts.includes(part.id))) throw new Error('这个零件已在总装中,请先从总装移除再加入组件。');
|
||||
if (initial.unplaced?.includes(part.id)) throw new Error('这个零件未能与整机位置唯一匹配,请先核对模型。');
|
||||
const next = installPart(assembly, part);
|
||||
// 新选择始终追加到时间线末尾,继承末尾进度;回看旧步骤不改变追加基准。
|
||||
commit(next); setCursor(next.steps.length - 1); setReplay(n => n + 1);
|
||||
} catch (cause) { message.warning(errorText(cause)); }
|
||||
};
|
||||
const removeStep = (id: string) => {
|
||||
try { if (toolPending) throw new Error('请先完成当前工具配置。'); commit(removeWorkflowStep(assembly, id)); setCursor(-1); }
|
||||
catch (cause) { message.warning(errorText(cause)); }
|
||||
};
|
||||
const unpickPart = (part: AssemblyPart) => {
|
||||
try {
|
||||
if (toolPending) throw new Error('请先完成当前工具配置。');
|
||||
if (assembly.steps.some(s => s.componentId && s.parts.includes(part.id))) throw new Error('这个零件随组件选中,取消组件选择即可整体移除;单独修改请编辑原组件。');
|
||||
const next = removeWorkflowPart(assembly, part.id); if (next === assembly) return;
|
||||
commit(next); setCursor(Math.min(cursor, next.steps.length - 1)); setReplay(n => n + 1);
|
||||
} catch (cause) { message.warning(errorText(cause)); }
|
||||
};
|
||||
const changeScene = (mode: 'independent' | 'continue' | 'inherit', base?: AssemblyStageRef) => {
|
||||
if (!currentStepId) return;
|
||||
try {
|
||||
if (mode === 'inherit') update(a => { const s = a.steps.find(s => s.id === currentStepId)!; delete s.scene; delete s.sceneMarker; });
|
||||
else commit(setStepScene(assembly, currentStepId, mode, base));
|
||||
setReplay(n => n + 1); setFit(n => n + 1);
|
||||
} catch (cause) { message.warning(errorText(cause)); }
|
||||
};
|
||||
const moveStep = (id: string, to: number) => {
|
||||
commit((a) => { const index = a.steps.findIndex((s) => s.id === id); if (index < 0 || to < 0 || to >= a.steps.length) return; const [step] = a.steps.splice(index, 1); a.steps.splice(to, 0, step); });
|
||||
fullView();
|
||||
update(a => {
|
||||
const index = a.steps.findIndex(s => s.id === id); if (index < 0 || to < 0 || to >= a.steps.length) return;
|
||||
const [step] = a.steps.splice(index, 1); a.steps.splice(to, 0, step);
|
||||
if (a.sceneSequence) a.sceneSequence = a.steps.map(s => ({ kind: 'step', id: s.id }));
|
||||
}); setCursor(-1);
|
||||
};
|
||||
const copyStep = (id: string) => {
|
||||
const step = assembly.steps.find((s) => s.id === id); if (!step) return;
|
||||
const copyId = newEditorId('step');
|
||||
copiedOffsets.current.set(copyId, step.parts.map((id) => [...assembly.parts.find((p) => p.id === id)!.installOffset]));
|
||||
selectStep(id);
|
||||
commit((a) => a.steps.splice(a.steps.findIndex((s) => s.id === id) + 1, 0, { id: copyId, label: `${step.label}(副本)`, parts: [] }));
|
||||
setActiveStep(copyId); setSelected([]); fullView();
|
||||
message.info('步骤设置已复制。选择另一组零件,再点击“替换此步零件”;同一零件不会重复安装。');
|
||||
const reset = () => modal.confirm({ title: '重新编排装配流程?', content: libraryMode ? '清空当前组件的内部步骤,其他组件与总装步骤保留。' : '只清空总装步骤,已创建的组件保留。保存前不影响已上传内容。', okText: '重新编排', cancelText: '取消', onOk: () => { update(a => { a.steps = []; delete a.sceneSequence; }); setCursor(-1); setTab('choose'); } });
|
||||
const close = () => changed.current ? modal.confirm({ title: '关闭并放弃本次流程修改?', content: '已上传的原流程保持不变。', okText: '放弃修改', cancelText: '继续编辑', onOk: onClose }) : onClose();
|
||||
const undo = (redo = false) => {
|
||||
setPlaying(false); setMotionPaused(false); setCursor(-1); setFocusPartId(undefined);
|
||||
setHistory(h => redo ? !h.future.length ? h : { past: [...h.past, h.current], current: h.future[0], future: h.future.slice(1) }
|
||||
: !h.past.length ? h : { past: h.past.slice(0, -1), current: h.past[h.past.length - 1], future: [h.current, ...h.future] });
|
||||
};
|
||||
const replaceParts = () => {
|
||||
if (!currentStep || !selected.length) return;
|
||||
const copied = copiedOffsets.current.get(currentStep.id);
|
||||
const uniform = copied?.length && copied.every((offset) => offset.every((v, i) => v === copied[0][i]));
|
||||
if (copied?.length && !uniform && copied.length !== selected.length) {
|
||||
message.warning('原步骤的零件使用了不同的进入设置。请选择相同数量的零件,或修改方向和距离以统一设置。'); return;
|
||||
}
|
||||
const offset = copied?.[0] ?? validOffset(); if (!offset) return;
|
||||
commit((a) => {
|
||||
a.steps.forEach((s) => { s.parts = s.id === activeStep ? [...selected] : s.parts.filter((id) => !selected.includes(id)); });
|
||||
a.parts.forEach((p) => { if (selected.includes(p.id)) p.installOffset = [...(copied?.length && !uniform ? copied[selected.indexOf(p.id)] : offset)]; });
|
||||
});
|
||||
copiedOffsets.current.delete(currentStep.id); setSelectionPreview(false);
|
||||
setPreview(assembly.steps.findIndex((s) => s.id === activeStep)); setReplay((n) => n + 1);
|
||||
};
|
||||
const applyOffset = () => {
|
||||
const offset = validOffset(); if (!offset || !selected.length) return;
|
||||
commit((a) => a.parts.forEach((p) => { if (selected.includes(p.id)) p.installOffset = [...offset]; }));
|
||||
setSelectionPreview(true); setTool('select');
|
||||
setReplay((n) => n + 1);
|
||||
};
|
||||
const transform = (id: string, position: AssemblyPart['position'], quaternion: AssemblyPart['quaternion']) => {
|
||||
const part = assembly.parts.find((p) => p.id === id); if (!part || JSON.stringify([part.position, part.quaternion]) === JSON.stringify([position, quaternion])) return;
|
||||
commit((a) => { const p = a.parts.find((p) => p.id === id)!; p.position = position; p.quaternion = quaternion; });
|
||||
};
|
||||
const removeSelected = () => {
|
||||
commit((a) => {
|
||||
// 父件仍被子件引用时禁止移除,防止破坏父坐标系。
|
||||
a.parts = a.parts.filter((p) => !selected.includes(p.id));
|
||||
a.steps.forEach((s) => { s.parts = s.parts.filter((id) => !selected.includes(id)); });
|
||||
a.steps = a.steps.filter((s) => s.parts.length);
|
||||
a.editorGroups?.forEach((g) => { g.parts = g.parts.filter((id) => !selected.includes(id)); });
|
||||
a.editorGroups = a.editorGroups?.filter((g) => g.parts.length);
|
||||
});
|
||||
setSelected([]); fullView();
|
||||
const save = () => {
|
||||
try { if (toolPending) throw new Error('请先完成当前工具配置。'); const next = workflowForSave(document); assemblyManifest(next, initial.sources, initial.manifest); onSave({ ...initial, catalog, assembly: next }); }
|
||||
catch (cause) { message.error(errorText(cause)); }
|
||||
};
|
||||
const download = () => {
|
||||
try {
|
||||
const manifest = assemblyManifest(finalAssembly, initial.sources);
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(manifest, null, 2)], { type: 'application/json' }));
|
||||
const a = document.createElement('a'); a.href = url; a.download = 'assembly.manifest.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
if (toolPending) throw new Error('请先完成当前工具配置。');
|
||||
const json = assemblyManifest(workflowForSave(document), initial.sources, initial.manifest);
|
||||
const url = URL.createObjectURL(new Blob([JSON.stringify(json, null, 2)], { type: 'application/json' }));
|
||||
const link = window.document.createElement('a'); link.href = url; link.download = 'assembly.manifest.json'; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
} catch (cause) { message.error(errorText(cause)); }
|
||||
};
|
||||
const close = () => changed.current ? modal.confirm({ title: '关闭并放弃本次流程修改?', content: '已上传的原文件不会删除。', okText: '放弃修改', cancelText: '继续编辑', onOk: onClose }) : onClose();
|
||||
return <Modal open title={<Space><span>制作装配流程</span><Tag color="purple">可视化编辑</Tag></Space>} width="calc(100vw - 40px)" className="assembly-editor-modal" style={{ top: 20 }}
|
||||
onCancel={close} footer={<div className="assembly-editor-footer"><Typography.Text type="secondary">{saveHint}</Typography.Text><Space>
|
||||
<Button onClick={close}>取消</Button><Button type="primary" disabled={!!problems.length} onClick={() => {
|
||||
try { assemblyManifest(finalAssembly, initial.sources); onSave({ ...initial, assembly: copyAssembly(finalAssembly) }); }
|
||||
catch (cause) { message.error(errorText(cause)); }
|
||||
}}>保存装配流程</Button></Space></div>}
|
||||
>
|
||||
<div className="assembly-editor-guide"><strong>① 使用上方零件模型</strong><span>→</span><strong>② 选择一组零件</strong><span>→</span><strong>③ 设方向并添加步骤</strong><span>→</span><strong>④ 预览并保存</strong></div>
|
||||
<div className="assembly-editor-toolbar"><Space wrap>
|
||||
<Input aria-label="装配流程名称" value={assembly.title} onChange={(e) => commit((a) => { a.title = e.target.value; })} style={{ width: 230 }} />
|
||||
<Button aria-label="撤销" icon={<UndoOutlined />} disabled={!history.past.length} onClick={undo}>撤销</Button>
|
||||
<Button aria-label="重做" icon={<RedoOutlined />} disabled={!history.future.length} onClick={redo}>重做</Button>
|
||||
<Button onClick={() => { fullView(); setTool('select'); }}>查看完整组装</Button><Button onClick={() => setFit((n) => n + 1)}>适应视图</Button>
|
||||
<Button aria-label={playing ? '暂停播放' : '播放完整流程'} icon={<PlayCircleOutlined />} disabled={!assembly.steps.length || assembly.steps.some((s) => !s.parts.length)} onClick={() => { if (playing) { setPlaying(false); return; } setSelectionPreview(false); setTool('select'); setPreview(0); setReplay((n) => n + 1); setPlaying(true); }}>{playing ? '暂停播放' : '播放完整流程'}</Button>
|
||||
{initial.reference && <Checkbox checked={referenceVisible} onChange={(e) => setReferenceVisible(e.target.checked)}>显示整机参考</Checkbox>}
|
||||
</Space><Tag>{assembly.parts.length} 个零件 · {assembly.steps.length} 个步骤</Tag></div>
|
||||
<div className="assembly-editor-layout">
|
||||
<aside className="assembly-part-sidebar">
|
||||
<div className="assembly-pane-title"><strong>零件</strong><Button size="small" aria-label="从零件模型中添加" icon={<PlusOutlined />} disabled={!available.length} onClick={() => { setLibraryIds(available.map((s) => s.asset.assetId)); setLibraryOpen(true); }}>从零件模型中添加</Button></div>
|
||||
<Input.Search placeholder="搜索零件名称" aria-label="搜索零件名称" value={search} onChange={(e) => setSearch(e.target.value)} allowClear />
|
||||
<Space wrap size={4} className="assembly-part-actions"><Button size="small" onClick={() => { setSelected(filtered.map((p) => p.id)); fullView(); }}>全选结果</Button><Button size="small" onClick={() => { setSelected(assembly.parts.filter((p) => !assigned.has(p.id)).map((p) => p.id)); fullView(); }}>尚未安排</Button><Button size="small" onClick={() => { setSelected([]); fullView(); }}>清空选择</Button></Space>
|
||||
<div className="assembly-part-list">
|
||||
{!assembly.parts.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="先在上方“零件模型”选择并上传零件文件夹,再从这里选择零件。" />}
|
||||
{filtered.map((p) => <div className={`assembly-part-row ${selected.includes(p.id) ? 'is-selected' : ''}`} key={p.id}>
|
||||
<Checkbox aria-label={`选择零件 ${p.name}`} checked={selected.includes(p.id)} onChange={() => pick(p.id)} />
|
||||
<button type="button" onClick={(e) => pick(p.id, e.shiftKey || e.metaKey || e.ctrlKey)} title={p.name}>{p.name}</button><span>{assigned.has(p.id) ? `第 ${assembly.steps.findIndex((s) => s.parts.includes(p.id)) + 1} 步` : '未安排'}</span>
|
||||
</div>)}
|
||||
const clearSelection = () => { setCursor(-1); setSearch(''); setPartFilter('all'); setFocusPartId(undefined); setPlaying(false); setMotionPaused(false); };
|
||||
const selectLibrary = (id: string) => {
|
||||
if (toolPending) { message.warning('请先完成当前工具配置。'); return; }
|
||||
setOperation('components'); setLibraryId(id); clearSelection(); setTab('choose');
|
||||
setCursor(libraryComponentAssembly(document, id).steps.length - 1);
|
||||
};
|
||||
const changeOperation = (value: string | number) => {
|
||||
if (toolPending) { message.warning('请先完成当前工具配置。'); return; }
|
||||
setOperation(value as 'steps' | 'components'); clearSelection(); setTab('choose');
|
||||
};
|
||||
const openLibraryCreate = (parentId: string | null) => { setLibraryDialog({ kind: 'create', parentId }); setLibraryName(''); };
|
||||
const openLibraryRename = (id: string) => { const c = libraryComponents(document).find(c => c.id === id)!; setLibraryDialog({ kind: 'rename', parentId: c.parentId, id }); setLibraryName(c.name); };
|
||||
const confirmLibraryDialog = () => {
|
||||
if (!libraryDialog || !libraryName.trim()) return;
|
||||
try {
|
||||
if (libraryDialog.kind === 'create') { const next = createLibraryComponent(document, libraryName, libraryDialog.parentId); commitDocument(next.assembly); selectLibrary(next.componentId); }
|
||||
else {
|
||||
const next = copyAssembly(document), c = libraryComponents(next).find(c => c.id === libraryDialog.id)!;
|
||||
if (libraryComponents(next).some(v => v.id !== c.id && v.parentId === c.parentId && v.name === libraryName.trim())) throw new Error('同一级已有这个组件名称。');
|
||||
const oldName = c.name; c.name = libraryName.trim();
|
||||
for (const steps of [next.steps, ...libraryComponents(next).map(c => c.steps)]) steps.forEach(s => { if (s.componentId === c.id && s.label === `安装组件 ${oldName}`) s.label = `安装组件 ${c.name}`; });
|
||||
commitDocument(next);
|
||||
}
|
||||
setLibraryDialog(null);
|
||||
} catch (cause) { message.warning(errorText(cause)); }
|
||||
};
|
||||
const toggleComponent = (id: string, selected: boolean) => {
|
||||
if (!selected) { const step = assembly.steps.find(s => s.componentId === id); if (step) removeStep(step.id); return; }
|
||||
try {
|
||||
if (toolPending) throw new Error('请先完成当前工具配置。');
|
||||
if (libraryMode && !libraryComponent) throw new Error('请先选择要编辑的上级组件。');
|
||||
const next = insertLibraryComponent(assembly, document, id, libraryMode ? libraryId : null);
|
||||
commit(next); setCursor(next.steps.length - 1); setReplay(n => n + 1);
|
||||
} catch (cause) { message.warning(errorText(cause)); }
|
||||
};
|
||||
const deleteComponent = (id: string) => { try { commitDocument(deleteLibraryComponent(document, id)); if (id === libraryId) { setLibraryId(null); clearSelection(); } } catch (cause) { message.warning(errorText(cause)); } };
|
||||
const choices = <div className="assembly-choice-panel"><Input.Search aria-label="搜索组件或零件" placeholder="搜索组件、零件名称或路径" value={search} onChange={e => setSearch(e.target.value)} allowClear />
|
||||
<AssemblyLibraryPanel document={document} current={assembly} activeId={libraryId} editing={libraryMode} search={search} onSelect={selectLibrary} onCreate={openLibraryCreate} onRename={openLibraryRename} onDelete={deleteComponent} onToggle={toggleComponent} />
|
||||
<div className="assembly-choice-section-title"><strong>零件</strong><span>已选 {installed.size} / {catalog.length}</span></div>
|
||||
<Segmented className="assembly-part-filter" block aria-label="零件筛选" value={partFilter} onChange={value => setPartFilter(String(value))} options={[{ label: '全部', value: 'all' }, { label: '已选中', value: 'selected' }, { label: '未选中', value: 'unselected' }]} />
|
||||
<div className="assembly-list-caption"><span>左键选中 · 右键移除</span><span>显示 {filtered.length}</span></div>
|
||||
<div className="assembly-part-list">{!filtered.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={search.trim() ? '没有匹配的零件' : partFilter === 'selected' ? '还没有选中零件' : partFilter === 'unselected' ? '全部零件都已选中' : '没有可用的零件'} />}{filtered.map(p => {
|
||||
const index = stages.findIndex(s => s.entering.includes(p.id)), owner = libraryOwner(document, p.id), step = assembly.steps.find(s => s.parts.includes(p.id));
|
||||
const reserved = libraryMode && !!owner && owner.id !== libraryId && !installed.has(p.id);
|
||||
return <button key={p.id} type="button" className={`assembly-part-row ${installed.has(p.id) ? 'is-installed' : ''} ${stage?.entering.includes(p.id) ? 'is-active' : ''} ${reserved ? 'is-reserved' : ''}`} aria-label={`${installed.has(p.id) ? '查看' : '安装'}零件 ${p.name}`} aria-pressed={installed.has(p.id)} title={step?.componentId ? '随组件选中,取消组件可整体移除' : p.name} onClick={() => pickPart(p)} onContextMenu={e => { e.preventDefault(); unpickPart(p); }} onKeyDown={e => { if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); unpickPart(p); } }}>
|
||||
<span className="assembly-part-state">{installed.has(p.id) ? '✓' : '+'}</span><span className="assembly-part-name">{p.name}<small>{step?.componentId ? `随组件选中 · 第 ${index + 1} 步` : reserved ? `归属:${libraryComponentPath(document, owner!.id)}` : initial.unplaced?.includes(p.id) ? '未匹配整机位置' : installed.has(p.id) ? `第 ${index + 1} 步 · 右键移除` : '点击安装'}</small></span>
|
||||
</button>;
|
||||
})}</div></div>;
|
||||
const stepList = <><div className="assembly-list-caption"><span>点击查看 · 拖动排序 · 只在分段处标记</span><Button size="small" type="text" onClick={reset}>重新编排</Button></div><ol className="assembly-step-list">{!stages.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="从组件与零件中选择,自动记录顺序" />}{stages.map((item, i) => {
|
||||
const s = assembly.steps.find(s => s.id === item.ref.id)!;
|
||||
return <li key={item.id} className={cursor === i ? 'is-active' : ''} draggable onDragStart={e => { dragging.current = s.id; e.dataTransfer.setData('text/plain', s.id); }} onDragEnd={() => { dragging.current = undefined; }} onDragOver={e => e.preventDefault()} onDrop={e => { e.preventDefault(); if (dragging.current) moveStep(dragging.current, i); dragging.current = undefined; }}>
|
||||
<HolderOutlined /><button type="button" className="assembly-step-label" aria-label={`查看第 ${i + 1} 步 ${s.label}`} onClick={() => { setFocusPartId(item.entering[0]); navigate(i); }}><b>{i + 1}</b><span>{s.label}{s.componentId && <small>组件 · {s.parts.length} 个零件</small>}{s.scene && <small className="assembly-segment-marker">{s.scene.mode === 'independent' ? '新拼装' : `继续拼装 · 接第 ${stages.findIndex(v => v.ref.kind === item.base?.kind && v.ref.id === item.base.id) + 1} 步`}</small>}</span></button>
|
||||
<Space size={0}><Button type="text" size="small" aria-label={`上移第 ${i + 1} 步`} icon={<ArrowUpOutlined />} disabled={i === 0} onClick={() => moveStep(s.id, i - 1)} /><Button type="text" size="small" aria-label={`下移第 ${i + 1} 步`} icon={<ArrowDownOutlined />} disabled={i === stages.length - 1} onClick={() => moveStep(s.id, i + 1)} /><Popconfirm title="移除此步骤?组件与原始零件保留。" onConfirm={() => removeStep(s.id)}><Button type="text" size="small" danger aria-label={`删除第 ${i + 1} 步`} icon={<DeleteOutlined />} /></Popconfirm></Space>
|
||||
</li>;
|
||||
})}</ol></>;
|
||||
return <ConfigProvider theme={{ inherit: false, algorithm: theme.darkAlgorithm, token: { colorPrimary: '#c5ff59', colorBgBase: '#14181d', colorTextBase: '#eef1f4', colorText: '#eef1f4', colorTextSecondary: '#a4afbd', colorTextTertiary: '#7f8d9e', borderRadius: 9 } }}>
|
||||
<Modal open title={<div className="assembly-modal-title"><span>装配流程</span><Tag>可视化编排</Tag></div>} width="min(1840px, calc(100vw - 32px))" className="assembly-editor-modal" style={{ top: 16 }} onCancel={close}
|
||||
footer={<div className="assembly-editor-footer"><Typography.Text type="secondary">{saveProblem || (libraryMode ? '组件内部顺序独立保存,不会自动加入总装。' : saveHint)}</Typography.Text><Space><Button onClick={close}>取消</Button><Tooltip title={saveProblem}><Button type="primary" disabled={!!saveProblem} onClick={save}>{libraryMode ? '保存组件库' : '保存装配流程'}</Button></Tooltip></Space></div>}>
|
||||
<div className="assembly-editor-toolbar"><Input aria-label="装配流程名称" value={document.title} onChange={e => { const next = copyAssembly(document); next.title = e.target.value; commitDocument(next); }} variant="borderless" /><div className="assembly-toolbar-actions"><Button aria-label="创建组件" icon={<PlusOutlined />} disabled={toolPending} onClick={() => openLibraryCreate(null)}>创建组件</Button><Segmented className="assembly-operation-select" aria-label="操作内容" value={operation} onChange={changeOperation} options={[{ label: '组件制作', value: 'components' }, { label: '步骤编排', value: 'steps' }]} /><Button className="assembly-history-button" aria-label="撤销" icon={<UndoOutlined />} disabled={!history.past.length} onClick={() => undo()}>撤销</Button><Button className="assembly-history-button" aria-label="重做" icon={<RedoOutlined />} disabled={!history.future.length} onClick={() => undo(true)}>重做</Button></div></div>
|
||||
<div className={`assembly-operation-context ${libraryMode ? 'is-library' : ''}`}><div><strong>{libraryMode ? '制作组件' : '步骤编排'}</strong><span>{libraryMode ? libraryComponent ? `${libraryComponentPath(document, libraryComponent.id)} · 总装 ${document.steps.length} 步保持独立` : '先创建或选择一个组件,内部可以选择零件和子组件。' : '组件与零件可以混合选择;默认接着上一步安装,只在分段处设置新拼装或继续拼装。'}</span></div></div>
|
||||
<div className="assembly-editor-layout"><main className="assembly-editor-center"><div className="assembly-comparison"><AssemblyReference assembly={renderAssembly} sources={initial.sources} unplaced={initial.unplaced} resetToken={whole} />
|
||||
<section className="assembly-stage" aria-label="当前装配视窗"><header className="assembly-stage-heading"><div><strong>{libraryMode ? libraryComponent?.name ?? '组件工作区' : '当前装配'}</strong><small>{stage ? `第 ${cursor + 1} 步 · ${stage.parts.length} 个零件` : '从空场景开始'}</small></div><span className="assembly-working-indicator">{playing ? '正在预览' : libraryMode ? '组件内部' : '按选择顺序安装'}</span></header>
|
||||
<AssemblyViewport assembly={renderAssembly} sources={initial.sources} selected={stage?.entering ?? []} preview={cursor} paused={motionPaused} onPreviewComplete={previewComplete} visibleParts={stage?.parts ?? []} enteringParts={stage?.entering ?? []} stageOffset={stage?.offset} fitParts={libraryMode && installed.size ? [...installed] : stage?.parts} focusKey={libraryMode ? libraryComponent?.id : stage?.entering.some(id => assembly.parts.find(p => p.id === id)?.installation) ? stage.id : undefined} replay={replay} referenceVisible={false} tool="select" fit={fit} onPick={id => { const p = catalog.find(p => p.id === id); if (p) pickPart(p); }} onTransform={() => {}} />
|
||||
{!stage && <div className="assembly-empty-canvas"><span>{libraryMode && !libraryComponent ? '先创建或选择组件' : '从第一个选择开始'}</span><small>{libraryMode ? '组件内部可以继续选择零件和子组件' : '在右侧选择组件或零件,自动记录安装顺序'}</small>{!!initial.assembly.steps.length && !changed.current && !libraryMode && <Button className="assembly-start-over" onClick={reset}>重新编排新流程</Button>}</div>}<footer className="assembly-view-caption">绿色边框标记本步新增零件。</footer>
|
||||
</section></div>
|
||||
<div className="assembly-playback"><div className="assembly-progress-line"><Button shape="circle" aria-label="上一步" icon={<ArrowLeftOutlined />} disabled={cursor < 0} onClick={() => navigate(cursor - 1)} /><div className="assembly-progress-caption" aria-live="polite"><small>{playing || motionPaused ? `从第 1 步预览至第 ${playUntil.current + 1} 步${motionPaused ? ' · 已暂停' : ''}` : libraryMode ? libraryComponent?.name ?? '组件工作区' : '总装进度'}</small><span>{`${cursor + 1} / ${stages.length} · ${stage?.label ?? '尚未开始'}`}</span></div><Button shape="circle" aria-label="下一步" icon={<ArrowRightOutlined />} disabled={cursor >= stages.length - 1} onClick={() => navigate(cursor + 1)} /></div>
|
||||
<Slider aria-label="装配预览进度" min={0} max={Math.max(1, stages.length)} value={cursor + 1} onChange={value => navigate(value - 1)} tooltip={{ formatter: value => `${value} / ${stages.length}` }} disabled={!stages.length} />
|
||||
<div className="assembly-preview-actions"><Button onClick={() => setWhole(v => !v)}>恢复整机参考</Button><Button aria-label={playing ? '暂停预览' : motionPaused ? '继续预览' : cursor >= 0 ? '预览到此步' : '播放全部步骤'} icon={playing ? <PauseOutlined /> : <PlayCircleOutlined />} disabled={!stages.length} onClick={() => play(cursor >= 0 ? cursor : stages.length - 1)}>{playing ? '暂停预览' : motionPaused ? '继续预览' : cursor >= 0 ? '预览到此步' : '播放全部步骤'}</Button><Button disabled={!stage} onClick={() => { setPlaying(false); setMotionPaused(false); setReplay(n => n + 1); }}>重播本步</Button><Button onClick={() => setFit(n => n + 1)}>重置视角</Button></div>
|
||||
</div>
|
||||
<div className="assembly-groups"><strong>零件分组</strong><Typography.Paragraph type="secondary">选中多个零件后命名,例如左腿、右腿。</Typography.Paragraph><Space.Compact style={{ width: '100%' }}><Input aria-label="零件分组名称" placeholder="例如:左腿" value={groupName} onChange={(e) => setGroupName(e.target.value)} /><Button disabled={!selected.length || !groupName.trim()} onClick={() => { commit((a) => { (a.editorGroups ??= []).push({ id: newEditorId('group'), name: groupName.trim(), parts: [...selected] }); }); setGroupName(''); }}>存为组</Button></Space.Compact>
|
||||
<div className="assembly-group-tags">{assembly.editorGroups?.map((g) => <Tag key={g.id} closable onClose={() => commit((a) => { a.editorGroups = a.editorGroups?.filter((v) => v.id !== g.id); })}><button type="button" onClick={() => { setSelected(g.parts.filter((id) => assembly.parts.some((p) => p.id === id))); fullView(); }}>{g.name} · {g.parts.length}</button></Tag>)}</div>
|
||||
</div>
|
||||
</aside>
|
||||
<main className="assembly-editor-center">
|
||||
<AssemblyViewport assembly={previewAssembly} sources={initial.sources} reference={initial.reference} selected={selected} preview={selectionPreview ? 1 : preview} replay={replay} referenceVisible={referenceVisible} tool={tool} fit={fit} onPick={pick} onTransform={transform} />
|
||||
<div className="assembly-preview-bar"><Tag color={preview === null && !selectionPreview ? 'default' : 'purple'}>{selectionPreview ? '所选零件进入预览' : preview === null ? '完整组装 · 可选择零件' : `预览第 ${preview + 1} 步:${assembly.steps[preview]?.label ?? ''}`}</Tag><Button icon={<PlayCircleOutlined />} disabled={preview === null && !selectionPreview} onClick={() => setReplay((n) => n + 1)}>重播此步</Button></div>
|
||||
<div className="assembly-step-settings"><div className="assembly-pane-title"><strong>为选中的 {selected.length} 个零件设置进入方式</strong></div>
|
||||
<Space wrap><Select aria-label="进入方向" value={side} onChange={(value) => { if (activeStep) copiedOffsets.current.delete(activeStep); setSide(value); setPlaying(false); setSelectionPreview(!!selected.length); setTool('select'); }} options={sides} style={{ width: 165 }} /><InputNumber aria-label="进入距离(毫米)" value={distance} onChange={(value) => { if (activeStep) copiedOffsets.current.delete(activeStep); setDistance(value); setPlaying(false); setSelectionPreview(!!selected.length && value !== null && value > 0); setTool('select'); }} addonAfter="毫米" min={0} style={{ width: 175 }} /><Button disabled={!selected.length} onClick={applyOffset}>应用到所选零件并预览</Button></Space>
|
||||
{activeStep && copiedOffsets.current.has(activeStep) && <Typography.Paragraph type="secondary" style={{ margin: '8px 0 0' }}>副本沿用原步骤的进入设置;选择零件后点击“替换此步零件”。修改方向或距离可统一覆盖。</Typography.Paragraph>}
|
||||
<Space.Compact style={{ width: '100%', marginTop: 10 }}><Input placeholder="步骤名称,例如:安装左腿" aria-label="新步骤名称" value={label} onChange={(e) => setLabel(e.target.value)} onPressEnter={addStep} /><Button type="primary" aria-label="添加步骤" icon={<PlusOutlined />} disabled={!selected.length} onClick={addStep}>添加步骤</Button></Space.Compact>
|
||||
<Typography.Paragraph type="secondary" style={{ margin: '8px 0 0' }}>距离使用毫米,保存时自动换算为米。一个步骤可同时安装多个零件。进入方向按零件父坐标系计算,最终位置与材质保持不变。</Typography.Paragraph>
|
||||
</div>
|
||||
<Collapse size="small" items={[{ key: 'alignment', label: '调整零件最终位置(模型未对齐时使用)', children: <Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Typography.Text type="secondary">GLB 中已有的坐标和方向会保留;若导出时每个零件都回到了原点,需要手动对齐。选择单个零件后拖动模型上的箭头或圆环。</Typography.Text>
|
||||
<Segmented aria-label="对齐工具" value={tool} options={[{ label: '选择', value: 'select' }, { label: '移动', value: 'translate' }, { label: '旋转', value: 'rotate' }]} onChange={(value) => { fullView(); setTool(value as typeof tool); }} disabled={!selectedPart} />
|
||||
{selectedPart && <><Input aria-label="零件显示名称" value={selectedPart.name} onChange={(e) => commit((a) => { a.parts.find((p) => p.id === selectedPart.id)!.name = e.target.value; })} />
|
||||
<Space wrap>{(['X', 'Y', 'Z'] as const).map((axis, i) => <InputNumber key={axis} aria-label={`最终位置 ${axis}(毫米)`} addonBefore={axis} addonAfter="毫米" value={selectedPart.position[i] * 1000} style={{ width: 170 }} onChange={(value) => { if (value !== null && Number.isFinite(value)) { fullView(); commit((a) => { a.parts.find((p) => p.id === selectedPart.id)!.position[i] = value / 1000; }); } }} />)}</Space></>}
|
||||
<Popconfirm title="从流程中移除所选零件?原文件仍会保留。" onConfirm={removeSelected}><Button danger icon={<DeleteOutlined />} disabled={!selected.length || assembly.parts.some((p) => p.parentId && selected.includes(p.parentId) && !selected.includes(p.id))}>移除所选零件</Button></Popconfirm>
|
||||
</Space> }]} />
|
||||
</main>
|
||||
<aside className="assembly-step-sidebar"><div className="assembly-pane-title"><strong>装配顺序</strong><Typography.Text type="secondary">拖动可排序</Typography.Text></div>
|
||||
{!assembly.steps.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="选择零件,设置进入方向后添加第一步" />}
|
||||
<ol className="assembly-step-list">{assembly.steps.map((step, i) => <li key={step.id} className={step.id === activeStep ? 'is-active' : ''} draggable
|
||||
onDragStart={(e) => { dragging.current = step.id; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', step.id); }} onDragEnd={() => { dragging.current = null; }} onDragOver={(e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; }} onDrop={(e) => { e.preventDefault(); if (dragging.current && dragging.current !== step.id) moveStep(dragging.current, i); dragging.current = null; }}>
|
||||
<div className="assembly-step-heading"><HolderOutlined /><button type="button" onClick={() => selectStep(step.id)}><b>{i + 1}</b><span>{step.label}</span></button></div>
|
||||
<div className="assembly-step-summary">{step.parts.length ? `${step.parts.length} 个零件` : '请选择零件填入此步'}</div>
|
||||
{activeStep === step.id && <Input aria-label="当前步骤名称" value={step.label} onChange={(e) => commit((a) => { a.steps.find((s) => s.id === step.id)!.label = e.target.value; })} />}
|
||||
<Space size={2} wrap><Tooltip title="上移"><Button size="small" aria-label={`上移第 ${i + 1} 步`} icon={<ArrowUpOutlined />} disabled={i === 0} onClick={() => moveStep(step.id, i - 1)} /></Tooltip><Tooltip title="下移"><Button size="small" aria-label={`下移第 ${i + 1} 步`} icon={<ArrowDownOutlined />} disabled={i === assembly.steps.length - 1} onClick={() => moveStep(step.id, i + 1)} /></Tooltip><Tooltip title="复制名称和进入设置,另选零件"><Button size="small" aria-label={`复制第 ${i + 1} 步设置`} icon={<CopyOutlined />} onClick={() => copyStep(step.id)} /></Tooltip><Popconfirm title="删除此步骤?其中的零件会回到未安排。" onConfirm={() => { commit((a) => { a.steps = a.steps.filter((s) => s.id !== step.id); }); fullView(); setActiveStep(null); }}><Button size="small" danger aria-label={`删除第 ${i + 1} 步`} icon={<DeleteOutlined />} /></Popconfirm></Space>
|
||||
{activeStep === step.id && <Button block size="small" disabled={!selected.length} onClick={replaceParts}>替换此步零件</Button>}
|
||||
</li>)}</ol>
|
||||
{!!problems.length && <Alert type="info" showIcon message="保存前还需要完成" description={<ul className="assembly-problems">{problems.map((p) => <li key={p}>{p}</li>)}</ul>} />}
|
||||
<Collapse size="small" items={[{ key: 'export', label: '高级:导出步骤 JSON', children: <><Typography.Paragraph type="secondary">系统已自动填写零件编号、变换和文件校验值。一般直接保存即可。</Typography.Paragraph><Button disabled={!!problems.length} onClick={download}>下载系统生成的 JSON</Button></> }]} />
|
||||
</aside>
|
||||
</div>
|
||||
<Modal open={libraryOpen} title="从零件模型中添加" okText="添加到装配流程" cancelText="取消" onCancel={() => setLibraryOpen(false)} okButtonProps={{ disabled: !libraryIds.length }} onOk={() => { commit((a) => { initial.sources.filter((s) => libraryIds.includes(s.asset.assetId)).forEach((s) => a.parts.push(sourcePart(s.asset))); }); setLibraryOpen(false); fullView(); }}>
|
||||
<Typography.Paragraph type="secondary">这里只列出上方“零件模型”中尚未加入本流程的零件,无需再次上传文件。</Typography.Paragraph>
|
||||
<Checkbox.Group value={libraryIds} onChange={(values) => setLibraryIds(values as string[])}><Space direction="vertical">{available.map((s) => <Checkbox key={s.asset.assetId} value={s.asset.assetId}>{s.asset.relativePath}</Checkbox>)}</Space></Checkbox.Group>
|
||||
<AssemblyStepSettings assembly={assembly} stepId={currentStepId} stageNumber={stage ? cursor + 1 : undefined} sceneControls={<AssemblySceneSettings stages={stages} cursor={cursor} onChange={changeScene} />} focusPartId={focusPartId} sources={initial.sources} onChange={update} onPreview={() => { setMotionPaused(false); setReplay(n => n + 1); }} onPendingChange={setToolPending} />
|
||||
</main><aside className="assembly-workbench">
|
||||
{libraryMode && <div className="assembly-library-context"><label>当前组件</label><Select aria-label="当前制作组件" showSearch optionFilterProp="label" placeholder="创建组件或选择已有组件" value={libraryComponent?.id} onChange={selectLibrary} options={libraryComponents(document).map(c => ({ value: c.id, label: libraryComponentPath(document, c.id) }))} /></div>}
|
||||
<Tabs activeKey={tab} onChange={setTab} items={[{ key: 'choose', label: '组件与零件', children: choices }, { key: 'steps', label: `${libraryMode ? '内部步骤' : '步骤'} ${stages.length}`, children: stepList }]} />
|
||||
<Collapse ghost size="small" className="assembly-more" items={[{ key: 'more', label: '更多操作', children: <Space direction="vertical"><Button onClick={reset}>{libraryMode ? '清空当前组件步骤' : '重新编排流程'}</Button><Button disabled={!!saveProblem} onClick={download}>下载系统生成的 JSON</Button></Space> }]} />
|
||||
</aside></div>
|
||||
</Modal>
|
||||
</Modal>;
|
||||
<Modal open={!!libraryDialog} title={libraryDialog?.kind === 'rename' ? '重命名组件' : libraryDialog?.parentId ? '创建子组件' : '创建组件'} okText={libraryDialog?.kind === 'rename' ? '保存名称' : '创建并制作'} cancelText="取消" onCancel={() => setLibraryDialog(null)} onOk={confirmLibraryDialog} okButtonProps={{ disabled: !libraryName.trim() }}>
|
||||
<Typography.Paragraph type="secondary">{libraryDialog?.parentId ? `上级组件:${libraryComponentPath(document, libraryDialog.parentId)}` : '可先创建空组件,再选择成员零件。'} 创建组件不会自动增加总装步骤。</Typography.Paragraph><Input aria-label="独立组件名称" placeholder="例如:躯干、躯干1" value={libraryName} onChange={e => setLibraryName(e.target.value)} onPressEnter={confirmLibraryDialog} />
|
||||
</Modal>
|
||||
</ConfigProvider>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Button, Checkbox, Empty, Popconfirm, Tooltip } from 'antd';
|
||||
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
|
||||
import { libraryComponentParts, libraryComponentPath, libraryComponents } from '@/utils/assemblyLibrary';
|
||||
import type { Assembly } from '@/utils/assemblyEditor';
|
||||
|
||||
/** 组件与零件共用同一选择区;叶子实例的交集决定是否能再次选择。 */
|
||||
export default function AssemblyLibraryPanel({ document, current, activeId, editing, search, onSelect, onCreate, onRename, onDelete, onToggle }: {
|
||||
document: Assembly; current: Assembly; activeId: string | null; editing: boolean; search: string;
|
||||
onSelect: (id: string) => void; onCreate: (parentId: string | null) => void;
|
||||
onRename: (id: string) => void; onDelete: (id: string) => void; onToggle: (id: string, selected: boolean) => void;
|
||||
}) {
|
||||
const all = libraryComponents(document), selected = new Set(current.steps.flatMap(s => s.parts));
|
||||
const query = search.trim().toLowerCase();
|
||||
const matches = new Set(all.filter(c => libraryComponentPath(document, c.id).toLowerCase().includes(query)).map(c => c.id));
|
||||
for (const id of [...matches]) { let c = all.find(v => v.id === id); const seen = new Set<string>(); while (c?.parentId && !seen.has(c.id)) { seen.add(c.id); matches.add(c.parentId); c = all.find(v => v.id === c!.parentId); } }
|
||||
const render = (parentId: string | null, seen = new Set<string>()) => all.filter(c => c.parentId === parentId && !seen.has(c.id) && matches.has(c.id)).map(c => {
|
||||
let parts: string[] = []; try { parts = libraryComponentParts(document, c.id); } catch { /* 保存区呈现具体校验错误 */ }
|
||||
const direct = current.steps.find(s => s.componentId === c.id), overlap = parts.filter(id => selected.has(id)).length;
|
||||
const checked = parts.length > 0 && overlap === parts.length;
|
||||
const eligible = !editing || !!activeId && c.parentId === activeId;
|
||||
const disabled = !parts.length || !eligible || !direct && overlap > 0;
|
||||
const hint = !parts.length ? '先编辑组件内容,再选择安装' : !eligible ? c.id === activeId ? '正在编辑这个组件' : '当前工作区只可选择它的直接子组件' : !direct && overlap ? checked ? '成员已随其他选择安装,不能重复选择' : `${overlap} 个成员零件已选,请先取消重复项` : direct ? '取消选择会移除此组件步骤,成员零件也会取消选中' : `选择后自动选中 ${parts.length} 个成员零件`;
|
||||
return <li key={c.id}>
|
||||
<div className={`assembly-library-row ${direct || checked ? 'is-active' : ''}`} title={hint}>
|
||||
<Checkbox aria-label={`选择组件 ${c.name}`} checked={checked} indeterminate={overlap > 0 && !checked} disabled={disabled} onChange={e => onToggle(c.id, e.target.checked)}><strong>{c.name}</strong><small>{parts.length} 个零件{direct ? ' · 已选择' : overlap ? ' · 成员已选' : !parts.length ? ' · 待制作' : ''}</small></Checkbox>
|
||||
<div className="assembly-library-row-actions"><Tooltip title={`编辑 ${c.name}`}><Button type="text" size="small" aria-label={`编辑库组件 ${c.name}`} icon={<EditOutlined />} onClick={() => onSelect(c.id)} /></Tooltip><Tooltip title="创建子组件"><Button type="text" size="small" aria-label={`在 ${c.name} 下新建子组件`} icon={<PlusOutlined />} onClick={() => onCreate(c.id)} /></Tooltip><Popconfirm title={`删除组件“${c.name}”?已引用或包含子组件时不可删除。`} onConfirm={() => onDelete(c.id)}><Button type="text" danger size="small" aria-label={`删除库组件 ${c.name}`} icon={<DeleteOutlined />} /></Popconfirm></div>
|
||||
{editing && activeId === c.id && <Button type="link" size="small" className="assembly-library-rename" onClick={() => onRename(c.id)}>重命名</Button>}
|
||||
</div>
|
||||
<ul>{render(c.id, new Set([...seen, c.id]))}</ul>
|
||||
</li>;
|
||||
});
|
||||
return <section className="assembly-choice-components" aria-label="组件选择">
|
||||
<div className="assembly-choice-section-title"><strong>组件</strong><span>{all.length} 个</span><Button type="link" size="small" onClick={() => onCreate(editing ? activeId : null)}>{editing && activeId ? '创建子组件' : '创建组件'}</Button></div>
|
||||
{!all.length ? <span className="assembly-no-components">还没有组件,也可直接选择下方零件。</span> : !matches.size ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有匹配的组件" /> : <ul className="assembly-library-tree">{render(null)}</ul>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Button, Empty, Input, Popover, Segmented, Tooltip } from 'antd';
|
||||
import { EyeInvisibleOutlined, EyeOutlined, ReloadOutlined } from '@ant-design/icons';
|
||||
import type { Assembly, AssemblySource } from '@/utils/assemblyEditor';
|
||||
import AssemblyViewport from './AssemblyViewport';
|
||||
const noUnplacedParts: string[] = [];
|
||||
|
||||
/** 参考模型的显隐仅存在本地,不写入步骤、草稿或公开 JSON。 */
|
||||
export default function AssemblyReference({ assembly, sources, unplaced = noUnplacedParts, resetToken }: { assembly: Assembly; sources: AssemblySource[]; unplaced?: string[]; resetToken: boolean }) {
|
||||
const [hidden, setHidden] = useState<Set<string>>(new Set()), [fit, setFit] = useState(0);
|
||||
const [search, setSearch] = useState(''), [filter, setFilter] = useState('all');
|
||||
useEffect(() => { setHidden(new Set()); setFit(n => n + 1); }, [resetToken]);
|
||||
const parts = useMemo(() => assembly.parts.filter(p => !unplaced.includes(p.id)), [assembly.parts, unplaced]);
|
||||
const allIds = useMemo(() => parts.map(p => p.id), [parts]);
|
||||
const shown = useMemo(() => allIds.filter(id => !hidden.has(id)), [allIds, hidden]);
|
||||
const reference = useMemo(() => ({ ...assembly, parts, steps: [] }), [assembly, parts]);
|
||||
const filtered = parts.filter(p => (filter !== 'hidden' || hidden.has(p.id)) && `${p.name} ${sources.find(s => s.asset.assetId === p.assetId)?.asset.relativePath ?? ''}`.toLowerCase().includes(search.trim().toLowerCase()));
|
||||
const toggle = (id: string) => setHidden(old => { const next = new Set(old); if (next.has(id)) next.delete(id); else next.add(id); return next; });
|
||||
const visibility = <div className="assembly-reference-controls" role="group" aria-label="参考模型零件显隐">
|
||||
<Input.Search aria-label="搜索参考零件" placeholder="搜索零件名称或路径" value={search} onChange={e => setSearch(e.target.value)} allowClear />
|
||||
<div className="assembly-reference-controls-toolbar"><Segmented size="small" aria-label="参考零件筛选" value={filter} onChange={value => setFilter(String(value))} options={[{ label: '全部', value: 'all' }, { label: '已隐藏', value: 'hidden' }]} /><span>{shown.length} / {parts.length} 显示</span></div>
|
||||
<div className="assembly-reference-visibility-list">{!filtered.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={search.trim() ? '没有匹配的零件' : '没有隐藏的零件'} />}{filtered.map(p => <button type="button" key={p.id} aria-label={`${hidden.has(p.id) ? '显示' : '隐藏'}参考零件 ${p.name}`} onClick={() => toggle(p.id)}><span className={hidden.has(p.id) ? 'is-hidden' : ''}>{hidden.has(p.id) ? <EyeInvisibleOutlined /> : <EyeOutlined />}</span><span title={p.name}>{p.name}</span><small>{hidden.has(p.id) ? '已隐藏' : '显示中'}</small></button>)}</div>
|
||||
<div className="assembly-reference-batch"><Button size="small" onClick={() => setHidden(new Set())}>全部显示</Button><Button size="small" onClick={() => setHidden(new Set(allIds))}>全部隐藏</Button><span>只影响左侧参考</span></div>
|
||||
</div>;
|
||||
return <section className="assembly-reference-stage" aria-label="整机参考视窗">
|
||||
<header className="assembly-stage-heading"><div><strong>整机参考</strong><small>{shown.length} / {parts.length} 显示</small></div><div className="assembly-stage-heading-actions"><Popover title="参考模型 · 零件显隐" trigger="click" placement="bottomLeft" content={visibility}><Button size="small" icon={<EyeOutlined />} aria-label="参考零件显隐">零件显隐</Button></Popover><Tooltip title="恢复完整参考模型"><Button size="small" disabled={shown.length === parts.length} onClick={() => setHidden(new Set())}>全部显示</Button></Tooltip><Tooltip title="重置参考视角"><Button size="small" aria-label="重置参考视角" icon={<ReloadOutlined />} onClick={() => setFit(n => n + 1)} /></Tooltip></div></header>
|
||||
<div className="assembly-reference-canvas"><AssemblyViewport assembly={reference} sources={sources} selected={[]} visibleParts={shown} fitParts={allIds} preview={null} replay={0} referenceVisible={false} tool="select" fit={fit} quality="reference" label="整机参考三维预览" hint="拖动旋转 · 滚轮缩放 · 点击零件隐藏" onPick={toggle} onTransform={() => {}} />
|
||||
{!shown.length && <div className="assembly-reference-empty"><span>{parts.length ? '参考零件已全部隐藏' : '暂无可定位的参考零件'}</span>{parts.length > 0 && <Button size="small" onClick={() => setHidden(new Set())}>显示全部参考零件</Button>}</div>}
|
||||
</div><footer className="assembly-view-caption">点击模型零件隐藏,通过“零件显隐”恢复。</footer>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Button, Select } from 'antd';
|
||||
import type { AssemblyStageRef } from '@/api/experience-types';
|
||||
import type { AssemblyStage } from '@/utils/assemblyWorkflow';
|
||||
|
||||
export default function AssemblySceneSettings({ stages, cursor, onChange }: {
|
||||
stages: AssemblyStage[]; cursor: number; onChange: (mode: 'independent' | 'continue' | 'inherit', base?: AssemblyStageRef) => void;
|
||||
}) {
|
||||
const stage = stages[cursor];
|
||||
if (!stage || stage.kind !== 'part') return null;
|
||||
const earlier = stages.slice(0, cursor).filter(s => !s.problem);
|
||||
const base = earlier.find(s => s.ref.kind === stage.base?.kind && s.ref.id === stage.base.id);
|
||||
return <div className="assembly-scene-settings">
|
||||
<div className="assembly-scene-controls"><span>拼装分段</span>
|
||||
<Button size="small" aria-label="标记新拼装" type={stage.sceneExplicit && stage.sceneMode === 'independent' ? 'primary' : 'default'} onClick={() => onChange('independent')}>新拼装</Button>
|
||||
<Button size="small" aria-label="标记继续拼装" type={stage.sceneExplicit && stage.sceneMode === 'continue' ? 'primary' : 'default'} disabled={!earlier.length} onClick={() => onChange('continue', base?.ref ?? earlier.at(-1)?.ref)}>继续拼装</Button>
|
||||
{stage.sceneExplicit && <Button size="small" type="text" onClick={() => onChange('inherit')}>取消标记</Button>}
|
||||
{stage.sceneExplicit && stage.sceneMode === 'continue' && <Select aria-label="续装基准步骤" showSearch virtual={false} optionFilterProp="label" placeholder="接着哪一段拼装" value={base?.id} onChange={id => onChange('continue', earlier.find(s => s.id === id)!.ref)} options={earlier.map(s => ({ value: s.id, label: `第 ${stages.indexOf(s) + 1} 步 · ${s.label}` }))} />}
|
||||
</div>
|
||||
<div className={`assembly-scene-hint ${stage.problem ? 'has-problem' : ''}`}>{stage.problem ?? (stage.sceneExplicit ? stage.sceneMode === 'independent' ? '从这里开始新拼装,后续组件和零件自动接着安装,直到下一个分段标记。' : `接着第 ${base ? stages.indexOf(base) + 1 : '?'} 步的进度拼装,后续自动延续。`
|
||||
: cursor === 0 ? '从第一个选择开始,后续自动继续拼装,无需逐步标记。' : '沿用上一安装进度;只有另起一段或接回其他进度时,才需要设置标记。')}</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { Vector3 as Point, Quaternion as Rotation } from 'three';
|
||||
import { Alert, App, Button, Input, InputNumber, Modal, Select, Space, Switch, Typography } from 'antd';
|
||||
import type { AssemblyPart, AssemblyTool, Vector3 } from '@/api/experience-types';
|
||||
import { entryOffset, newEditorId, type Assembly, type AssemblySource, type EntrySide } from '@/utils/assemblyEditor';
|
||||
import { analyzeScrewHead, inferToolTipAxis, sourceGeometry } from '@/utils/assemblyGeometry';
|
||||
import { normalizedInstallation } from '@/utils/assemblyToolConfig';
|
||||
import { toolRoll, toolRotation } from '@/utils/assemblyMotion';
|
||||
import { errorText, isAbort } from '@/utils/format';
|
||||
import SurfaceCalibration from './SurfaceCalibration';
|
||||
|
||||
const directions: { value: EntrySide; label: string }[] = [
|
||||
{ value: 'x+', label: 'X' }, { value: 'y+', label: 'Y' }, { value: 'z+', label: 'Z' },
|
||||
{ value: 'x-', label: '−X' }, { value: 'y-', label: '−Y' }, { value: 'z-', label: '−Z' },
|
||||
];
|
||||
export default function AssemblyStepSettings({ assembly, stepId, connectionId, stageNumber, sceneControls, focusPartId, sources, onChange, onPreview, onPendingChange }: {
|
||||
assembly: Assembly; stepId: string | null; connectionId?: string; stageNumber?: number; focusPartId?: string; sources: AssemblySource[];
|
||||
sceneControls?: ReactNode;
|
||||
onChange: (mutate: (draft: Assembly) => void) => void; onPreview: () => void; onPendingChange: (pending: boolean) => void;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const step = assembly.steps.find(s => s.id === stepId);
|
||||
const connection = assembly.componentPlan?.connections.find(c => c.id === connectionId);
|
||||
const [target, setTarget] = useState<string>();
|
||||
const part = assembly.parts.find(p => p.id === (target && step?.parts.includes(target) ? target : step?.parts[0]));
|
||||
const motion = step?.componentId ? undefined : part?.installation;
|
||||
const profile = assembly.tools?.find(t => t.id === motion?.toolId);
|
||||
const [side, setSide] = useState<EntrySide | 'custom'>('y+'), [distance, setDistance] = useState<number | null>(80);
|
||||
const [useTool, setUseTool] = useState(false), [toolAsset, setToolAsset] = useState<string>();
|
||||
const [draftTool, setDraftTool] = useState<AssemblyTool>();
|
||||
const [headDirty, setHeadDirty] = useState(false);
|
||||
const [turns, setTurns] = useState<number | null>(3), [travel, setTravel] = useState<number | null>(1.2), [roll, setRoll] = useState<number | null>(0);
|
||||
const [direction, setDirection] = useState<'clockwise' | 'counterclockwise'>('clockwise');
|
||||
const [axisMode, setAxisMode] = useState<'auto' | EntrySide>('auto'), [depth, setDepth] = useState<number | null>(.35);
|
||||
const [busy, setBusy] = useState(false), [error, setError] = useState('');
|
||||
const [calibrationSettingsOpen, setCalibrationSettingsOpen] = useState(false);
|
||||
const [calibration, setCalibration] = useState<{ mode: 'tool' | 'screw'; source: AssemblySource; tool?: AssemblyTool } | null>(null);
|
||||
const job = useRef<AbortController>();
|
||||
const partRef = useRef(part?.id); partRef.current = part?.id;
|
||||
const configured = !!motion && profile?.assetId === toolAsset;
|
||||
const parameterDirty = !!motion && (turns !== motion.turns || travel === null || Math.abs(travel - motion.travel * 1000) > 1e-8 || direction !== motion.direction || roll === null || Math.abs(roll - (profile ? toolRoll(profile, motion) : 0)) > .001 || headDirty);
|
||||
const pending = busy || useTool && (!configured || parameterDirty);
|
||||
useEffect(() => { setTarget(focusPartId && step?.parts.includes(focusPartId) ? focusPartId : step?.parts[0]); }, [stepId, focusPartId]);
|
||||
useEffect(() => {
|
||||
job.current?.abort(); setBusy(false); setError(''); setCalibration(null); setCalibrationSettingsOpen(false); setDraftTool(undefined);
|
||||
return () => job.current?.abort();
|
||||
}, [part?.id]);
|
||||
useEffect(() => {
|
||||
setUseTool(!!motion); setToolAsset(profile?.assetId); setTurns(motion?.turns ?? 3); setTravel((motion?.travel ?? .0012) * 1000);
|
||||
setDirection(motion?.direction ?? 'clockwise'); setRoll(motion && profile ? toolRoll(profile, motion) : 0); setAxisMode('auto'); setHeadDirty(false);
|
||||
}, [part?.id, JSON.stringify(motion), JSON.stringify(profile)]);
|
||||
useEffect(() => {
|
||||
const offset = step?.componentId ? step.installOffset ?? [0, .08, 0] : part?.installOffset ?? connection?.installOffset;
|
||||
if (!offset) return;
|
||||
const axis = offset.findIndex(v => Math.abs(v) > 1e-10);
|
||||
if (axis >= 0 && offset.filter(v => Math.abs(v) > 1e-10).length === 1) { setSide(`${['x', 'y', 'z'][axis]}${offset[axis] < 0 ? '-' : '+'}` as EntrySide); setDistance(Math.abs(offset[axis]) * 1000); }
|
||||
else { setSide('custom'); setDistance(Math.hypot(...offset) * 1000); }
|
||||
}, [part?.id, step?.id, connection?.id, JSON.stringify(step?.componentId ? step.installOffset : part?.installOffset ?? connection?.installOffset)]);
|
||||
useEffect(() => { onPendingChange(!!pending); }, [pending, onPendingChange]);
|
||||
useEffect(() => () => onPendingChange(false), [onPendingChange]);
|
||||
const changeOffset = (axis: EntrySide | 'custom', millimeters: number | null) => {
|
||||
setSide(axis); setDistance(millimeters);
|
||||
if ((!part && !connection) || millimeters === null || !Number.isFinite(millimeters) || millimeters <= 0) return;
|
||||
onChange(a => {
|
||||
const p = a.parts.find(p => p.id === part?.id), c = a.componentPlan?.connections.find(c => c.id === connection?.id), target = step?.componentId ? a.steps.find(s => s.id === step.id) : p ?? c;
|
||||
if (!target) return;
|
||||
const original = target.installOffset ?? [0, .08, 0], length = Math.hypot(...original);
|
||||
target.installOffset = axis === 'custom' && length > 0 ? original.map(v => v / length * millimeters / 1000) as Vector3 : entryOffset(axis === 'custom' ? 'y+' : axis, millimeters);
|
||||
}); onPreview();
|
||||
};
|
||||
const run = async (fn: (signal: AbortSignal) => Promise<void>) => {
|
||||
job.current?.abort(); const abort = new AbortController(); job.current = abort; setBusy(true); setError('');
|
||||
try { await fn(abort.signal); }
|
||||
catch (e) { if (!abort.signal.aborted && !isAbort(e)) setError(errorText(e)); }
|
||||
finally { if (job.current === abort && !abort.signal.aborted) setBusy(false); }
|
||||
};
|
||||
const applyTool = (tool: AssemblyTool, options?: { analyze?: boolean; point?: { position: Vector3; axis: Vector3 } }) => {
|
||||
if (!part) return;
|
||||
const partId = part.id;
|
||||
void run(async signal => {
|
||||
if (!turns || !Number.isInteger(turns) || turns < 1 || turns > 20 || !travel || travel < .01 || travel > 100 || roll === null || !Number.isFinite(roll)) throw new Error('请填写 1–20 的整数圈数和有效的拧入行程。');
|
||||
const source = sources.find(s => s.asset.assetId === part.assetId);
|
||||
if (!source) throw new Error('未找到当前零件原文件,请刷新资源。');
|
||||
let axis = options?.point?.axis ?? motion?.axis, socket = options?.point?.position ?? motion?.socketPosition;
|
||||
if (!options?.point && (options?.analyze || headDirty || !axis || !socket || axisMode !== 'auto')) {
|
||||
if (depth === null || depth < 0 || !Number.isFinite(depth)) throw new Error('请填写有效的螺丝头插入点深度。');
|
||||
const head = analyzeScrewHead(await sourceGeometry(source, signal), depth / 1000, axisMode === 'auto' ? undefined : entryOffset(axisMode, 1000));
|
||||
axis = head.axis; socket = head.socketPosition;
|
||||
}
|
||||
signal.throwIfAborted(); if (partRef.current !== partId) return;
|
||||
if (!tool.tipAxis) { const toolSource = sources.find(s => s.asset.assetId === tool.assetId); if (!toolSource) throw new Error('工具原文件缺失。'); tool = { ...tool, tipAxis: inferToolTipAxis(await sourceGeometry(toolSource, signal), tool.tipPosition) }; }
|
||||
if (!axis || !socket) throw new Error('请先校准螺丝头。');
|
||||
signal.throwIfAborted(); if (partRef.current !== partId) return;
|
||||
const installation = normalizedInstallation({ ...(motion ?? {}), type: 'screw', toolId: tool.id, axis, socketPosition: socket, toolQuaternion: toolRotation(tool.tipAxis!, axis, roll), turns, travel: travel / 1000, direction });
|
||||
onChange(a => {
|
||||
const p = a.parts.find(p => p.id === partId); if (!p) return;
|
||||
if (a.steps.some(s => s.parts.some(id => a.parts.find(v => v.id === id)?.assetId === tool.assetId))) throw new Error('这个 GLB 已是装配零件,请先从流程移除,再设为工具。');
|
||||
const byId = new Map(a.parts.map(p => [p.id, p]));
|
||||
const seen = new Set<string>();
|
||||
for (let node: AssemblyPart | undefined = p; node && !seen.has(node.id); node = node.parentId ? byId.get(node.parentId) : undefined) { seen.add(node.id); if (Math.max(...node.scale) - Math.min(...node.scale) > 1e-8) throw new Error('螺丝及其父零件须等比缩放,才能正确旋转工具。'); }
|
||||
const tools = a.tools ??= [], existing = tools.findIndex(t => t.id === tool.id);
|
||||
if (existing < 0 && tools.length >= 32) throw new Error('当前播放器最多支持 32 个工具配置,请复用已有工具。');
|
||||
if (existing >= 0) tools[existing] = tool; else tools.push(tool);
|
||||
p.installation = installation;
|
||||
if (options?.analyze || headDirty || options?.point || !motion) {
|
||||
// 起始偏移是父坐标,拧入轴是零件局部坐标,需经过零件自身旋转与缩放。
|
||||
const outward = new Point(...axis!).negate().multiply(new Point(...p.scale)).applyQuaternion(new Rotation(...p.quaternion)).normalize();
|
||||
p.installOffset = outward.multiplyScalar((distance && distance > 0 ? distance : 18) / 1000).toArray();
|
||||
}
|
||||
});
|
||||
setToolAsset(tool.assetId); setUseTool(true); onPreview(); message.success('工具已对齐螺丝头,可重播本步检查旋转与拧入方向。');
|
||||
});
|
||||
};
|
||||
const selectTool = (assetId: string) => {
|
||||
setToolAsset(assetId); setError(''); setDraftTool(undefined);
|
||||
if (assembly.steps.some(s => s.parts.some(id => assembly.parts.find(p => p.id === id)?.assetId === assetId))) { setError('这个 GLB 已作为装配零件选中,请先从流程移除,再将它设为工具。'); return; }
|
||||
const source = sources.find(s => s.asset.assetId === assetId)!;
|
||||
const existing = assembly.tools?.find(t => t.assetId === assetId);
|
||||
if (existing) applyTool(existing);
|
||||
else setCalibration({ source, tool: existing, mode: 'tool' });
|
||||
};
|
||||
const selectedSource = sources.find(s => s.asset.assetId === toolAsset), selectedProfile = assembly.tools?.find(t => t.assetId === toolAsset) ?? (draftTool?.assetId === toolAsset ? draftTool : undefined);
|
||||
return <section className="assembly-step-config">
|
||||
<div className="assembly-config-heading"><strong>{connection ? `组件总装 · ${connection.name}` : step?.componentId ? step.label : step && part ? `当前步骤 · ${part.name}` : '安装设置'}</strong><Typography.Text type="secondary">{connection || step?.componentId ? `${stageNumber ? `第 ${stageNumber} 步 · ` : ''}组件整体进入,保留内部相对位置` : step ? `第 ${stageNumber ?? assembly.steps.indexOf(step) + 1} 步` : '点选零件后可设置进入方向与工具'}</Typography.Text></div>
|
||||
{sceneControls}
|
||||
{step && <Input className="assembly-step-name" aria-label="当前步骤名称" value={step.label} variant="borderless" onChange={e => onChange(a => { const s = a.steps.find(s => s.id === step.id); if (s) s.label = e.target.value; })} />}
|
||||
{step && !step.componentId && step.parts.length > 1 && <Select aria-label="当前步骤零件" value={part?.id} onChange={setTarget} options={step.parts.map(id => ({ value: id, label: assembly.parts.find(p => p.id === id)?.name ?? id }))} style={{ width: '100%', marginBottom: 10 }} />}
|
||||
<div className="assembly-config-basic"><div><label>进入方向{side === 'custom' && (part || connection) ? ' · 当前沿模型轴线' : ''}</label><div className="assembly-direction-buttons">{directions.map(d => <Button key={d.value} aria-label={`从 ${d.label} 进入`} size="small" type={side === d.value ? 'primary' : 'default'} disabled={!part && !connection || busy} onClick={() => changeOffset(d.value, distance)}>{d.label}</Button>)}</div></div>
|
||||
<div><label>进入距离</label><InputNumber aria-label="进入距离(毫米)" precision={3} min={.01} addonAfter="毫米" value={distance} disabled={!part && !connection || busy} onChange={value => changeOffset(side, value)} /></div>
|
||||
{!step?.componentId && <div className="assembly-use-tool"><label>使用工具拧入</label><Switch aria-label="使用工具拧入" checked={useTool} disabled={!part || busy} onChange={checked => { setUseTool(checked); setError(''); if (!checked && part) onChange(a => { const p = a.parts.find(p => p.id === part.id); if (p) delete p.installation; }); }} /></div>}
|
||||
</div>
|
||||
{useTool && part && <div className="assembly-tool-settings"><div className="assembly-tool-selector"><Select showSearch virtual={false} optionFilterProp="label" aria-label="安装工具 GLB" placeholder="从项目 GLB 文件中选择工具" value={toolAsset} disabled={busy} onChange={selectTool} options={sources.filter(s => s.asset.type === 'part-glb').map(s => ({ value: s.asset.assetId, label: s.asset.relativePath }))} /><Button disabled={!selectedSource || busy} onClick={() => selectedSource && setCalibration({ source: selectedSource, tool: selectedProfile, mode: 'tool' })}>校准工具工作端</Button></div>
|
||||
<Space wrap><Select aria-label="拧紧旋转方向" value={direction} onChange={setDirection} options={[{ value: 'clockwise', label: '顺时针拧紧' }, { value: 'counterclockwise', label: '逆时针拧入' }]} style={{ width: 145 }} disabled={busy} /><InputNumber aria-label="旋转圈数" value={turns} onChange={setTurns} min={1} max={20} precision={0} addonAfter="圈" style={{ width: 120 }} disabled={busy} /><InputNumber aria-label="拧入行程(毫米)" precision={3} value={travel} onChange={setTravel} min={.01} max={100} addonBefore="拧入" addonAfter="毫米" style={{ width: 180 }} disabled={busy} /><Button type="primary" loading={busy} disabled={!selectedProfile || !turns || !travel} onClick={() => selectedProfile && applyTool(selectedProfile)}>应用工具并预览</Button></Space>
|
||||
{error && <Alert type="warning" showIcon message={error} />}
|
||||
<Button className="assembly-calibration-link" type="link" size="small" onClick={() => setCalibrationSettingsOpen(true)}>螺丝头与工具方向校准</Button>
|
||||
<Modal open={calibrationSettingsOpen} title="螺丝头与工具方向校准" width={660} onCancel={() => setCalibrationSettingsOpen(false)} footer={<Button onClick={() => setCalibrationSettingsOpen(false)}>返回装配编辑</Button>}>
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}><Space wrap><Select aria-label="螺丝局部拧入轴" value={axisMode} onChange={value => { setAxisMode(value); setHeadDirty(true); }} options={[{ value: 'auto', label: '自动识别螺丝头' }, ...directions.map(d => ({ value: d.value, label: `局部 ${d.label}` }))]} style={{ width: 180 }} /><InputNumber aria-label="螺丝头插入点深度(毫米)" value={depth} min={0} addonBefore="深度" addonAfter="毫米" onChange={value => { setDepth(value); setHeadDirty(true); }} style={{ width: 180 }} /><InputNumber aria-label="工具绕轴角度" precision={2} value={roll} addonBefore="转角" addonAfter="°" onChange={setRoll} style={{ width: 150 }} /></Space><Space wrap><Button disabled={!selectedProfile || busy} onClick={() => selectedProfile && applyTool(selectedProfile, { analyze: true })}>重新识别螺丝头</Button><Button disabled={busy} onClick={() => { const s = sources.find(s => s.asset.assetId === part.assetId); if (s) { setCalibrationSettingsOpen(false); setCalibration({ source: s, mode: 'screw' }); } }}>在模型上点选螺丝头</Button></Space>{motion && <Typography.Text type="secondary">局部拧入轴 [{motion.axis.map(v => v.toFixed(4)).join(', ')}];工具尖端会对齐插入点,按零件自身朝向旋转。</Typography.Text>}</Space>
|
||||
</Modal>
|
||||
{pending && !busy && <Typography.Text type="warning">选择并校准工具后才可保存;自动识别失败时请点选螺丝头。</Typography.Text>}
|
||||
</div>}
|
||||
{calibration && <SurfaceCalibration source={calibration.source} mode={calibration.mode} depth={(depth ?? .35) / 1000} initial={calibration.mode === 'tool' && calibration.tool?.tipAxis ? { position: calibration.tool.tipPosition, axis: calibration.tool.tipAxis } : calibration.mode === 'screw' && motion ? { position: motion.socketPosition, axis: motion.axis } : undefined} onClose={() => setCalibration(null)} onSave={value => {
|
||||
if (calibration.mode === 'tool') {
|
||||
const tool: AssemblyTool = { ...(calibration.tool ?? { id: newEditorId('tool'), assetId: calibration.source.asset.assetId }), tipPosition: value.position, tipAxis: value.axis };
|
||||
setDraftTool(tool); setCalibration(null); applyTool(tool);
|
||||
} else {
|
||||
setCalibration(null); if (selectedProfile) applyTool(selectedProfile, { point: value }); else setError('请先选择并校准安装工具。');
|
||||
}
|
||||
}} />}
|
||||
</section>;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Spin } from 'antd';
|
||||
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 { TransformControls } from 'three/addons/controls/TransformControls.js';
|
||||
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
|
||||
@@ -10,10 +11,22 @@ import type { AssemblyPart } from '@/api/experience-types';
|
||||
import type { Assembly, AssemblySource } from '@/utils/assemblyEditor';
|
||||
import { safeExperienceUrl } from '@/utils/modelAssets';
|
||||
import { errorText } from '@/utils/format';
|
||||
import { fitPreviewTextures } from '@/utils/assemblyPreviewMemory';
|
||||
import { geometryFacts, inferToolTipAxis } from '@/utils/assemblyGeometry';
|
||||
import { alignedToolQuaternion, ScrewTransition, screwDuration } from '@/utils/assemblyMotion';
|
||||
import type { Vector3 } from '@/api/experience-types';
|
||||
|
||||
export interface SurfacePick { partId: string; position: Vector3; normal: Vector3 }
|
||||
|
||||
interface Props {
|
||||
assembly: Assembly; sources: AssemblySource[]; reference?: AssemblySource; selected: string[];
|
||||
preview: number | null; replay: number; referenceVisible: boolean; tool: 'select' | 'translate' | 'rotate'; fit: number;
|
||||
visibleParts?: string[]; enteringParts?: string[]; stageOffset?: AssemblyPart['installOffset']; focusKey?: string;
|
||||
label?: string; hint?: string; fitParts?: string[]; quality?: 'reference' | 'detail';
|
||||
paused?: boolean; onLoadingChange?: (loading: boolean) => void;
|
||||
onPreviewComplete?: (preview: number, replay: number) => void;
|
||||
onSurfacePick?: (pick: SurfacePick) => void;
|
||||
marker?: { partId: string; position: Vector3; axis: Vector3 };
|
||||
onPick: (id: string, additive: boolean) => void;
|
||||
onTransform: (id: string, position: AssemblyPart['position'], quaternion: AssemblyPart['quaternion']) => void;
|
||||
}
|
||||
@@ -42,31 +55,44 @@ export default function AssemblyViewport(props: Props) {
|
||||
useEffect(() => {
|
||||
const host = container.current!;
|
||||
const abort = new AbortController();
|
||||
let disposed = false, frame = 0, needsRender = true, dragging = false, animating = false, animationStart = 0;
|
||||
let disposed = false, frame = 0, needsRender = true, dragging = false, animating = false, completionNotified = false, elapsed = 0, previousTime = performance.now();
|
||||
let motionDuration = .8;
|
||||
let renderer: THREE.WebGLRenderer;
|
||||
setLoading(true); setProblem('');
|
||||
try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false }); }
|
||||
try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); }
|
||||
catch { setLoading(false); setProblem('当前浏览器无法开启 3D 预览。请开启硬件加速后重试;零件列表仍可编辑。'); return; }
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, props.quality === 'reference' ? 1.25 : 2));
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||||
renderer.toneMappingExposure = 1.15;
|
||||
renderer.domElement.setAttribute('aria-label', '装配模型三维预览');
|
||||
renderer.toneMapping = THREE.AgXToneMapping;
|
||||
renderer.toneMappingExposure = 1.05;
|
||||
renderer.domElement.setAttribute('aria-label', props.label ?? '装配模型三维预览');
|
||||
host.appendChild(renderer.domElement);
|
||||
const scene = new THREE.Scene(); scene.background = new THREE.Color('#f1f4fa');
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(38, 1, 0.001, 10000); camera.position.set(1, 0.8, 1);
|
||||
const pmrem = new THREE.PMREMGenerator(renderer), room = new RoomEnvironment();
|
||||
const environment = pmrem.fromScene(room, 0.04); scene.environment = environment.texture; room.dispose(); pmrem.dispose();
|
||||
scene.add(new THREE.HemisphereLight(0xffffff, 0xa5b0c2, 2));
|
||||
const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(2, 5, 3); scene.add(sun);
|
||||
scene.add(new THREE.HemisphereLight(0xffffff, 0x343840, 0.45));
|
||||
const sun = new THREE.DirectionalLight(0xffecd9, 2.5); sun.position.set(3, 4, -2); scene.add(sun);
|
||||
const fill = new THREE.DirectionalLight(0xdce7ff, 0.7); fill.position.set(-2, 2, 3); scene.add(fill);
|
||||
const grid = new THREE.GridHelper(6, 60, 0x626a75, 0x626a75);
|
||||
(grid.material as THREE.Material).transparent = true; (grid.material as THREE.Material).opacity = 0.14; (grid.material as THREE.Material).depthWrite = false;
|
||||
scene.add(grid);
|
||||
const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = false;
|
||||
controls.addEventListener('change', () => { needsRender = true; });
|
||||
const display = new THREE.Group(), models = new THREE.Group(), referenceGroup = new THREE.Group();
|
||||
display.add(models, referenceGroup); scene.add(display);
|
||||
const groups = new Map<string, THREE.Group>();
|
||||
const instances = new Map<string, THREE.Object3D>();
|
||||
const axes = new THREE.AxesHelper(1); scene.add(axes); axes.visible = false;
|
||||
let axesSize = 0.1;
|
||||
const templates: THREE.Object3D[] = [];
|
||||
const loaded = new Map<string, THREE.Object3D>();
|
||||
const screwMotions = new Map<string, { transition: ScrewTransition; delay: number }>();
|
||||
const marker = new THREE.Group(); marker.userData.editorMarker = true;
|
||||
const markerDot = new THREE.Mesh(new THREE.SphereGeometry(1, 16, 12), new THREE.MeshBasicMaterial({ color: 0xc5ff59, depthTest: false }));
|
||||
const markerArrow = new THREE.ArrowHelper(new THREE.Vector3(0, 0, 1), new THREE.Vector3(), 1, 0xc5ff59);
|
||||
marker.add(markerDot, markerArrow); marker.traverse(o => { o.userData.editorMarker = true; }); scene.add(marker); marker.visible = false;
|
||||
let ensureVisible: () => void = () => {};
|
||||
const boxes: THREE.BoxHelper[] = [];
|
||||
const transform = new TransformControls(camera, renderer.domElement);
|
||||
const transformHelper = transform.getHelper(); scene.add(transformHelper);
|
||||
@@ -79,14 +105,17 @@ export default function AssemblyViewport(props: Props) {
|
||||
const clearBoxes = () => { boxes.splice(0).forEach((b) => { scene.remove(b); b.geometry.dispose(); (b.material as THREE.Material).dispose(); }); };
|
||||
const update = (next: Props) => {
|
||||
if (dragging) return;
|
||||
screwMotions.forEach(m => m.transition.dispose()); screwMotions.clear();
|
||||
transform.detach();
|
||||
display.quaternion.fromArray(next.assembly.displayQuaternion);
|
||||
referenceGroup.visible = next.referenceVisible && next.preview === null;
|
||||
const visible = next.preview === null ? null : new Set(next.assembly.steps.slice(0, next.preview + 1).flatMap((s) => s.parts));
|
||||
const visible = next.visibleParts ? new Set(next.visibleParts) : next.preview === null ? null : new Set(next.assembly.steps.slice(0, next.preview + 1).flatMap((s) => s.parts));
|
||||
for (const p of next.assembly.parts) {
|
||||
const group = groups.get(p.id); if (!group) continue;
|
||||
group.position.fromArray(p.position); group.quaternion.fromArray(p.quaternion); group.scale.fromArray(p.scale);
|
||||
group.visible = !visible || visible.has(p.id);
|
||||
// 父级模型隐藏时仍保留坐标层级,让独立制作的子组件能单独显示。
|
||||
group.visible = true;
|
||||
const instance = instances.get(p.id); if (instance) instance.visible = !visible || visible.has(p.id);
|
||||
}
|
||||
clearBoxes();
|
||||
scene.updateMatrixWorld(true);
|
||||
@@ -98,15 +127,35 @@ export default function AssemblyViewport(props: Props) {
|
||||
axes.scale.setScalar(axesSize);
|
||||
}
|
||||
for (const id of next.selected) {
|
||||
const group = groups.get(id); if (!group?.visible) continue;
|
||||
const box = new THREE.BoxHelper(group, 0x6950e8); box.renderOrder = 100;
|
||||
const group = groups.get(id); if (!group || visible && !visible.has(id)) continue;
|
||||
const box = new THREE.BoxHelper(instances.get(id) ?? group, 0xc5ff59); box.renderOrder = 100;
|
||||
(box.material as THREE.Material).depthTest = false; scene.add(box); boxes.push(box);
|
||||
}
|
||||
if (next.tool !== 'select' && next.preview === null && next.selected.length === 1) {
|
||||
const group = groups.get(next.selected[0]);
|
||||
if (group) { transform.setMode(next.tool); transform.setSpace('local'); transform.attach(group); }
|
||||
}
|
||||
animating = next.preview !== null; animationStart = performance.now(); needsRender = true;
|
||||
let delay = 0;
|
||||
if (!next.stageOffset && next.preview !== null && next.preview >= 0) for (const id of next.enteringParts ?? next.assembly.steps[next.preview]?.parts ?? []) {
|
||||
const part = next.assembly.parts.find(p => p.id === id), config = next.assembly.tools?.find(t => t.id === part?.installation?.toolId);
|
||||
const template = config ? loaded.get(config.assetId) : undefined, group = groups.get(id);
|
||||
if (part?.installation && config && template && group) {
|
||||
const tool = new THREE.Group(); tool.add(clone(template));
|
||||
const calibrated = config.tipAxis ? config : { ...config, tipAxis: inferToolTipAxis(geometryFacts(template), config.tipPosition) };
|
||||
screwMotions.set(id, { transition: new ScrewTransition(group, part, tool, calibrated, delay), delay }); delay += screwDuration(part.installation);
|
||||
}
|
||||
}
|
||||
motionDuration = Math.max(.8, delay); elapsed = 0; completionNotified = false; previousTime = performance.now();
|
||||
marker.visible = !!next.marker;
|
||||
if (next.marker) {
|
||||
const group = groups.get(next.marker.partId);
|
||||
if (group) {
|
||||
group.add(marker); marker.position.fromArray(next.marker.position); markerArrow.setDirection(new THREE.Vector3(...next.marker.axis).normalize());
|
||||
const size = instances.has(next.marker.partId) ? new THREE.Box3().setFromObject(instances.get(next.marker.partId)!).getSize(new THREE.Vector3()).length() : .05;
|
||||
const length = Math.max(size * .25, .001); markerDot.scale.setScalar(length * .04); markerArrow.setLength(length, length * .18, length * .08);
|
||||
}
|
||||
}
|
||||
animating = next.preview !== null && next.preview >= 0; needsRender = true;
|
||||
};
|
||||
const fit = () => {
|
||||
// 使用最终位姿取包围盒;只移动相机,绝不归中、缩放或重写零件的原始变换。
|
||||
@@ -114,11 +163,24 @@ export default function AssemblyViewport(props: Props) {
|
||||
const preview = next.preview;
|
||||
update({ ...next, preview: null });
|
||||
scene.updateMatrixWorld(true);
|
||||
const box = new THREE.Box3().setFromObject(models);
|
||||
const box = new THREE.Box3();
|
||||
const fasteners = !next.stageOffset ? (next.enteringParts ?? []).filter(id => next.assembly.parts.find(p => p.id === id)?.installation) : [];
|
||||
const ids = next.fitParts ?? (fasteners.length ? fasteners : next.assembly.componentPlan && next.visibleParts?.length ? next.visibleParts : next.assembly.parts.map(p => p.id));
|
||||
ids.forEach(id => { const instance = instances.get(id); if (instance) box.union(new THREE.Box3().setFromObject(instance)); else { const group = groups.get(id); if (group) box.expandByPoint(group.getWorldPosition(new THREE.Vector3())); } });
|
||||
for (const id of fasteners) {
|
||||
const part = next.assembly.parts.find(p => p.id === id)!, config = next.assembly.tools?.find(t => t.id === part.installation!.toolId), group = groups.get(id);
|
||||
const template = config && loaded.get(config.assetId);
|
||||
if (template && config?.tipAxis && group) {
|
||||
const rotation = alignedToolQuaternion(part.installation!, config), position = new THREE.Vector3(...part.installation!.socketPosition).sub(new THREE.Vector3(...config.tipPosition).applyQuaternion(rotation));
|
||||
const matrix = group.matrixWorld.clone().multiply(new THREE.Matrix4().compose(position, rotation, new THREE.Vector3(1, 1, 1)));
|
||||
box.union(new THREE.Box3().setFromObject(template).applyMatrix4(matrix));
|
||||
}
|
||||
}
|
||||
if (box.isEmpty()) box.setFromObject(referenceGroup);
|
||||
if (!box.isEmpty()) {
|
||||
const center = box.getCenter(new THREE.Vector3()), radius = Math.max(box.getSize(new THREE.Vector3()).length() / 2, 0.01);
|
||||
axesSize = radius * 0.6;
|
||||
grid.scale.setScalar(radius); grid.position.y = box.min.y - radius * .015;
|
||||
const distance = radius / Math.sin(THREE.MathUtils.degToRad(camera.fov / 2)) * Math.max(1, 1 / camera.aspect) * 1.15;
|
||||
camera.near = Math.max(radius / 1000, 0.00001); camera.far = Math.max(distance * 100, 100);
|
||||
camera.position.copy(center).add(new THREE.Vector3(1, 0.65, 1).normalize().multiplyScalar(distance));
|
||||
@@ -133,37 +195,65 @@ export default function AssemblyViewport(props: Props) {
|
||||
const pointerUp = (e: PointerEvent) => {
|
||||
if (e.button !== 0 || !down || down.onGizmo || dragging || Math.hypot(down.x - e.clientX, down.y - e.clientY) > 5) return;
|
||||
const rect = renderer.domElement.getBoundingClientRect(), ray = new THREE.Raycaster();
|
||||
// 模型刚载入或相机刚适配时,点击可能先于下一渲染帧到达。
|
||||
scene.updateMatrixWorld(true); camera.updateMatrixWorld(true);
|
||||
ray.setFromCamera(new THREE.Vector2((e.clientX - rect.left) / rect.width * 2 - 1, -(e.clientY - rect.top) / rect.height * 2 + 1), camera);
|
||||
for (const hit of ray.intersectObject(models, true)) {
|
||||
if (hit.object.userData.editorMarker) continue;
|
||||
let object: THREE.Object3D | null = hit.object;
|
||||
let visible = true;
|
||||
for (let ancestor: THREE.Object3D | null = object; ancestor; ancestor = ancestor.parent) if (!ancestor.visible) visible = false;
|
||||
if (!visible) continue;
|
||||
while (object && !object.userData.partId) object = object.parent;
|
||||
if (object) { latest.current.onPick(object.userData.partId, e.shiftKey || e.metaKey || e.ctrlKey); break; }
|
||||
if (object) {
|
||||
if (latest.current.onSurfacePick && hit.face) {
|
||||
const inverse = object.matrixWorld.clone().invert(), meshToPart = inverse.clone().multiply(hit.object.matrixWorld);
|
||||
latest.current.onSurfacePick!({ partId: object.userData.partId, position: hit.point.clone().applyMatrix4(inverse).toArray(), normal: hit.face.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(meshToPart)).normalize().toArray() });
|
||||
} else latest.current.onPick(object.userData.partId, e.shiftKey || e.metaKey || e.ctrlKey);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
renderer.domElement.addEventListener('pointerdown', pointerDown); renderer.domElement.addEventListener('pointerup', pointerUp);
|
||||
const draw = (time: number) => {
|
||||
frame = requestAnimationFrame(draw);
|
||||
const delta = Math.min(.1, Math.max(0, (time - previousTime) / 1000)); previousTime = time;
|
||||
if (document.hidden) return;
|
||||
if (animating && !dragging) {
|
||||
const next = latest.current, t = Math.min(1, (time - animationStart) / 800), remaining = (1 - t) ** 3;
|
||||
const installing = new Set(next.assembly.steps[next.preview ?? -1]?.parts ?? []);
|
||||
if (animating && !dragging && !latest.current.paused) {
|
||||
elapsed += delta;
|
||||
const next = latest.current, t = Math.min(1, elapsed / .8), remaining = (1 - t) ** 3;
|
||||
const installing = new Set(next.enteringParts ?? next.assembly.steps[next.preview ?? -1]?.parts ?? []);
|
||||
next.assembly.parts.forEach((p) => {
|
||||
const object = groups.get(p.id);
|
||||
if (object && installing.has(p.id)) object.position.fromArray(p.position).addScaledVector(new THREE.Vector3(...p.installOffset), remaining);
|
||||
const screw = screwMotions.get(p.id);
|
||||
if (screw) { screw.transition.sample(elapsed); const instance = instances.get(p.id); if (instance) instance.visible = elapsed >= screw.delay; return; }
|
||||
if (object && installing.has(p.id)) {
|
||||
// 连接时整个组件使用同一个世界方向偏移;同一层级只移动根部,避免重复位移。
|
||||
const ancestorMoving = next.stageOffset && (() => { let id = p.parentId; const seen = new Set<string>(); while (id && !seen.has(id)) { if (installing.has(id)) return true; seen.add(id); id = next.assembly.parts.find(v => v.id === id)?.parentId ?? null; } return false; })();
|
||||
const offset = new THREE.Vector3(...(next.stageOffset ?? p.installOffset));
|
||||
if (next.stageOffset && object.parent) {
|
||||
const inverse = object.parent.matrixWorld.clone().invert();
|
||||
offset.applyMatrix4(inverse).sub(new THREE.Vector3().applyMatrix4(inverse));
|
||||
}
|
||||
object.position.fromArray(p.position);
|
||||
if (!ancestorMoving) object.position.addScaledVector(offset, remaining);
|
||||
}
|
||||
});
|
||||
animating = t < 1; needsRender = true;
|
||||
animating = elapsed < motionDuration; needsRender = true;
|
||||
}
|
||||
if (needsRender) { boxes.forEach((b) => b.update()); renderer.render(scene, camera); needsRender = false; }
|
||||
// 由真实动画完成事件推进流程,等待模型载入,后台标签页也不会按定时器跳过步骤。
|
||||
if (!animating && !completionNotified && !loadingRun && elapsed >= motionDuration && latest.current.preview !== null && latest.current.preview >= 0) {
|
||||
completionNotified = true; latest.current.onPreviewComplete?.(latest.current.preview, latest.current.replay);
|
||||
}
|
||||
};
|
||||
frame = requestAnimationFrame(draw);
|
||||
api.current = { update, fit };
|
||||
api.current = { update: next => { update(next); ensureVisible(); }, fit };
|
||||
const manager = new THREE.LoadingManager();
|
||||
// GLB 必须自包含。只允许解析内嵌数据,避免意外加载包外贴图或缓冲区。
|
||||
manager.setURLModifier((url) => { if (/^(blob:|data:)/.test(url)) return url; throw new Error('GLB 引用了外部贴图或缓冲区,请导出为内嵌资源的 GLB'); });
|
||||
const loader = new GLTFLoader(manager);
|
||||
const draco = new DRACOLoader().setDecoderPath(`${import.meta.env.BASE_URL}vendor/draco/`).setWorkerLimit(1);
|
||||
const loader = new GLTFLoader(manager).setDRACOLoader(draco);
|
||||
const fetchModel = async (source: AssemblySource) => {
|
||||
let buffer: ArrayBuffer;
|
||||
if (source.file) buffer = await source.file.arrayBuffer();
|
||||
@@ -175,27 +265,13 @@ export default function AssemblyViewport(props: Props) {
|
||||
}
|
||||
abort.signal.throwIfAborted();
|
||||
const gltf = await loader.parseAsync(buffer, '');
|
||||
try { await fitPreviewTextures(gltf.scene, latest.current.assembly.parts.length * (props.quality === 'reference' ? 2 : 1), abort.signal); }
|
||||
catch (cause) { disposeObjects([gltf.scene]); throw cause; }
|
||||
if (disposed) { disposeObjects([gltf.scene]); throw new DOMException('Aborted', 'AbortError'); }
|
||||
templates.push(gltf.scene); return gltf.scene;
|
||||
};
|
||||
const loadModels = async () => {
|
||||
const next = latest.current, required = [...new Set(next.assembly.parts.map((p) => p.assetId))];
|
||||
const loaded = new Map<string, THREE.Object3D>();
|
||||
const errors: string[] = []; let index = 0;
|
||||
await Promise.all([0, 1].map(async () => {
|
||||
while (!disposed && index < required.length) {
|
||||
const id = required[index++];
|
||||
const source = latest.current.sources.find((s) => s.asset.assetId === id);
|
||||
try { if (!source) throw new Error('有零件原文件尚未载入,请刷新资源列表'); loaded.set(id, await fetchModel(source)); }
|
||||
catch (cause) { if (!disposed) errors.push(errorText(cause)); }
|
||||
}
|
||||
}));
|
||||
if (disposed) return;
|
||||
next.assembly.parts.forEach((p) => {
|
||||
const group = new THREE.Group(); group.userData.partId = p.id;
|
||||
const template = loaded.get(p.assetId); if (template) group.add(clone(template));
|
||||
groups.set(p.id, group);
|
||||
});
|
||||
const next = latest.current;
|
||||
next.assembly.parts.forEach(p => { const group = new THREE.Group(); group.userData.partId = p.id; groups.set(p.id, group); });
|
||||
// 层级预先由编辑器校验;额外防止损坏的草稿产生场景环。
|
||||
next.assembly.parts.forEach((p) => {
|
||||
const seen = new Set([p.id]); let parentId = p.parentId, valid = true;
|
||||
@@ -203,28 +279,50 @@ export default function AssemblyViewport(props: Props) {
|
||||
const parent = valid && p.parentId ? groups.get(p.parentId) : null;
|
||||
(parent ?? models).add(groups.get(p.id)!);
|
||||
});
|
||||
if (next.reference) {
|
||||
try { const ref = loaded.get(next.reference.asset.assetId) ?? await fetchModel(next.reference); if (!disposed) referenceGroup.add(clone(ref)); }
|
||||
catch (cause) { if (!disposed) errors.push(`参考整机:${errorText(cause)}`); }
|
||||
}
|
||||
if (disposed) return;
|
||||
update(latest.current); fit(); setLoading(false); setProblem(errors.join(';'));
|
||||
const failed = new Set<string>();
|
||||
let loadingRun = false, firstModel = true, fittedScope: string | undefined;
|
||||
const loadVisible = async () => {
|
||||
if (loadingRun || disposed) return;
|
||||
loadingRun = true;
|
||||
let added = false;
|
||||
try {
|
||||
while (!disposed) {
|
||||
const current = latest.current;
|
||||
const visible = new Set(current.visibleParts ?? current.assembly.parts.map(p => p.id));
|
||||
const required = [...new Set([...current.assembly.parts.filter(p => visible.has(p.id)).map(p => p.assetId), ...(!current.stageOffset && current.preview !== null && current.preview >= 0 ? (current.enteringParts ?? []).flatMap(id => { const toolId = current.assembly.parts.find(p => p.id === id)?.installation?.toolId; const tool = current.assembly.tools?.find(t => t.id === toolId); return tool ? [tool.assetId] : []; }) : [])])];
|
||||
const queue = required.filter(id => !loaded.has(id) && !failed.has(id)).slice(0, 2);
|
||||
if (!queue.length) break;
|
||||
setLoading(true);
|
||||
await Promise.all(queue.map(async id => {
|
||||
try {
|
||||
const source = current.sources.find(s => s.asset.assetId === id);
|
||||
if (!source) throw new Error('有零件原文件尚未载入,请重新打开编辑器。');
|
||||
const template = await fetchModel(source); loaded.set(id, template); added = true;
|
||||
if (disposed) return;
|
||||
current.assembly.parts.filter(p => p.assetId === id).forEach(p => { const instance = clone(template); groups.get(p.id)!.add(instance); instances.set(p.id, instance); });
|
||||
} catch (cause) { if (!disposed) { failed.add(id); setProblem(errorText(cause)); } }
|
||||
}));
|
||||
if (!disposed) { update(latest.current); if (firstModel || fittedScope !== latest.current.focusKey) { fit(); firstModel = false; fittedScope = latest.current.focusKey; } }
|
||||
}
|
||||
} finally { loadingRun = false; if (!disposed) { if (added) fit(); setLoading(false); } }
|
||||
};
|
||||
loadModels().catch((cause) => { if (!disposed) { setLoading(false); setProblem(errorText(cause)); } });
|
||||
ensureVisible = () => { void loadVisible(); };
|
||||
update(next); fit(); ensureVisible();
|
||||
return () => {
|
||||
disposed = true; abort.abort(); api.current = undefined; cancelAnimationFrame(frame); observer.disconnect();
|
||||
renderer.domElement.removeEventListener('pointerdown', pointerDown); renderer.domElement.removeEventListener('pointerup', pointerUp);
|
||||
clearBoxes(); transform.dispose(); controls.dispose(); disposeObjects([...templates, axes]); environment.dispose(); renderer.dispose(); renderer.forceContextLoss(); renderer.domElement.remove();
|
||||
screwMotions.forEach(m => m.transition.dispose()); marker.removeFromParent();
|
||||
clearBoxes(); transform.dispose(); controls.dispose(); draco.dispose(); disposeObjects([...templates, axes, grid, marker]); environment.dispose(); renderer.dispose(); renderer.forceContextLoss(); renderer.domElement.remove();
|
||||
};
|
||||
}, [topology, props.sources, props.reference]);
|
||||
|
||||
useEffect(() => { api.current?.update(props); }, [props.assembly, props.selected, props.preview, props.replay, props.referenceVisible, props.tool]);
|
||||
useEffect(() => { api.current?.fit(); }, [props.fit]);
|
||||
useEffect(() => { api.current?.update(props); }, [props.assembly, props.selected, props.preview, props.replay, props.referenceVisible, props.tool, props.visibleParts, props.enteringParts, props.stageOffset, props.marker]);
|
||||
useEffect(() => { props.onLoadingChange?.(loading); }, [loading, props.onLoadingChange]);
|
||||
useEffect(() => { api.current?.fit(); }, [props.fit, props.focusKey]);
|
||||
return <div className="assembly-viewport-wrap">
|
||||
<div ref={container} className="assembly-viewport" />
|
||||
{loading && <div className="assembly-loading"><Spin tip="正在载入原始模型…"><span /></Spin></div>}
|
||||
{problem && <Alert className="assembly-preview-problem" type="warning" showIcon message={problem} />}
|
||||
<div className="assembly-axis-key"><span>X</span><span>Y</span><span>Z</span></div>
|
||||
<div className="assembly-canvas-hint">拖动旋转 · 滚轮缩放 · 点击选零件 · Shift 多选</div>
|
||||
<div className="assembly-canvas-hint">{props.hint ?? '拖动旋转 · 滚轮缩放'}</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ import WalkingUploadGuide, { type WalkingUploadContext } from './WalkingUploadGu
|
||||
import { resourceProblems } from '@/api/project-resources';
|
||||
import { walkingProfiles } from '@/utils/walkingUpload';
|
||||
|
||||
// 暂停可视化装配入口;恢复时关闭此开关,原有可用性检查继续生效。
|
||||
const assemblyEditorPaused = true;
|
||||
|
||||
const sections = {
|
||||
whole: {
|
||||
title: '整机模型', icon: <RobotOutlined />, number: '01',
|
||||
@@ -39,7 +42,9 @@ const sections = {
|
||||
},
|
||||
};
|
||||
|
||||
export default function ModelAssetUpload({ value, onChange, disabled = false, busy = false, onUpload, onEditAssembly, renderCurrent, configured = {}, mode = 'manage', walking, hasMoreAssets = false, renderWalking, resourceProtocol = false, autoUpload = false, retrySections = {} }: {
|
||||
export default function ModelAssetUpload({ value, onChange, disabled = false, busy = false, onUpload, onEditAssembly, renderCurrent, configured = {}, mode = 'manage', walking, hasMoreAssets = false, renderWalking, resourceProtocol = false, autoUpload = false, retrySections = {}, assemblyLoading = false, assemblyProgress }: {
|
||||
assemblyLoading?: boolean;
|
||||
assemblyProgress?: string;
|
||||
resourceProtocol?: boolean;
|
||||
autoUpload?: boolean;
|
||||
retrySections?: Partial<Record<ExperienceFileSection, boolean>>;
|
||||
@@ -115,10 +120,11 @@ export default function ModelAssetUpload({ value, onChange, disabled = false, bu
|
||||
<Space wrap>
|
||||
{section === 'whole' && picker(section, 'whole-glb', '选择整机 GLB')}
|
||||
{section === 'parts' && picker(section, 'part-glb', '选择零件文件夹', true)}
|
||||
{section === 'assembly' && <Button type="primary" aria-label="制作装配流程" icon={<BuildOutlined />} disabled={busy || value.parts.checking || !!value.parts.problems.length || !hasParts || !onEditAssembly} onClick={onEditAssembly}>制作装配流程</Button>}
|
||||
{section === 'assembly' && <Button type="primary" aria-label="制作装配流程" loading={assemblyLoading} icon={<BuildOutlined />} disabled={assemblyEditorPaused || resourceProtocol && disabled || busy || value.parts.checking || !!value.parts.problems.length || !hasParts || !onEditAssembly} onClick={onEditAssembly}>{assemblyLoading ? '正在载入装配流程' : resourceProtocol && configured.assembly ? '编辑装配流程' : '制作装配流程'}</Button>}
|
||||
</Space>
|
||||
{section === 'walking' && (renderWalking ? renderWalking(<><WalkingUploadGuide picker={picker(section, 'walking-zip', '选择行走资源 ZIP')} selection={selection} mode={mode} actions={selectionContent} {...walking} />{renderCurrent?.(section)}</>) : <WalkingUploadGuide picker={picker(section, 'walking-zip', '选择行走资源 ZIP')} selection={selection} mode={mode} actions={selectionContent} {...walking} />)}
|
||||
<Typography.Text type="secondary">{resourceProtocol && section === 'parts' && mode === 'manage' ? '文件夹上传会替换整个零件列表;添加一个零件请使用下方“上传单个零件”。' : info.hint}</Typography.Text>
|
||||
{section === 'assembly' && assemblyProgress && <Typography.Text role="status">{assemblyProgress}</Typography.Text>}
|
||||
<Typography.Text type="secondary">{section === 'assembly' && resourceProtocol && mode === 'manage' ? configured.assembly ? '点击“编辑装配流程”读取已上传的零件和现有步骤,无需重新选择文件夹。修改并保存后才会更新。' : '直接使用上方已上传的零件:选中一组零件,设置方向并添加步骤,JSON 由系统生成。' : resourceProtocol && section === 'parts' && mode === 'manage' ? '文件夹上传会替换整个零件列表;添加一个零件请使用下方“上传单个零件”。' : info.hint}</Typography.Text>
|
||||
{section === 'assembly' && <Collapse size="small" items={[{ key: 'import', label: '高级导入(JSON)', children: <Space direction="vertical">
|
||||
<Typography.Text type="secondary">仅导入装配步骤 JSON。引用的零件需先在上方“零件模型”通过文件夹上传。</Typography.Text>
|
||||
{picker(section, 'assembly-manifest', '选择拼装步骤 JSON')}
|
||||
|
||||
@@ -4,7 +4,8 @@ import type { ProjectView, SelectedFile } from '@/api/types';
|
||||
import { getProject } from '@/api';
|
||||
import { clearProjectResource, uploadProjectResource, type ResourceBatch, type ResourceType } from '@/api/project-resources';
|
||||
import { emptyExperienceFiles, experienceFileSections, peekExperienceFiles, releaseExperienceFiles, type ExperienceFileSection } from '@/utils/experienceFiles';
|
||||
import { assemblyManifest, peekAssemblySession, prepareAssemblySession, releaseAssemblySession, type AssemblySession } from '@/utils/assemblyEditor';
|
||||
import { assemblyManifest, peekAssemblySession, releaseAssemblySession, type AssemblySession } from '@/utils/assemblyEditor';
|
||||
import { prepareBoundAssemblySession } from '@/utils/boundAssembly';
|
||||
import { peekWalkingSession, releaseWalkingSession } from '@/utils/walkingForm';
|
||||
import { safeExperienceUrl } from '@/utils/modelAssets';
|
||||
import { errorText, formatSize, isAbort } from '@/utils/format';
|
||||
@@ -26,6 +27,7 @@ export default function ProjectResourcesPanel({ project, disabled, onUpdate }: {
|
||||
const [plan, setPlan] = useState<AssemblySession | null>(() => peekAssemblySession(code) ?? null);
|
||||
const generatedAssembly = useRef<File | undefined>(plan ? files.assembly.selected[0]?.file : undefined);
|
||||
const [editor, setEditor] = useState<AssemblySession | null>(null);
|
||||
const [openingEditor, setOpeningEditor] = useState(false);
|
||||
const [busy, setBusy] = useState(false), [error, setError] = useState(''), [progress, setProgress] = useState('');
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const partJob = useRef<PartChangeJob>();
|
||||
@@ -71,7 +73,7 @@ export default function ProjectResourcesPanel({ project, disabled, onUpdate }: {
|
||||
const next = experienceFileSections.find(section => files[section].selected.length && !files[section].checking && !files[section].problems.length && attempted.current[section] !== files[section].selected);
|
||||
if (next) void upload(next);
|
||||
}, [files, busy, uncertain, partRetry, disabled, project.repoStatus]);
|
||||
const refresh = () => perform(async signal => { const next = await getProject(code); signal.throwIfAborted(); onUpdate(next.project); setUncertain(false); partJob.current = undefined; setPartRetry(false); message.success('已刷新当前绑定,可核对后继续操作'); });
|
||||
const refresh = () => perform(async signal => { const next = await getProject(code); signal.throwIfAborted(); onUpdate(next.project); setPlan(null); setUncertain(false); partJob.current = undefined; setPartRetry(false); message.success('已刷新当前绑定,可核对后继续操作'); });
|
||||
const changePart = async (change?: PartChange) => {
|
||||
if (running.current || disabled || uncertain || project.repoStatus !== 'READY') return;
|
||||
if (change) partJob.current = { project, change, retained: new Map() };
|
||||
@@ -95,29 +97,22 @@ export default function ProjectResourcesPanel({ project, disabled, onUpdate }: {
|
||||
try {
|
||||
await clearProjectResource(code, resourceTypes[section], signal);
|
||||
const next = await getProject(code); signal.throwIfAborted(); onUpdate(next.project);
|
||||
if (section === 'parts' || section === 'assembly') setPlan(null);
|
||||
message.success('已清除绑定,OSS 原文件保留');
|
||||
} catch (cause) { setUncertain(true); throw cause; }
|
||||
});
|
||||
const openEditor = () => perform(async signal => {
|
||||
let sourceFiles = files;
|
||||
if (!files.parts.selected.length && project.modelPartsFiles?.length) {
|
||||
const selected: SelectedFile[] = [];
|
||||
for (const resource of project.modelPartsFiles) {
|
||||
const url = safeExperienceUrl(resource.url); if (!url) throw new Error('零件下载地址无效');
|
||||
const response = await fetch(url, { signal }); if (!response.ok) throw new Error(`零件下载失败:${resource.relativePath} (${response.status})`);
|
||||
const blob = await response.blob(); if (blob.size !== resource.sizeBytes) throw new Error(`零件大小与绑定记录不一致:${resource.relativePath}`);
|
||||
selected.push({ relativePath: resource.relativePath, file: new File([blob], resource.relativePath.split('/').pop()!, { type: 'model/gltf-binary' }) });
|
||||
}
|
||||
sourceFiles = { ...files, parts: { ...files.parts, selected, problems: [], checking: false } };
|
||||
|
||||
}
|
||||
const session = await prepareAssemblySession(plan, plan?.assembly ?? null, [], sourceFiles); signal.throwIfAborted(); setEditor(session);
|
||||
});
|
||||
const openEditor = async () => {
|
||||
setOpeningEditor(true);
|
||||
try { await perform(async signal => {
|
||||
const session = await prepareBoundAssemblySession(project, files, plan, signal, setProgress);
|
||||
signal.throwIfAborted(); setEditor(session);
|
||||
}); } finally { setOpeningEditor(false); }
|
||||
};
|
||||
const current = (section: ExperienceFileSection) => {
|
||||
const url = binding(project, section);
|
||||
const list = section === 'parts' ? project.modelPartsFiles : section === 'walking' ? project.walkingResourcesFiles : undefined;
|
||||
return <Space direction="vertical" style={{ width: '100%' }}>
|
||||
{section === 'assembly' && plan && <Typography.Text type="success">已生成 {plan.assembly.steps.length} 个步骤,自动上传成功后生效。</Typography.Text>}
|
||||
{section === 'assembly' && plan && <Typography.Text type="success">已生成 {plan.assembly.steps.length} 个总装步骤{plan.assembly.componentLibrary ? `、${plan.assembly.componentLibrary.components.length} 个独立组件` : ''},自动上传成功后生效。</Typography.Text>}
|
||||
<Typography.Text type={url ? 'success' : 'secondary'}>{url ? '当前已绑定' : '尚未绑定'}</Typography.Text>
|
||||
{section === 'parts' && <PartsResourceList files={project.modelPartsFiles ?? []} disabled={busy || uncertain || partRetry || disabled || project.repoStatus !== 'READY' || !!files.parts.selected.length} onChange={changePart} />}
|
||||
{url && <>{safeExperienceUrl(url) && <Typography.Link href={url} target="_blank" rel="noreferrer">{list ? '资源目录地址' : '查看当前文件'}</Typography.Link>}
|
||||
@@ -132,17 +127,17 @@ export default function ProjectResourcesPanel({ project, disabled, onUpdate }: {
|
||||
{partRetry && !uncertain && <Space><Button disabled={busy} onClick={() => { void changePart(); }}>重试本次零件操作</Button><Button disabled={busy} onClick={() => { partJob.current = undefined; setPartRetry(false); setError(''); }}>取消本次零件操作</Button></Space>}
|
||||
{uncertain && <Alert type="warning" message="确认或清除结果需核对,请先刷新当前绑定;所选文件已保留,不会自动重复提交。" />}
|
||||
<Button loading={busy} disabled={busy} onClick={refresh}>刷新资源绑定</Button>
|
||||
<ModelAssetUpload resourceProtocol autoUpload retrySections={failedSections} value={files} onChange={setFiles} busy={busy || uncertain || partRetry} disabled={disabled || project.repoStatus !== 'READY' || uncertain}
|
||||
<ModelAssetUpload resourceProtocol autoUpload assemblyLoading={openingEditor} assemblyProgress={openingEditor ? progress : undefined} retrySections={failedSections} value={files} onChange={setFiles} busy={busy || uncertain || partRetry} disabled={disabled || project.repoStatus !== 'READY' || uncertain}
|
||||
configured={{ whole: !!project.modelGlbUrl, parts: !!project.modelPartsBaseUrl, assembly: !!project.assemblyJsonUrl || !!plan, walking: !!project.walkingResourcesBaseUrl }}
|
||||
onUpload={upload} onEditAssembly={openEditor} renderCurrent={current}
|
||||
renderWalking={() => <><WalkingFolderUpload autoUpload retry={failedSections.walking} selected={files.walking.selected} busy={busy || uncertain} disabled={disabled || project.repoStatus !== 'READY'} onChange={selected => setFiles(old => ({ ...old, walking: { ...old.walking, selected } }))} onUpload={() => { void upload('walking'); }} />{current('walking')}</>}
|
||||
/>
|
||||
{editor && <Suspense fallback={<Alert message="正在载入装配编辑器" />}><AssemblyEditor saveHint="保存后自动生成 JSON 并上传,绑定成功后更新前台。" initial={editor} onClose={() => setEditor(null)} onSave={session => {
|
||||
const json = assemblyManifest(session.assembly, session.sources);
|
||||
const json = assemblyManifest(session.assembly, session.sources, session.manifest);
|
||||
const file = new File([JSON.stringify(json, null, 2)], 'assembly.json', { type: 'application/json' });
|
||||
generatedAssembly.current = file; setPlan(session); setEditor(null);
|
||||
setFiles(old => ({ ...old, assembly: { ...old.assembly, selected: [{ file, relativePath: file.name }], problems: [] } }));
|
||||
message.success('已生成步骤 JSON,正在自动上传');
|
||||
message.success(session.assembly.componentLibrary ? '已生成组件库与总装配置,正在自动上传' : '已生成步骤 JSON,正在自动上传');
|
||||
}} /></Suspense>}
|
||||
</Space>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Button, InputNumber, Modal, Space, Typography } from 'antd';
|
||||
import type { Vector3 } from '@/api/experience-types';
|
||||
import type { Assembly, AssemblySource } from '@/utils/assemblyEditor';
|
||||
import AssemblyViewport from './AssemblyViewport';
|
||||
|
||||
export default function SurfaceCalibration({ source, mode, initial, depth = 0, onSave, onClose }: {
|
||||
source: AssemblySource; mode: 'tool' | 'screw'; initial?: { position: Vector3; axis: Vector3 }; depth?: number;
|
||||
onSave: (value: { position: Vector3; axis: Vector3 }) => void; onClose: () => void;
|
||||
}) {
|
||||
const [point, setPoint] = useState<Vector3 | null>(initial?.position ?? null), [axis, setAxis] = useState<Vector3>(initial?.axis ?? [0, 0, -1]);
|
||||
const [fit, setFit] = useState(0);
|
||||
const assembly = useMemo<Assembly>(() => ({ title: '工作端校准', enabled: true, unit: 'meter', displayQuaternion: [0, 0, 0, 1], referenceAssetId: null, parts: [{ id: 'calibration', name: '校准模型', assetId: source.asset.assetId, parentId: null, position: [0, 0, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [0, 0, 0] }], steps: [] }), [source]);
|
||||
const sources = useMemo(() => [source], [source]);
|
||||
const marker = useMemo(() => point ? { partId: 'calibration', position: point, axis } : undefined, [point, axis]);
|
||||
return <Modal open className="assembly-surface-modal" title={mode === 'tool' ? '校准工具工作端' : '校准螺丝头插入点'} width={820} onCancel={onClose} footer={<Space><Button onClick={() => setFit(n => n + 1)}>重置视角</Button><Button onClick={onClose}>取消</Button><Button type="primary" disabled={!point} onClick={() => point && onSave({ position: point, axis })}>使用此{mode === 'tool' ? '工作端' : '插入点'}</Button></Space>}>
|
||||
<Typography.Paragraph type="secondary">{source.asset.relativePath}。{mode === 'tool' ? '旋转模型,点击工具工作端的端面中心。绿箭头应从工具尖端指向螺孔内;该工具的后续步骤共用这次校准。' : '点击螺丝头的孔口中心。绿箭头应沿螺丝杆指向孔内,点击后按设置的深度生成插入点。'}拖动可旋转,滚轮缩放。</Typography.Paragraph>
|
||||
<div className="assembly-calibration-canvas"><AssemblyViewport assembly={assembly} sources={sources} selected={[]} preview={null} replay={0} referenceVisible={false} tool="select" fit={fit} visibleParts={['calibration']} onPick={() => {}} onTransform={() => {}} marker={marker} onSurfacePick={pick => {
|
||||
const direction = pick.normal.map(v => mode === 'screw' ? -v : v) as Vector3;
|
||||
setAxis(direction); setPoint(pick.position.map((v, i) => v + direction[i] * (mode === 'screw' ? depth : 0)) as Vector3);
|
||||
}} /></div>
|
||||
<div className="assembly-calibration-fields"><strong>{point ? '已选中,可微调坐标(毫米)' : '请在模型上点选工作端'}</strong><Space wrap>{(['X', 'Y', 'Z'] as const).map((label, i) => <InputNumber key={label} aria-label={`校准点 ${label}(毫米)`} addonBefore={label} value={point ? point[i] * 1000 : null} precision={4} onChange={value => { if (value !== null && Number.isFinite(value)) setPoint(old => (old ?? [0, 0, 0]).map((v, j) => i === j ? value / 1000 : v) as Vector3); }} style={{ width: 175 }} />)}</Space>
|
||||
<div className="assembly-calibration-axis"><span>工作方向</span>{(['x+', 'y+', 'z+', 'x-', 'y-', 'z-'] as const).map(value => <Button key={value} size="small" onClick={() => { const v: Vector3 = [0, 0, 0]; v[['x', 'y', 'z'].indexOf(value[0])] = value[1] === '+' ? 1 : -1; setAxis(v); }}>{value[1] === '-' ? '−' : ''}{value[0].toUpperCase()}</Button>)}<Button size="small" onClick={() => setAxis(v => v.map(x => -x) as Vector3)}>反转方向</Button></div>
|
||||
<Typography.Text type="secondary">当前方向:[{axis.map(v => v.toFixed(4)).join(', ')}];单位和原 GLB 保持一致。</Typography.Text>
|
||||
</div>
|
||||
</Modal>;
|
||||
}
|
||||
@@ -1,46 +1,213 @@
|
||||
.assembly-editor-modal .ant-modal-body { max-height: calc(100vh - 170px); overflow: auto; }
|
||||
.assembly-editor-guide { display: flex; gap: 14px; align-items: center; flex-wrap: wrap; padding: 10px 16px; color: #5945cb; background: #f3f0ff; border-radius: 10px; font-size: 13px; }
|
||||
.assembly-editor-guide span { color: #b5a7e9; }
|
||||
.assembly-editor-toolbar { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; margin: 14px 0; }
|
||||
.assembly-editor-layout { display: grid; grid-template-columns: 240px minmax(350px, 1fr) 270px; gap: 16px; align-items: start; }
|
||||
.assembly-pane-title { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 12px; }
|
||||
.assembly-part-sidebar, .assembly-step-sidebar { min-width: 0; padding: 14px; border: 1px solid #e9eaf2; border-radius: 10px; background: #fafbfe; }
|
||||
.assembly-part-actions { margin: 10px 0; }
|
||||
.assembly-part-list { max-height: 340px; overflow: auto; }
|
||||
.assembly-part-row { display: flex; align-items: center; gap: 7px; padding: 8px 6px; border-radius: 6px; }
|
||||
.assembly-part-row.is-selected { background: #eee9ff; }
|
||||
.assembly-part-row button { min-width: 0; flex: 1; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.assembly-part-row button, .assembly-group-tags button, .assembly-step-heading button { border: 0; background: transparent; color: inherit; cursor: pointer; padding: 0; font: inherit; }
|
||||
.assembly-part-row > span { font-size: 11px; color: #8790a6; flex-shrink: 0; }
|
||||
.assembly-groups { margin-top: 16px; padding-top: 14px; border-top: 1px solid #e5e8f0; }
|
||||
.assembly-groups .ant-typography { font-size: 12px; margin: 4px 0 8px; }
|
||||
.assembly-group-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
|
||||
.assembly-editor-center { min-width: 0; }
|
||||
.assembly-viewport-wrap { position: relative; border: 1px solid #e3e7f2; overflow: hidden; border-radius: 12px; background: #f1f4fa; }
|
||||
.assembly-viewport { height: clamp(300px, 40vh, 520px); width: 100%; }
|
||||
.assembly-editor-modal { padding-bottom: 0; }
|
||||
.assembly-editor-modal .ant-modal-content { height: calc(100dvh - 32px); max-height: 1100px; box-sizing: border-box; display: flex; flex-direction: column; padding: 18px 20px 14px; background: #181c22; border: 1px solid #343b45; border-radius: 20px; box-shadow: 0 24px 100px #0009; }
|
||||
.assembly-editor-modal .ant-modal-header { background: transparent; margin-bottom: 10px; flex: none; }
|
||||
.assembly-editor-modal .ant-modal-body { flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
||||
.assembly-editor-modal .ant-modal-footer { flex: none; margin-top: 10px; }
|
||||
.assembly-editor-modal .ant-modal-title { color: #f0f2f5; }
|
||||
.assembly-editor-modal .ant-modal-close { color: #aeb7c3; top: 16px; right: 16px; border-radius: 50%; border: 1px solid #3c424c; }
|
||||
.assembly-modal-title { display: flex; align-items: center; gap: 12px; padding-right: 42px; }
|
||||
.assembly-modal-title > span { font-size: 18px; font-weight: 600; }
|
||||
.assembly-modal-title .ant-tag { color: #afbac7; background: #232930; border: 0; font-size: 11px; }
|
||||
.assembly-editor-toolbar { flex: none; display: flex; justify-content: space-between; align-items: center; gap: 20px; margin-bottom: 12px; }
|
||||
.assembly-editor-toolbar > .ant-input { width: min(500px, 45%); padding-left: 0; font-size: 13px; color: #aeb8c6; }
|
||||
.assembly-toolbar-actions { display: flex; align-items: center; gap: 6px; }
|
||||
.assembly-editor-modal .ant-segmented { background: #0e1217; }
|
||||
.assembly-editor-modal .ant-segmented-item-selected { background: #30382c; color: #d5ff93; }
|
||||
.assembly-editor-layout { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 1fr) 300px; gap: 14px; }
|
||||
.assembly-editor-center { position: relative; display: flex; flex-direction: column; gap: 10px; min-width: 0; min-height: 0; }
|
||||
.assembly-viewport-wrap { position: relative; overflow: hidden; }
|
||||
.assembly-viewport { height: clamp(500px, calc(100vh - 260px), 850px); width: 100%; }
|
||||
.assembly-viewport canvas { display: block; width: 100%; height: 100%; touch-action: none; }
|
||||
.assembly-canvas-hint { position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%); white-space: nowrap; font-size: 11px; color: #526078; padding: 5px 10px; border-radius: 20px; background: #ffffffdf; pointer-events: none; }
|
||||
.assembly-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; pointer-events: none; background: #f1f4fa88; }
|
||||
.assembly-canvas-hint { position: absolute; top: 16px; left: 18px; color: #84909f; font-size: 11px; pointer-events: none; }
|
||||
.assembly-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; pointer-events: none; background: #20262d99; z-index: 3; }
|
||||
.assembly-loading .ant-spin { min-width: 180px; }
|
||||
.assembly-preview-problem { position: absolute; top: 10px; left: 10px; right: 10px; max-height: 130px; overflow: auto; font-size: 12px; }
|
||||
.assembly-preview-bar { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 10px 0; }
|
||||
.assembly-preview-bar .ant-tag { white-space: normal; }
|
||||
.assembly-step-settings { border: 1px solid #e6e1fa; border-radius: 10px; padding: 14px; margin: 12px 0; background: #fcfbff; }
|
||||
.assembly-step-settings .ant-typography { font-size: 12px; }
|
||||
.assembly-step-list { padding: 0; margin: 0; list-style: none; max-height: 530px; overflow: auto; }
|
||||
.assembly-step-list > li { padding: 10px; margin-bottom: 10px; border: 1px solid #e3e6ef; background: #fff; border-radius: 8px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.assembly-step-list > li.is-active { border-color: #8d77f1; background: #fbfaff; }
|
||||
.assembly-step-heading { display: flex; align-items: center; gap: 6px; }
|
||||
.assembly-step-heading > span { color: #9ba2b1; cursor: grab; }
|
||||
.assembly-step-heading button { display: flex; align-items: center; gap: 8px; text-align: left; overflow-wrap: anywhere; }
|
||||
.assembly-step-heading b { border-radius: 6px; background: #f0ecff; color: #6c4ae4; min-width: 24px; text-align: center; font-size: 12px; line-height: 24px; }
|
||||
.assembly-step-summary { color: #8790a6; font-size: 12px; }
|
||||
.assembly-step-sidebar .ant-collapse { margin-top: 12px; }
|
||||
.assembly-problems { padding-left: 16px; margin: 6px 0; font-size: 12px; }
|
||||
.assembly-editor-footer { display: flex; justify-content: space-between; align-items: center; gap: 16px; text-align: left; }
|
||||
.assembly-editor-footer .ant-typography { font-size: 12px; }
|
||||
@media (max-width: 1150px) { .assembly-editor-layout { grid-template-columns: 210px minmax(300px, 1fr); } .assembly-step-sidebar { grid-column: 1 / -1; } .assembly-step-list { display: flex; gap: 10px; } .assembly-step-list > li { min-width: 210px; max-width: 250px; } }
|
||||
@media (max-width: 720px) { .assembly-editor-layout { display: flex; flex-direction: column; } .assembly-part-sidebar, .assembly-editor-center, .assembly-step-sidebar { width: 100%; box-sizing: border-box; } .assembly-part-list { max-height: 170px; } .assembly-editor-footer { flex-direction: column; align-items: stretch; } .assembly-editor-guide { font-size: 11px; gap: 6px; } }
|
||||
.assembly-axis-key { position: absolute; top: 12px; right: 12px; display: flex; gap: 8px; font-size: 12px; font-weight: 700; pointer-events: none; }
|
||||
.assembly-axis-key span { background: #ffffffd9; border-radius: 4px; padding: 2px 7px; }
|
||||
.assembly-axis-key span:nth-child(1) { color: #d93838; }.assembly-axis-key span:nth-child(2) { color: #389b44; }.assembly-axis-key span:nth-child(3) { color: #3a6dde; }
|
||||
.assembly-preview-problem { position: absolute; top: 44px; left: 12px; right: 12px; max-height: 130px; overflow: auto; font-size: 12px; z-index: 4; }
|
||||
.assembly-empty-canvas { position: absolute; inset: 42px 0 28px; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 12px; pointer-events: none; color: #c6cdd6; }
|
||||
.assembly-empty-canvas > span { font-size: 20px; font-weight: 500; }
|
||||
.assembly-empty-canvas small { max-width: 80%; text-align: center; color: #8d98a8; font-size: 12px; line-height: 1.8; }
|
||||
.assembly-playback { flex: none; display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; column-gap: 20px; padding: 9px 12px 2px; border-radius: 12px; background: #181d25d9; border: 1px solid #3a424c80; }
|
||||
.assembly-progress-line { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.assembly-progress-caption { display: flex; flex-direction: column; align-items: center; min-width: 0; gap: 4px; color: #e0e6ed; }
|
||||
.assembly-progress-caption small { color: #91a07e; font-size: 10px; }
|
||||
.assembly-progress-caption > span { max-width: 350px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 12px; }
|
||||
.assembly-preview-actions { grid-column: 2; grid-row: 1; display: flex; justify-content: center; gap: 6px; flex-wrap: wrap; }
|
||||
.assembly-preview-actions .ant-btn { font-size: 11px; height: 30px; padding-inline: 10px; border-radius: 20px; color: #c5ced9; background: #1c222a; }
|
||||
.assembly-playback .ant-slider { grid-column: 1 / -1; grid-row: 2; margin: 10px 5px 6px; }
|
||||
.assembly-workbench { min-width: 0; min-height: 0; display: flex; flex-direction: column; border: 1px solid #303741; border-radius: 14px; padding: 0 15px 10px; background: #13171d; overflow: hidden; }
|
||||
.assembly-workbench .ant-tabs { min-height: 0; flex: 1; display: flex; flex-direction: column; }
|
||||
.assembly-workbench .ant-tabs-content-holder { min-height: 0; overflow: hidden; }
|
||||
.assembly-workbench .ant-tabs-content { height: 100%; }
|
||||
.assembly-workbench .ant-tabs-tabpane-active { display: flex; flex-direction: column; height: 100%; min-height: 0; overflow: hidden; }
|
||||
.assembly-workbench .ant-tabs-nav, .assembly-workbench .assembly-more, .assembly-workbench > .ant-alert { flex: none; }
|
||||
.assembly-workbench .ant-tabs-tabpane-active > :not(.assembly-part-list):not(.assembly-step-list):not(.assembly-components-panel) { flex-shrink: 0; }
|
||||
.assembly-workbench .ant-tabs-tab { padding: 14px 0; font-size: 12px; }
|
||||
.assembly-workbench .ant-tabs-nav { margin-bottom: 12px; }
|
||||
.assembly-workbench .ant-input-affix-wrapper, .assembly-workbench .ant-input-search-button { background: #1c222a; border-color: #343d49; }
|
||||
.assembly-list-caption { display: flex; align-items: center; justify-content: space-between; margin: 12px 0 8px; color: #7f8a99; font-size: 11px; }
|
||||
.assembly-part-filter { margin-top: 10px; font-size: 11px; }
|
||||
.assembly-part-list { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding-right: 3px; }
|
||||
.assembly-part-row { width: 100%; display: flex; align-items: center; gap: 10px; padding: 11px 7px; border: 0; border-bottom: 1px solid #262d36; background: transparent; color: #cbd2dc; text-align: left; cursor: pointer; font: inherit; border-radius: 6px; }
|
||||
.assembly-part-row:hover { background: #252c35; }
|
||||
.assembly-part-row.is-active { background: #2c3624; }
|
||||
.assembly-part-state { height: 26px; min-width: 26px; border: 1px solid #3d4653; border-radius: 7px; display: grid; place-items: center; color: #8f9aaa; font-size: 11px; }
|
||||
.is-installed .assembly-part-state { color: #c5ff59; border-color: #5d7544; background: #253020; }
|
||||
.assembly-part-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
|
||||
.assembly-part-name small { display: block; color: #687585; font-size: 10px; margin-top: 5px; }
|
||||
.assembly-part-mark { color: #607044; font-size: 12px; }
|
||||
.assembly-step-list { flex: 1; min-height: 0; padding: 0; margin: 0; list-style: none; overflow: auto; overscroll-behavior: contain; }
|
||||
.assembly-components-panel { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; }
|
||||
.assembly-step-list > li { display: flex; align-items: center; gap: 5px; padding: 10px 3px; border-bottom: 1px solid #282f38; border-radius: 6px; }
|
||||
.assembly-step-list > li.is-active { background: #293322; }
|
||||
.assembly-step-list > li > .anticon { color: #586372; cursor: grab; }
|
||||
.assembly-step-label, .assembly-component-row > button, .assembly-connections button:first-child { border: 0; padding: 0; display: flex; gap: 7px; align-items: center; text-align: left; background: transparent; color: #cbd3dd; font: inherit; cursor: pointer; flex: 1; min-width: 0; font-size: 12px; }
|
||||
.assembly-step-label span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.assembly-step-label small { display: block; margin-top: 5px; color: #7f8d9e; font-size: 10px; }
|
||||
.assembly-step-label .assembly-scene-continue { color: #c1e28c; }
|
||||
.assembly-step-list > li.is-connection { border-left: 2px solid #7eaa48; padding-left: 6px; }
|
||||
.assembly-connection-mark { color: #b5df7b; font-size: 16px; }
|
||||
.assembly-step-label b, .assembly-component-row b { color: #9aae84; font-size: 10px; min-width: 18px; }
|
||||
.assembly-step-list .ant-btn { width: 23px; height: 23px; min-width: 23px; font-size: 10px; }
|
||||
.assembly-current-component { flex: none; padding: 12px 0 10px; border-bottom: 1px solid #303944; display: flex; flex-direction: column; gap: 8px; }
|
||||
.assembly-current-component > div:first-child { display: flex; align-items: center; justify-content: space-between; font-size: 12px; }
|
||||
.assembly-current-component > div:first-child > span { color: #82906f; font-size: 11px; }
|
||||
.assembly-join-entry { flex: none; padding: 10px 0; display: flex; flex-direction: column; gap: 6px; border-bottom: 1px solid #303944; }
|
||||
.assembly-join-entry > span { color: #92a17f; font-size: 10px; line-height: 1.6; }
|
||||
.assembly-side-help { font-size: 11px; line-height: 1.8; }
|
||||
.assembly-component-row { display: flex; gap: 6px; align-items: center; padding: 12px 0; border-bottom: 1px solid #2b333c; }
|
||||
.assembly-component-row small, .assembly-connections small { display: block; margin-top: 5px; color: #748192; font-size: 10px; }
|
||||
.assembly-connection-form { display: flex; flex-direction: column; gap: 10px; margin-top: 20px; }
|
||||
.assembly-connection-form strong { font-size: 12px; }
|
||||
.assembly-connection-form .ant-typography { font-size: 10px; }
|
||||
.assembly-connections > div { display: flex; gap: 8px; margin-top: 12px; align-items: center; }
|
||||
.assembly-workbench .ant-collapse-header { padding-inline: 0 !important; font-size: 11px; color: #84909e !important; }
|
||||
.assembly-workbench .ant-collapse-content-box { padding-inline: 0 !important; }
|
||||
.assembly-editor-footer { display: flex; justify-content: space-between; align-items: center; gap: 15px; text-align: left; padding-top: 6px; }
|
||||
.assembly-editor-footer .ant-typography { color: #7f8a99; font-size: 11px; max-width: 70%; }
|
||||
.assembly-editor-modal .ant-btn-primary { color: #1b2412; font-weight: 600; box-shadow: none; }
|
||||
.assembly-editor-modal .ant-btn-primary:disabled { color: #68725d; }
|
||||
.assembly-workbench ::-webkit-scrollbar { width: 4px; height: 4px; }
|
||||
.assembly-workbench ::-webkit-scrollbar-thumb { background: #3a4553; border-radius: 4px; }
|
||||
@media (max-width: 1050px) { .assembly-editor-layout { grid-template-columns: minmax(0, 1fr) 285px; gap: 12px; } .assembly-editor-toolbar { gap: 10px; } .assembly-toolbar-actions .ant-segmented { font-size: 11px; } }
|
||||
.assembly-join-choices { display: flex; flex-direction: column; gap: 6px; }
|
||||
.assembly-join-choices button { display: flex; align-items: center; gap: 9px; text-align: left; padding: 9px 10px; border: 1px solid #333e4b; border-radius: 8px; color: #b8c3d0; background: #1b222b; cursor: pointer; font-size: 12px; }
|
||||
.assembly-join-choices button[aria-pressed="true"] { background: #293523; border-color: #718e48; color: #d7f8aa; }
|
||||
.assembly-join-choices b { font-size: 10px; min-width: 15px; }
|
||||
.assembly-empty-canvas .assembly-start-over { pointer-events: auto; margin-top: 5px; font-size: 12px; color: #bcd18f; border-color: #566346; background: #242d22; }
|
||||
.assembly-stage { flex: 1; min-height: 0; position: relative; display: flex; flex-direction: column; overflow: hidden; border: 1px solid #363e48; border-radius: 14px; background: radial-gradient(ellipse at 48% 35%, #343c47 0%, #242a32 53%, #1a1f26 100%); }
|
||||
.assembly-stage > .assembly-viewport-wrap { flex: 1; min-height: 0; }
|
||||
.assembly-stage .assembly-viewport { height: 100%; }
|
||||
.assembly-comparison { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, .9fr) minmax(0, 1.1fr); gap: 10px; }
|
||||
.assembly-reference-stage { min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; border: 1px solid #363e48; border-radius: 14px; background: radial-gradient(ellipse at 48% 35%, #303943, #1a1f26); }
|
||||
.assembly-stage-heading { flex: none; min-height: 40px; box-sizing: border-box; display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; padding: 7px 10px; border-bottom: 1px solid #3a424c80; background: #1a2028bb; }
|
||||
.assembly-stage-heading > div:first-child { display: flex; align-items: baseline; gap: 8px; }
|
||||
.assembly-stage-heading strong { font-size: 12px; color: #dce4ee; white-space: nowrap; }
|
||||
.assembly-stage-heading small { font-size: 10px; color: #8998a9; white-space: nowrap; }
|
||||
.assembly-stage-heading-actions { display: flex; align-items: center; gap: 5px; }
|
||||
.assembly-stage-heading-actions .ant-btn { font-size: 10px; height: 25px; padding-inline: 6px; }
|
||||
.assembly-working-indicator { font-size: 10px; color: #c2d7a2; }
|
||||
.assembly-reference-canvas { flex: 1; min-height: 0; position: relative; }
|
||||
.assembly-reference-canvas > .assembly-viewport-wrap { height: 100%; }
|
||||
.assembly-reference-canvas .assembly-viewport { height: 100%; }
|
||||
.assembly-view-caption { flex: none; min-height: 26px; box-sizing: border-box; padding: 6px 10px; color: #8291a1; font-size: 10px; line-height: 1.4; }
|
||||
.assembly-reference-empty { position: absolute; inset: 40px 0 20px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; color: #96a4b4; font-size: 12px; pointer-events: none; }
|
||||
.assembly-reference-empty .ant-btn { pointer-events: auto; }
|
||||
.assembly-reference-controls { width: min(360px, calc(100vw - 72px)); }
|
||||
.assembly-reference-controls-toolbar { display: flex; justify-content: space-between; align-items: center; margin-top: 10px; gap: 8px; }
|
||||
.assembly-reference-controls-toolbar > span { color: #8998a9; font-size: 11px; }
|
||||
.assembly-reference-visibility-list { max-height: min(320px, calc(100dvh - 300px)); min-height: 80px; overflow-y: auto; margin: 8px 0; overscroll-behavior: contain; }
|
||||
.assembly-reference-visibility-list > button { width: 100%; display: flex; align-items: center; gap: 9px; padding: 10px 5px; border: 0; border-bottom: 1px solid #303944; background: transparent; color: #c7d2dd; cursor: pointer; font: inherit; text-align: left; }
|
||||
.assembly-reference-visibility-list > button:hover { background: #2a333d; }
|
||||
.assembly-reference-visibility-list > button > span:first-child { color: #c5e892; }
|
||||
.assembly-reference-visibility-list > button > span.is-hidden { color: #66717f; }
|
||||
.assembly-reference-visibility-list > button > span:nth-child(2) { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
|
||||
.assembly-reference-visibility-list > button > small { font-size: 10px; color: #8491a0; }
|
||||
.assembly-reference-batch { display: flex; align-items: center; gap: 8px; padding-top: 8px; border-top: 1px solid #303944; }
|
||||
.assembly-reference-batch > span { margin-left: auto; color: #8491a0; font-size: 10px; }
|
||||
.assembly-toolbar-actions .assembly-history-button { min-width: 76px; height: 34px; background: #2b343e; border-color: #586673; color: #eef4e8; font-size: 12px; box-shadow: 0 2px 5px #0003; }
|
||||
.assembly-toolbar-actions .assembly-history-button:disabled { opacity: 1; background: #20262e; border-color: #37424e; color: #7f8d9e; }
|
||||
.assembly-define-component { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 10px; margin: 4px 0 8px; border: 1px solid #4b6240; background: #242e20; border-radius: 8px; font-size: 11px; color: #c5d5b4; }
|
||||
.assembly-component-members { max-height: 290px; overflow: auto; width: 100%; }
|
||||
.assembly-step-config { flex: none; padding: 10px 12px; border: 1px solid #35404c; border-radius: 12px; background: #171d24; }
|
||||
.assembly-config-heading { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 8px; font-size: 12px; }
|
||||
.assembly-config-heading strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.assembly-config-heading .ant-typography { font-size: 10px; flex-shrink: 0; }
|
||||
.assembly-scene-settings { margin: 0 0 10px; padding-bottom: 8px; border-bottom: 1px solid #303a46; }
|
||||
.assembly-scene-controls { display: flex; align-items: center; gap: 10px; }
|
||||
.assembly-scene-controls > span { color: #9cabba; font-size: 11px; flex: none; }
|
||||
.assembly-scene-controls > .ant-select { flex: 1; min-width: 0; max-width: 420px; }
|
||||
.assembly-scene-hint { color: #91a67b; font-size: 10px; margin-top: 5px; line-height: 1.5; }
|
||||
.assembly-scene-hint.has-problem { color: #ffb66c; }
|
||||
.assembly-config-basic { display: flex; align-items: flex-end; gap: 20px; flex-wrap: wrap; }
|
||||
.assembly-config-basic label { display: block; margin-bottom: 6px; font-size: 11px; color: #8d9aab; }
|
||||
.assembly-direction-buttons { display: flex; gap: 5px; }
|
||||
.assembly-direction-buttons .ant-btn { width: 37px; height: 29px; font-size: 11px; }
|
||||
.assembly-config-basic .ant-input-number-group-wrapper { width: 150px; }
|
||||
.assembly-use-tool { min-width: 90px; padding-bottom: 4px; margin-left: auto; }
|
||||
.assembly-tool-settings { margin-top: 9px; padding-top: 9px; border-top: 1px solid #303a46; display: flex; flex-direction: column; gap: 8px; }
|
||||
.assembly-tool-selector { display: flex; gap: 8px; }
|
||||
.assembly-tool-selector .ant-select { flex: 1; min-width: 0; }
|
||||
.assembly-tool-settings .assembly-calibration-link { align-self: flex-start; padding: 0; height: 20px; color: #a7ba8e; font-size: 11px; }
|
||||
.assembly-tool-settings .ant-typography { font-size: 11px; }
|
||||
.assembly-calibration-canvas { border: 1px solid #3c4653; border-radius: 12px; overflow: hidden; background: radial-gradient(ellipse, #343d47, #1a2027); }
|
||||
.assembly-calibration-canvas .assembly-viewport { height: 380px; }
|
||||
.assembly-calibration-fields { display: flex; flex-direction: column; gap: 12px; margin-top: 14px; font-size: 12px; }
|
||||
.assembly-calibration-axis { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.assembly-surface-modal .ant-modal-body { max-height: calc(100vh - 200px); overflow: auto; }
|
||||
@media (max-width: 1050px) { .assembly-config-basic { gap: 10px; } .assembly-direction-buttons .ant-btn { width: 31px; } .assembly-use-tool { margin-left: 0; } }
|
||||
.assembly-step-config .assembly-step-name { color: #a9b7c9; font-size: 11px; padding: 0; margin: -4px 0 8px; }
|
||||
@media (max-width: 1250px) { .assembly-playback { column-gap: 10px; } .assembly-preview-actions { gap: 4px; } .assembly-preview-actions .ant-btn { padding-inline: 7px; font-size: 10px; } .assembly-progress-caption > span { max-width: 220px; } }
|
||||
@media (max-height: 800px) { .assembly-editor-modal .ant-modal-content { padding: 12px 16px 10px; } .assembly-editor-modal .ant-modal-header { margin-bottom: 6px; } .assembly-editor-toolbar { margin-bottom: 8px; } .assembly-editor-modal .ant-modal-footer { margin-top: 6px; } .assembly-step-config { padding: 8px 10px; } .assembly-config-heading { margin-bottom: 6px; } .assembly-tool-settings { gap: 6px; margin-top: 7px; padding-top: 7px; } }
|
||||
@media (max-width: 900px) { .assembly-editor-layout { grid-template-columns: minmax(0, 1fr) 250px; gap: 10px; } .assembly-workbench { padding-inline: 10px; } .assembly-playback { grid-template-columns: 1fr; } .assembly-preview-actions { grid-column: 1; grid-row: 3; margin-bottom: 6px; } .assembly-progress-caption > span { max-width: 190px; } .assembly-config-basic { gap: 8px; } .assembly-tool-selector { flex-wrap: wrap; } }
|
||||
@media (max-width: 760px) { .assembly-editor-modal { width: calc(100vw - 16px) !important; max-width: none; margin: 0 auto; } .assembly-editor-modal .ant-modal-content { padding: 12px; } .assembly-editor-layout { grid-template-columns: minmax(0, 1fr) 210px; } .assembly-editor-toolbar { gap: 6px; } .assembly-editor-toolbar > .ant-input { width: 28%; } .assembly-toolbar-actions { gap: 3px; } .assembly-toolbar-actions .assembly-history-button { min-width: 54px; padding-inline: 6px; } .assembly-editor-footer .ant-typography { max-width: 50%; } .assembly-config-heading .ant-typography { display: none; } .assembly-direction-buttons { gap: 3px; } .assembly-direction-buttons .ant-btn { width: 26px; } }
|
||||
.assembly-operation-select { border: 1px solid #617b43; padding: 4px; }
|
||||
.assembly-operation-select .ant-segmented-item-label { padding-inline: 14px; font-weight: 600; }
|
||||
.assembly-operation-context { flex: none; display: flex; justify-content: space-between; gap: 12px; align-items: center; padding: 9px 12px; margin-bottom: 10px; border: 1px solid #343f49; border-radius: 9px; background: #1c232b; }
|
||||
.assembly-operation-context > div { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||
.assembly-operation-context strong { white-space: nowrap; font-size: 12px; color: #d3dec8; }
|
||||
.assembly-operation-context span { font-size: 11px; color: #8f9dac; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.assembly-operation-context.is-library { border-color: #4b603a; background: #222b20; }
|
||||
.assembly-library-context { flex: none; display: flex; flex-direction: column; gap: 8px; padding-top: 12px; }
|
||||
.assembly-library-context label { font-size: 11px; color: #a8b599; }
|
||||
.assembly-library-context > .ant-select { width: 100%; }
|
||||
.assembly-library-context > div:last-child { display: flex; gap: 5px; }
|
||||
.assembly-library-context .ant-btn { font-size: 11px; }
|
||||
.assembly-workbench .ant-tabs-tabpane-active > .assembly-library-panel { flex: 1; flex-shrink: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; }
|
||||
.assembly-library-actions { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; }
|
||||
.assembly-library-actions .ant-btn { font-size: 11px; }
|
||||
.assembly-library-tree, .assembly-library-tree ul { list-style: none; margin: 0; padding: 0; }
|
||||
.assembly-library-tree ul { margin-left: 10px; padding-left: 8px; border-left: 1px solid #3d4b35; }
|
||||
.assembly-library-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 7px; padding: 10px 5px; border-bottom: 1px solid #2c353e; border-radius: 7px; }
|
||||
.assembly-library-row.is-active { background: #283323; }
|
||||
.assembly-library-name { min-width: 0; display: flex; flex-direction: column; gap: 5px; background: none; border: 0; text-align: left; color: #dde5d5; padding: 0; cursor: pointer; }
|
||||
.assembly-library-name strong { display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; font-size: 12px; }
|
||||
.assembly-library-name small { color: #829071; font-size: 10px; }
|
||||
.assembly-library-row-actions { display: flex; gap: 0; align-items: flex-start; }
|
||||
.assembly-library-row-actions .ant-btn { width: 22px; height: 23px; min-width: 22px; font-size: 10px; padding: 0; }
|
||||
.assembly-library-insert { grid-column: 1 / -1; justify-self: start; font-size: 10px; height: 24px; border-color: #5f7744; color: #c8e5a3; }
|
||||
.assembly-library-child-tag { justify-self: start; font-size: 10px; line-height: 18px; }
|
||||
@media (max-height: 800px) { .assembly-operation-context { padding: 6px 9px; margin-bottom: 8px; } .assembly-operation-select { padding: 2px; } }
|
||||
@media (max-width: 1250px) { .assembly-editor-toolbar { gap: 8px; } .assembly-editor-toolbar > .ant-input { min-width: 100px; width: 22%; } .assembly-operation-select .ant-segmented-item-label { padding-inline: 8px; } .assembly-toolbar-actions .ant-segmented { font-size: 11px; } }
|
||||
/* 组件与零件同屏选择,不再出现直接装配/组件装配的第二套工作区。 */
|
||||
.assembly-workbench .ant-tabs-tabpane-active > .assembly-choice-panel { flex: 1; flex-shrink: 1; min-height: 0; }
|
||||
.assembly-choice-panel { display: flex; flex-direction: column; gap: 0; height: 100%; overflow: hidden; }
|
||||
.assembly-choice-panel > .ant-input-search { flex: none; margin-bottom: 8px; }
|
||||
.assembly-choice-components { flex: 0 1 auto; max-height: min(230px, 28dvh); overflow-y: auto; overscroll-behavior: contain; border-bottom: 1px solid #34402c; margin-bottom: 8px; padding-bottom: 7px; }
|
||||
.assembly-choice-section-title { display: flex; gap: 8px; align-items: center; min-height: 28px; font-size: 11px; flex: none; }
|
||||
.assembly-choice-section-title strong { color: #c4d9a7; }
|
||||
.assembly-choice-section-title > span { margin-left: auto; color: #8c9a81; font-size: 10px; }
|
||||
.assembly-choice-section-title > .ant-btn { font-size: 10px; padding-inline: 4px; }
|
||||
.assembly-no-components { display: block; padding: 4px 0 7px; color: #7e8b9a; font-size: 10px; }
|
||||
.assembly-choice-panel .assembly-library-row { padding: 7px 4px; gap: 4px; }
|
||||
.assembly-choice-panel .assembly-library-row > .ant-checkbox-wrapper { min-width: 0; font-size: 11px; align-items: center; }
|
||||
.assembly-choice-panel .assembly-library-row > .ant-checkbox-wrapper > span:last-child { min-width: 0; overflow: hidden; }
|
||||
.assembly-choice-panel .assembly-library-row strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 11px; }
|
||||
.assembly-choice-panel .assembly-library-row small { display: block; margin-top: 3px; font-size: 10px; color: #849473; }
|
||||
.assembly-library-rename { padding: 0 !important; height: 18px; font-size: 10px; justify-self: start; }
|
||||
.assembly-choice-panel .assembly-part-filter { margin-top: 4px; }
|
||||
.assembly-choice-panel .assembly-list-caption { margin: 8px 0 5px; font-size: 10px; }
|
||||
.assembly-choice-panel .assembly-part-list { flex: 1; min-height: 40px; }
|
||||
.assembly-part-row.is-reserved { opacity: .62; }
|
||||
.assembly-step-label .assembly-segment-marker { color: #c3e58f; font-size: 10px; }
|
||||
.assembly-scene-controls .ant-btn { font-size: 11px; }
|
||||
.assembly-scene-controls .ant-btn-text { color: #8d9c7f; font-size: 10px; }
|
||||
@media (max-height: 800px) { .assembly-choice-components { max-height: min(160px, 24dvh); } .assembly-choice-panel .assembly-library-row { padding: 5px 3px; } .assembly-scene-settings { margin-bottom: 7px; padding-bottom: 6px; } }
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ dayjs.locale('zh-cn');
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<ConfigProvider locale={zhCN} theme={theme}>
|
||||
<AntApp>
|
||||
<BrowserRouter>
|
||||
<BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
|
||||
@@ -82,7 +82,7 @@ export default function ProjectDetailPage() {
|
||||
const p = data.project;
|
||||
const ready = p.repoStatus === 'READY';
|
||||
const blocked = p.publishStatus === 'BLOCKED' || data.moderationStatus === 'BLOCKED';
|
||||
const experiences = <Suspense fallback={<Spin tip="加载装配与仿真" />}>
|
||||
const experiences = <Suspense fallback={<Spin tip="加载装配与仿真"><div style={{ minHeight: 120 }} /></Spin>}>
|
||||
{'modelGlbUrl' in p ? <ProjectResourcesPanel key={p.projectCode} project={p} disabled={data.deleted} onUpdate={project => setData(old => old ? { ...old, project } : old)} /> : <ExperiencePanel
|
||||
key={p.projectCode} projectCode={p.projectCode} canPublish={ready && !blocked && !data.deleted}
|
||||
disabled={data.deleted} refreshKey={experienceRefresh}
|
||||
|
||||
+53
-19
@@ -1,10 +1,19 @@
|
||||
import type { AssemblyPart, ExperienceDraftContent, ModelAsset, Vector3 } from '@/api/experience-types';
|
||||
import type { ExperienceFileSelections } from './experienceFiles';
|
||||
import { experiencePathProblem } from './modelAssets';
|
||||
import { toolConfigProblems } from './assemblyToolConfig';
|
||||
import { libraryProblems } from './assemblyLibrary';
|
||||
|
||||
export type Assembly = NonNullable<ExperienceDraftContent['assembly']>;
|
||||
export interface AssemblySource { asset: ModelAsset; file?: File }
|
||||
export interface AssemblySession { assembly: Assembly; sources: AssemblySource[]; reference?: AssemblySource }
|
||||
export interface AssemblyDocument extends Record<string, unknown> {
|
||||
schemaVersion: 1; kind: 'assembly'; unit: 'meter'; title: string;
|
||||
displayQuaternion: Assembly['displayQuaternion'];
|
||||
files: { path: string; bytes: number; sha256: string }[];
|
||||
parts: (Omit<AssemblyPart, 'assetId' | 'name'> & { file: string; name?: string; [key: string]: unknown })[];
|
||||
steps: Assembly['steps'];
|
||||
}
|
||||
export interface AssemblySession { assembly: Assembly; sources: AssemblySource[]; reference?: AssemblySource; manifest?: AssemblyDocument; catalog?: AssemblyPart[]; unplaced?: string[] }
|
||||
export type EntrySide = 'x+' | 'x-' | 'y+' | 'y-' | 'z+' | 'z-';
|
||||
export const newEditorId = (prefix: string) => `${prefix}-${crypto.randomUUID()}`;
|
||||
export const copyAssembly = (value: Assembly): Assembly => structuredClone(value);
|
||||
@@ -28,11 +37,11 @@ export async function prepareAssemblySession(existing: AssemblySession | null, a
|
||||
if (files.parts.checking) throw new Error('零件文件夹仍在检查中,请稍后制作装配流程。');
|
||||
if (files.parts.problems.length) throw new Error('请先修正上方零件文件夹的问题,再制作装配流程。');
|
||||
const localParts = files.parts.type === 'part-glb' && !files.parts.checking && !files.parts.problems.length ? files.parts.selected : [];
|
||||
const referenced = new Set(assembly?.parts.map((p) => p.assetId) ?? []);
|
||||
const referenced = new Set([...(assembly?.parts.map((p) => p.assetId) ?? []), ...(assembly?.tools?.map(t => t.assetId) ?? [])]);
|
||||
const readyParts = assets.filter((a) => a.status === 'READY' && a.type === 'part-glb');
|
||||
const currentFiles = new Set(localParts.map((s) => s.file));
|
||||
// 保留已有流程使用的原文件与当前零件文件夹,不把未使用的旧选择重新混入零件库。
|
||||
const sources = [...(existing?.sources ?? []).filter((s) => s.file && (referenced.has(s.asset.assetId) || currentFiles.has(s.file) || readyParts.some((a) => a.assetId === s.asset.assetId)))];
|
||||
const sources = [...(existing?.sources ?? []).filter((s) => s.file && (existing?.manifest?.files.some(f => f.path === s.asset.relativePath) || !localParts.length && existing?.catalog?.some(p => p.assetId === s.asset.assetId) || referenced.has(s.asset.assetId) || currentFiles.has(s.file) || readyParts.some((a) => a.assetId === s.asset.assetId)))];
|
||||
// 摘要与预览都读取原文件;不重写、压缩或改变 GLB 的材质。
|
||||
for (const selected of localParts) {
|
||||
if (!sources.some((s) => s.file === selected.file && s.asset.relativePath === selected.relativePath)) {
|
||||
@@ -56,7 +65,12 @@ export async function prepareAssemblySession(existing: AssemblySession | null, a
|
||||
const selected = files.whole.selected[0];
|
||||
reference = existing?.reference?.file === selected.file ? existing.reference : await localSource(selected.file, selected.relativePath, 'whole-glb');
|
||||
}
|
||||
return bindAssemblySession({ assembly: next, sources, reference }, assets);
|
||||
const prepared = bindAssemblySession({ assembly: next, sources, reference, manifest: existing?.manifest, catalog: existing?.catalog, unplaced: existing?.unplaced }, assets);
|
||||
if (!prior && reference?.file) {
|
||||
const { placeFromWhole } = await import('./assemblyPlacement');
|
||||
return placeFromWhole(prepared, reference.file, new AbortController().signal);
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
|
||||
/** 唯一匹配才关联;版本歧义保持待上传状态,绝不悄悄换成同名文件。 */
|
||||
@@ -72,16 +86,16 @@ export function bindAssemblySession(session: AssemblySession, assets: ModelAsset
|
||||
const asset = replacements.get(source.asset.assetId) ?? source.asset;
|
||||
sources.set(asset.assetId, { asset, file: source.file ?? sources.get(asset.assetId)?.file });
|
||||
}
|
||||
return { ...session, assembly: { ...session.assembly, parts: session.assembly.parts.map((p) => ({ ...p, assetId: replacements.get(p.assetId)?.assetId ?? p.assetId })) }, sources: [...sources.values()] };
|
||||
return { ...session, assembly: { ...session.assembly, parts: session.assembly.parts.map((p) => ({ ...p, assetId: replacements.get(p.assetId)?.assetId ?? p.assetId })), tools: session.assembly.tools?.map(t => ({ ...t, assetId: replacements.get(t.assetId)?.assetId ?? t.assetId })) }, catalog: session.catalog?.map(p => ({ ...p, assetId: replacements.get(p.assetId)?.assetId ?? p.assetId })), sources: [...sources.values()] };
|
||||
}
|
||||
export function pendingAssemblyFiles(session: AssemblySession): boolean {
|
||||
return session.assembly.parts.some((part) => session.sources.find((s) => s.asset.assetId === part.assetId)?.file && part.assetId.startsWith('local-'));
|
||||
return [...session.assembly.parts, ...(session.assembly.tools ?? [])].some((part) => session.sources.find((s) => s.asset.assetId === part.assetId)?.file && part.assetId.startsWith('local-'));
|
||||
}
|
||||
|
||||
/** 保留流程使用的本地原文件,避免更换选择或移除卡片选择后无从上传。 */
|
||||
export function stageAssemblyFiles(session: AssemblySession, files: ExperienceFileSelections): ExperienceFileSelections {
|
||||
if (files.parts.checking) throw new Error('零件文件仍在检查中,请稍后保存流程。');
|
||||
const needed = session.sources.filter((s) => s.file && s.asset.assetId.startsWith('local-') && session.assembly.parts.some((p) => p.assetId === s.asset.assetId));
|
||||
const needed = session.sources.filter((s) => s.file && s.asset.assetId.startsWith('local-') && (session.assembly.parts.some((p) => p.assetId === s.asset.assetId) || session.assembly.tools?.some(t => t.assetId === s.asset.assetId)));
|
||||
if (!needed.length) return files;
|
||||
const selected = files.parts.type === 'part-glb' ? [...files.parts.selected] : [];
|
||||
for (const source of needed) {
|
||||
@@ -95,8 +109,9 @@ export function stageAssemblyFiles(session: AssemblySession, files: ExperienceFi
|
||||
export function assemblyProblems(assembly: Assembly): string[] {
|
||||
const problems: string[] = [];
|
||||
if (!assembly.title.trim()) problems.push('请填写装配流程名称。');
|
||||
if (!assembly.parts.length) problems.push('请先载入零件模型。');
|
||||
if (!assembly.steps.length) problems.push('选中一组零件,点击“添加步骤”开始制作。');
|
||||
const hasLibrary = !!assembly.componentLibrary?.components.length;
|
||||
if (!assembly.parts.length && !hasLibrary) problems.push('请先载入零件模型。');
|
||||
if (!assembly.steps.length && !hasLibrary) problems.push('选中一组零件,点击“添加步骤”开始制作。');
|
||||
const byId = new Map(assembly.parts.map((p) => [p.id, p]));
|
||||
if (byId.size !== assembly.parts.length) problems.push('存在重复零件,请重新载入。');
|
||||
const finite = (v: number[], n: number) => v.length === n && v.every(Number.isFinite);
|
||||
@@ -116,6 +131,7 @@ export function assemblyProblems(assembly: Assembly): string[] {
|
||||
for (const [i, step] of assembly.steps.entries()) {
|
||||
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(step.id)) problems.push(`第 ${i + 1} 步的编号无效,请重新创建此步骤。`);
|
||||
if (!step.label.trim()) problems.push(`请填写第 ${i + 1} 步的名称。`);
|
||||
if (step.installOffset !== undefined && !finite(step.installOffset, 3)) problems.push(`第 ${i + 1} 步的组件进入方向无效。`);
|
||||
if (stepIds.has(step.id)) problems.push(`第 ${i + 1} 步重复。`);
|
||||
stepIds.add(step.id);
|
||||
if (!step.parts.length) problems.push(`第 ${i + 1} 步还没有选择零件。`);
|
||||
@@ -128,29 +144,47 @@ export function assemblyProblems(assembly: Assembly): string[] {
|
||||
}
|
||||
current.forEach((id) => assigned.add(id));
|
||||
}
|
||||
const missing = assembly.parts.filter((p) => !assigned.has(p.id));
|
||||
const libraryParts = new Set(assembly.componentLibrary?.components.flatMap(c => c.parts) ?? []);
|
||||
const missing = assembly.parts.filter((p) => !assigned.has(p.id) && !libraryParts.has(p.id));
|
||||
if (assembly.steps.length && missing.length) problems.push(`还有 ${missing.length} 个零件未安排步骤。`);
|
||||
return [...new Set(problems)];
|
||||
return [...new Set([...problems, ...toolConfigProblems(assembly)])];
|
||||
}
|
||||
|
||||
export function assemblyManifest(assembly: Assembly, sources: AssemblySource[]) {
|
||||
const problems = assemblyProblems(assembly);
|
||||
export function assemblyManifest(assembly: Assembly, sources: AssemblySource[], original?: AssemblyDocument) {
|
||||
const problems = [...assemblyProblems(assembly), ...libraryProblems(assembly)];
|
||||
if (problems.length) throw new Error(problems[0]);
|
||||
const paths = new Map<string, string>();
|
||||
const usedPaths = new Set<string>();
|
||||
const files: { path: string; bytes: number; sha256: string }[] = [];
|
||||
for (const assetId of new Set(assembly.parts.map((p) => p.assetId))) {
|
||||
// 保留工具和其他扩展字段引用的文件,避免编辑后丢失扳手等资源。
|
||||
const files = original ? original.files.map(f => ({ ...f })) : [] as AssemblyDocument['files'];
|
||||
files.forEach(f => {
|
||||
const source = sources.find(s => s.asset.relativePath === f.path)?.asset;
|
||||
if (!source || source.bytes !== f.bytes || source.sha256 !== f.sha256) throw new Error(`流程引用的文件已变化:${f.path}。请核对零件后重新打开。`);
|
||||
usedPaths.add(f.path);
|
||||
});
|
||||
for (const assetId of new Set([...assembly.parts.map((p) => p.assetId), ...(assembly.tools?.map(t => t.assetId) ?? [])])) {
|
||||
const asset = sources.find((s) => s.asset.assetId === assetId)?.asset;
|
||||
if (!asset || asset.status !== 'READY' || !/^[a-f0-9]{64}$/.test(asset.sha256) || !Number.isSafeInteger(asset.bytes) || asset.bytes <= 0 || experiencePathProblem(asset.relativePath)) throw new Error('零件文件信息不完整,请重新选择文件或刷新资源列表。');
|
||||
let path = asset.relativePath;
|
||||
if (usedPaths.has(path)) path = `assets/${files.length + 1}/${path}`;
|
||||
while (usedPaths.has(path)) path = `assets/${path}`;
|
||||
const declared = original && files.find(f => f.path === path);
|
||||
if (declared && (declared.bytes !== asset.bytes || declared.sha256 !== asset.sha256)) throw new Error(`同路径零件内容不一致:${path}`);
|
||||
if (!declared && usedPaths.has(path)) path = `assets/${files.length + 1}/${path}`;
|
||||
while (!declared && usedPaths.has(path)) path = `assets/${path}`;
|
||||
paths.set(assetId, path); usedPaths.add(path);
|
||||
files.push({ path, bytes: asset.bytes, sha256: asset.sha256 });
|
||||
if (!declared) files.push({ path, bytes: asset.bytes, sha256: asset.sha256 });
|
||||
}
|
||||
const totalParts = new Set(assembly.steps.flatMap(s => s.parts));
|
||||
const originalLibraryParts = (original?.componentLibrary as { parts?: AssemblyDocument['parts'] } | undefined)?.parts;
|
||||
const originalParts = [...(original?.parts ?? []), ...(Array.isArray(originalLibraryParts) ? originalLibraryParts : [])];
|
||||
const mappedParts = assembly.parts.map(({ id, name, assetId, parentId, position, quaternion, scale, installOffset, installation }) => ({ ...originalParts.find(p => p.id === id), id, name, file: paths.get(assetId)!, parentId, position: [...position], quaternion: [...quaternion], scale: [...scale], installOffset: [...installOffset], installation: installation ? structuredClone(installation) : undefined }));
|
||||
return {
|
||||
...original,
|
||||
schemaVersion: 1, kind: 'assembly', title: assembly.title, unit: 'meter', displayQuaternion: [...assembly.displayQuaternion], files,
|
||||
parts: assembly.parts.map(({ id, name, assetId, parentId, position, quaternion, scale, installOffset }) => ({ id, name, file: paths.get(assetId)!, parentId, position: [...position], quaternion: [...quaternion], scale: [...scale], installOffset: [...installOffset] })),
|
||||
...(assembly.componentPlan ? { componentPlan: structuredClone(assembly.componentPlan) } : original?.componentPlan ? { componentPlan: undefined } : {}),
|
||||
...(assembly.componentLibrary ? { componentLibrary: { ...structuredClone(assembly.componentLibrary), parts: mappedParts.filter(p => !totalParts.has(p.id)) } } : original?.componentLibrary ? { componentLibrary: undefined } : {}),
|
||||
...(assembly.sceneSequence ? { sceneSequence: structuredClone(assembly.sceneSequence) } : original?.sceneSequence ? { sceneSequence: undefined } : {}),
|
||||
...(assembly.tools ? { tools: assembly.tools.map(({ assetId, ...tool }) => ({ ...((original?.tools as Record<string, unknown>[] | undefined)?.find(t => t.id === tool.id)), ...tool, file: paths.get(assetId)! })) } : {}),
|
||||
parts: assembly.componentLibrary ? mappedParts.filter(p => totalParts.has(p.id)) : mappedParts,
|
||||
steps: assembly.steps.map((s) => ({ ...s, parts: [...s.parts] })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import * as THREE from 'three';
|
||||
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
||||
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
|
||||
import type { Vector3 } from '@/api/experience-types';
|
||||
import type { AssemblySource } from './assemblyEditor';
|
||||
import { safeExperienceUrl } from './modelAssets';
|
||||
|
||||
export interface GeometryFacts { positions: Float64Array; triangles: Uint32Array; min: Vector3; max: Vector3 }
|
||||
export interface ScrewHead { axis: Vector3; surface: Vector3; socketPosition: Vector3; length: number; headWidth: number; tailWidth: number }
|
||||
export function disposeAssemblyObjects(objects: THREE.Object3D[]) {
|
||||
const resources = new Set<{ dispose: () => void }>(), images = new Set<ImageBitmap>();
|
||||
objects.forEach(object => object.traverse(child => {
|
||||
const mesh = child as THREE.Mesh;
|
||||
if (mesh.geometry) resources.add(mesh.geometry);
|
||||
for (const material of [mesh.material].flat().filter(Boolean)) {
|
||||
resources.add(material);
|
||||
for (const texture of Object.values(material)) if (texture instanceof THREE.Texture) { resources.add(texture); if (texture.source?.data) images.add(texture.source.data); }
|
||||
}
|
||||
}));
|
||||
resources.forEach(r => r.dispose()); images.forEach(image => image.close?.());
|
||||
}
|
||||
export async function readGeometry(source: AssemblySource, signal: AbortSignal): Promise<GeometryFacts> {
|
||||
let bytes: ArrayBuffer;
|
||||
if (source.file) bytes = await source.file.arrayBuffer();
|
||||
else {
|
||||
const url = safeExperienceUrl(source.asset.downloadUrl); if (!url) throw new Error('零件没有可读取的原 GLB,请刷新资源。');
|
||||
const response = await fetch(url, { signal, credentials: 'omit' });
|
||||
if (!response.ok) throw new Error(`读取零件失败(${response.status})`);
|
||||
bytes = await response.arrayBuffer();
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
const manager = new THREE.LoadingManager();
|
||||
manager.setURLModifier(url => { if (/^(blob:|data:)/.test(url)) return url; throw new Error('请使用材质与缓冲区均内嵌的 GLB。'); });
|
||||
const draco = new DRACOLoader().setDecoderPath(`${import.meta.env.BASE_URL}vendor/draco/`).setWorkerLimit(1);
|
||||
let root: THREE.Object3D | undefined;
|
||||
try {
|
||||
root = (await new GLTFLoader(manager).setDRACOLoader(draco).parseAsync(bytes, '')).scene;
|
||||
signal.throwIfAborted(); return geometryFacts(root);
|
||||
} finally { if (root) disposeAssemblyObjects([root]); draco.dispose(); }
|
||||
}
|
||||
const cache = new WeakMap<File, Promise<GeometryFacts>>();
|
||||
export function sourceGeometry(source: AssemblySource, signal: AbortSignal) {
|
||||
if (!source.file) return readGeometry(source, signal);
|
||||
const file = source.file;
|
||||
let pending = cache.get(file);
|
||||
if (!pending) { pending = readGeometry(source, signal).catch(error => { cache.delete(file); throw error; }); cache.set(file, pending); }
|
||||
return pending.then(facts => { signal.throwIfAborted(); return facts; });
|
||||
}
|
||||
export function geometryFacts(root: THREE.Object3D): GeometryFacts {
|
||||
root.updateMatrixWorld(true);
|
||||
const positions: number[] = [], triangles: number[] = [], point = new THREE.Vector3(), box = new THREE.Box3();
|
||||
root.traverse(child => {
|
||||
const mesh = child as THREE.Mesh;
|
||||
const attr = mesh.geometry?.getAttribute('position'); if (!mesh.isMesh || !attr) return;
|
||||
const base = positions.length / 3;
|
||||
for (let i = 0; i < attr.count; i++) { point.fromBufferAttribute(attr, i).applyMatrix4(mesh.matrixWorld); if (![point.x, point.y, point.z].every(Number.isFinite)) throw new Error('模型顶点包含无效坐标。'); positions.push(point.x, point.y, point.z); box.expandByPoint(point); }
|
||||
const index = mesh.geometry.index;
|
||||
for (let i = 0; i < (index?.count ?? attr.count); i++) triangles.push(base + (index?.getX(i) ?? i));
|
||||
});
|
||||
if (positions.length < 9 || box.isEmpty()) throw new Error('模型没有可分析的三角网格。');
|
||||
return { positions: new Float64Array(positions), triangles: new Uint32Array(triangles), min: box.min.toArray(), max: box.max.toArray() };
|
||||
}
|
||||
export function inferToolTipAxis(facts: GeometryFacts, tipPosition: Vector3): Vector3 {
|
||||
const tip = new THREE.Vector3(...tipPosition), outward = tip.clone().sub(new THREE.Vector3(...facts.min).add(new THREE.Vector3(...facts.max)).multiplyScalar(.5));
|
||||
const triangle = new THREE.Triangle(), nearest = new THREE.Vector3(), normal = new THREE.Vector3();
|
||||
let best = Infinity, result: THREE.Vector3 | undefined;
|
||||
for (let i = 0; i + 2 < facts.triangles.length; i += 3) {
|
||||
[triangle.a, triangle.b, triangle.c].forEach((p, j) => p.fromArray(facts.positions, facts.triangles[i + j] * 3));
|
||||
triangle.getNormal(normal); if (normal.lengthSq() < .5) continue;
|
||||
triangle.closestPointToPoint(tip, nearest); const distance = nearest.distanceToSquared(tip);
|
||||
if (distance >= best) continue; best = distance; result = normal.clone(); if (result.dot(outward) < 0) result.negate();
|
||||
}
|
||||
if (!result) throw new Error('无法测量工具工作方向,请重新点选工作端。');
|
||||
return result.normalize().toArray();
|
||||
}
|
||||
function principalAxis(facts: GeometryFacts): THREE.Vector3 {
|
||||
const p = facts.positions, mean = new THREE.Vector3();
|
||||
for (let i = 0; i < p.length; i += 3) mean.add(new THREE.Vector3(p[i], p[i + 1], p[i + 2]));
|
||||
mean.multiplyScalar(3 / p.length);
|
||||
const c = Array.from({ length: 3 }, () => [0, 0, 0]), vectors = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
|
||||
for (let i = 0; i < p.length; i += 3) {
|
||||
const v = [p[i] - mean.x, p[i + 1] - mean.y, p[i + 2] - mean.z];
|
||||
for (let r = 0; r < 3; r++) for (let s = 0; s < 3; s++) c[r][s] += v[r] * v[s];
|
||||
}
|
||||
for (let k = 0; k < 40; k++) {
|
||||
let r = 0, s = 1; for (const [i, j] of [[0, 2], [1, 2]]) if (Math.abs(c[i][j]) > Math.abs(c[r][s])) { r = i; s = j; }
|
||||
if (Math.abs(c[r][s]) < 1e-15) break;
|
||||
const angle = .5 * Math.atan2(2 * c[r][s], c[s][s] - c[r][r]), co = Math.cos(angle), si = Math.sin(angle), rr = c[r][r], ss = c[s][s], rs = c[r][s];
|
||||
c[r][r] = co * co * rr - 2 * si * co * rs + si * si * ss; c[s][s] = si * si * rr + 2 * si * co * rs + co * co * ss; c[r][s] = c[s][r] = 0;
|
||||
for (let i = 0; i < 3; i++) if (i !== r && i !== s) { const ir = c[i][r], is = c[i][s]; c[i][r] = c[r][i] = co * ir - si * is; c[i][s] = c[s][i] = si * ir + co * is; }
|
||||
for (let i = 0; i < 3; i++) { const ir = vectors[i][r], is = vectors[i][s]; vectors[i][r] = co * ir - si * is; vectors[i][s] = si * ir + co * is; }
|
||||
}
|
||||
const i = [0, 1, 2].sort((a, b) => c[b][b] - c[a][a])[0];
|
||||
return new THREE.Vector3(vectors[0][i], vectors[1][i], vectors[2][i]).normalize();
|
||||
}
|
||||
|
||||
/** 以端面法向校正主轴,宽端为头;不能区分时要求手动指定拧入轴。 */
|
||||
export function analyzeScrewHead(facts: GeometryFacts, depth = .00035, inwardOverride?: Vector3): ScrewHead {
|
||||
const p = facts.positions, indices = facts.triangles;
|
||||
let axis = inwardOverride ? new THREE.Vector3(...inwardOverride).normalize().negate() : principalAxis(facts);
|
||||
if (!inwardOverride) {
|
||||
const groups = new Map<string, { area: number; normal: THREE.Vector3 }>();
|
||||
const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3(), normal = new THREE.Vector3();
|
||||
for (let i = 0; i + 2 < indices.length; i += 3) {
|
||||
a.fromArray(p, indices[i] * 3); b.fromArray(p, indices[i + 1] * 3).sub(a); c.fromArray(p, indices[i + 2] * 3).sub(a);
|
||||
normal.crossVectors(b, c); const area = normal.length(); if (area < 1e-15) continue;
|
||||
normal.divideScalar(area); if (Math.abs(normal.dot(axis)) < .97) continue; if (normal.dot(axis) < 0) normal.negate();
|
||||
const key = normal.toArray().map(v => Math.round(v * 1000)).join(',');
|
||||
const item = groups.get(key) ?? { area: 0, normal: new THREE.Vector3() }; item.area += area; item.normal.addScaledVector(normal, area); groups.set(key, item);
|
||||
}
|
||||
const dominant = [...groups.values()].sort((a, b) => b.area - a.area)[0];
|
||||
if (!dominant) throw new Error('未识别到可靠的螺丝端面,请手动选择拧入轴或在模型上点选螺丝头。');
|
||||
axis = dominant.normal.normalize();
|
||||
}
|
||||
const project = (direction: THREE.Vector3) => {
|
||||
let min = Infinity, max = -Infinity;
|
||||
for (let i = 0; i < p.length; i += 3) { const d = p[i] * direction.x + p[i + 1] * direction.y + p[i + 2] * direction.z; min = Math.min(min, d); max = Math.max(max, d); }
|
||||
return { min, max };
|
||||
};
|
||||
let { min, max } = project(axis);
|
||||
if (max - min < 1e-8 || depth < 0 || depth >= max - min) throw new Error('插入点深度必须小于零件轴向长度。');
|
||||
const band = Math.min(.0006, (max - min) * .15);
|
||||
const u = new THREE.Vector3().crossVectors(axis, Math.abs(axis.x) < .8 ? new THREE.Vector3(1, 0, 0) : new THREE.Vector3(0, 1, 0)).normalize();
|
||||
const v = new THREE.Vector3().crossVectors(axis, u);
|
||||
const cap = (at: number) => {
|
||||
let u0 = Infinity, u1 = -Infinity, v0 = Infinity, v1 = -Infinity, count = 0;
|
||||
for (let i = 0; i < p.length; i += 3) {
|
||||
const point = new THREE.Vector3(p[i], p[i + 1], p[i + 2]); if (Math.abs(point.dot(axis) - at) > band) continue;
|
||||
const x = point.dot(u), y = point.dot(v); u0 = Math.min(u0, x); u1 = Math.max(u1, x); v0 = Math.min(v0, y); v1 = Math.max(v1, y); count++;
|
||||
}
|
||||
if (count < 3) throw new Error('端面数据不足,请在模型上点选螺丝头。');
|
||||
return { width: Math.max(u1 - u0, v1 - v0), center: u.clone().multiplyScalar((u0 + u1) / 2).addScaledVector(v, (v0 + v1) / 2) };
|
||||
};
|
||||
let head = cap(max), tail = cap(min);
|
||||
if (!inwardOverride) {
|
||||
if (Math.max(head.width, tail.width) < Math.min(head.width, tail.width) * 1.15) throw new Error('两端宽度接近,不能可靠区分螺丝头,请手动指定拧入轴或点选螺丝头。');
|
||||
if (tail.width > head.width) { axis.negate(); ({ min, max } = project(axis)); head = cap(max); tail = cap(min); }
|
||||
}
|
||||
const surface = axis.clone().multiplyScalar(max).add(head.center);
|
||||
return { axis: axis.clone().negate().toArray(), surface: surface.toArray(), socketPosition: surface.clone().addScaledVector(axis, -depth).toArray(), length: max - min, headWidth: head.width, tailWidth: tail.width };
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { AssemblyLibraryComponent, AssemblyStep } from '@/api/experience-types';
|
||||
import { assemblyProblems, copyAssembly, newEditorId, type Assembly } from './assemblyEditor';
|
||||
|
||||
export const libraryComponents = (a: Assembly) => a.componentLibrary?.components ?? [];
|
||||
export const libraryOwner = (a: Assembly, partId: string) => libraryComponents(a).find(c => c.parts.includes(partId));
|
||||
export function libraryComponentParts(a: Assembly, id: string, ancestors = new Set<string>()): string[] {
|
||||
if (ancestors.has(id)) throw new Error('组件不能循环引用。');
|
||||
const c = libraryComponents(a).find(c => c.id === id);
|
||||
if (!c) throw new Error('引用的组件不存在。');
|
||||
const visited = new Set([...ancestors, id]);
|
||||
return c.steps.flatMap(s => s.componentId ? libraryComponentParts(a, s.componentId, visited) : s.parts);
|
||||
}
|
||||
export function libraryComponentPath(a: Assembly, id: string): string {
|
||||
const names: string[] = [], seen = new Set<string>();
|
||||
for (let c = libraryComponents(a).find(c => c.id === id); c && !seen.has(c.id); c = libraryComponents(a).find(v => v.id === c!.parentId)) {
|
||||
names.unshift(c.name); seen.add(c.id);
|
||||
}
|
||||
return names.join(' / ');
|
||||
}
|
||||
export function libraryComponentAssembly(a: Assembly, id: string | null): Assembly {
|
||||
const c = libraryComponents(a).find(c => c.id === id);
|
||||
const next = copyAssembly(a);
|
||||
delete next.componentPlan; delete next.componentLibrary; delete next.sceneSequence;
|
||||
next.steps = structuredClone(c?.steps ?? []);
|
||||
return next;
|
||||
}
|
||||
/** 所有引用仅刷新自己的零件快照,不插入或重排总装步骤。 */
|
||||
export function syncLibraryReferences(a: Assembly): Assembly {
|
||||
const next = copyAssembly(a);
|
||||
const refresh = (steps: AssemblyStep[]) => steps.forEach(s => { if (s.componentId) s.parts = libraryComponentParts(next, s.componentId); });
|
||||
libraryComponents(next).forEach(c => refresh(c.steps)); refresh(next.steps);
|
||||
return next;
|
||||
}
|
||||
export function editLibraryComponent(a: Assembly, id: string, edited: Assembly): Assembly {
|
||||
const next = copyAssembly(a), c = libraryComponents(next).find(c => c.id === id);
|
||||
if (!c) throw new Error('请先选择要制作的组件。');
|
||||
c.steps = structuredClone(edited.steps);
|
||||
c.parts = c.steps.filter(s => !s.componentId).flatMap(s => s.parts);
|
||||
const used = new Set(c.steps.flatMap(s => s.parts));
|
||||
for (const p of edited.parts.filter(p => used.has(p.id))) {
|
||||
const i = next.parts.findIndex(v => v.id === p.id);
|
||||
if (i < 0) next.parts.push(structuredClone(p)); else next.parts[i] = structuredClone(p);
|
||||
}
|
||||
next.tools = structuredClone(edited.tools);
|
||||
return syncLibraryReferences(next);
|
||||
}
|
||||
export function createLibraryComponent(a: Assembly, name: string, parentId: string | null) {
|
||||
const trimmed = name.trim(), next = copyAssembly(a);
|
||||
const library = next.componentLibrary ??= { version: 1, components: [] };
|
||||
if (!trimmed) throw new Error('请填写组件名称。');
|
||||
if (parentId && !library.components.some(c => c.id === parentId)) throw new Error('上级组件不存在。');
|
||||
if (library.components.some(c => c.parentId === parentId && c.name === trimmed)) throw new Error('同一级已有这个组件名称。');
|
||||
const component: AssemblyLibraryComponent = { id: newEditorId('library'), name: trimmed, parentId, parts: [], steps: [] };
|
||||
library.components.push(component);
|
||||
return { assembly: next, componentId: component.id };
|
||||
}
|
||||
export function insertLibraryComponent(a: Assembly, libraryDocument: Assembly, id: string, parentId: string | null): Assembly {
|
||||
const c = libraryComponents(libraryDocument).find(c => c.id === id);
|
||||
if (!c || parentId && c.parentId !== parentId) throw new Error('请选择当前组件的直接子组件。');
|
||||
const parts = libraryComponentParts(libraryDocument, id);
|
||||
if (!parts.length) throw new Error('这个组件还没有安装零件,请先制作组件内容。');
|
||||
const used = new Set(a.steps.flatMap(s => s.parts));
|
||||
if (new Set(parts).size !== parts.length || parts.some(p => used.has(p))) throw new Error('这个组件包含已在当前流程中的零件,不能重复加入。');
|
||||
const next = copyAssembly(a);
|
||||
const definitions = new Map(libraryDocument.parts.map(p => [p.id, p]));
|
||||
for (const id of parts) if (!next.parts.some(p => p.id === id)) {
|
||||
const p = definitions.get(id); if (!p) throw new Error('组件引用的零件已不存在。'); next.parts.push(structuredClone(p));
|
||||
}
|
||||
next.steps.push({ id: newEditorId('step'), label: `安装组件 ${c.name}`, parts, componentId: id, installOffset: [0, .08, 0] });
|
||||
return next;
|
||||
}
|
||||
export function deleteLibraryComponent(a: Assembly, id: string): Assembly {
|
||||
const all = libraryComponents(a), c = all.find(c => c.id === id);
|
||||
if (!c) return a;
|
||||
if (all.some(v => v.parentId === id)) throw new Error('请先处理这个组件的子组件,再删除上级组件。');
|
||||
if (a.steps.some(s => s.componentId === id) || all.some(v => v.steps.some(s => s.componentId === id))) throw new Error('组件已被步骤引用,请先移除引用步骤再删除。');
|
||||
const next = copyAssembly(a); next.componentLibrary!.components = all.filter(v => v.id !== id).map(v => structuredClone(v)); return next;
|
||||
}
|
||||
export function libraryProblems(a: Assembly): string[] {
|
||||
const lib = a.componentLibrary; if (!lib) return [];
|
||||
const errors: string[] = [], ids = new Set<string>(), owned = new Set<string>(), names = new Set<string>();
|
||||
if (lib.version !== 1) return ['组件库版本不受支持。'];
|
||||
for (const c of lib.components) {
|
||||
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(c.id) || ids.has(c.id) || !c.name.trim()) errors.push('组件库的编号或名称无效。');
|
||||
ids.add(c.id);
|
||||
const key = JSON.stringify([c.parentId, c.name]); if (names.has(key)) errors.push('同一级的组件名称不能重复。'); names.add(key);
|
||||
if (c.parentId && !lib.components.some(v => v.id === c.parentId)) errors.push('组件的上级已不存在。');
|
||||
const seen = new Set([c.id]);
|
||||
for (let parent = c.parentId; parent; parent = lib.components.find(v => v.id === parent)?.parentId ?? null) {
|
||||
if (seen.has(parent)) { errors.push('组件层级不能形成循环。'); break; } seen.add(parent);
|
||||
}
|
||||
const direct = c.steps.filter(s => !s.componentId).flatMap(s => s.parts);
|
||||
if (JSON.stringify([...direct].sort()) !== JSON.stringify([...c.parts].sort())) errors.push(`“${c.name}”的零件归属与内部步骤不一致。`);
|
||||
for (const id of c.parts) { if (owned.has(id)) errors.push('同一零件不能归属多个组件。'); owned.add(id); }
|
||||
if (c.parts.some(id => a.tools?.some(t => t.assetId === a.parts.find(p => p.id === id)?.assetId))) errors.push('工具 GLB 不能同时归属装配组件,请先移除其零件步骤。');
|
||||
for (const s of c.steps.filter(s => s.componentId)) {
|
||||
const child = lib.components.find(v => v.id === s.componentId);
|
||||
if (!child || child.parentId !== c.id) errors.push('组件内部只能引用它的直接子组件。');
|
||||
}
|
||||
const earlier = new Set<string>();
|
||||
for (const s of c.steps) {
|
||||
if (s.scene?.mode === 'continue' && (s.scene.base?.kind !== 'step' || !earlier.has(s.scene.base.id) || s.scene.base.componentId)) errors.push(`组件“${c.name}”的续装基准必须是它自己的更早步骤。`);
|
||||
earlier.add(s.id);
|
||||
}
|
||||
try {
|
||||
const parts = libraryComponentParts(a, c.id);
|
||||
if (new Set(parts).size !== parts.length) errors.push(`“${c.name}”重复使用了同一个零件或子组件。`);
|
||||
for (const s of c.steps.filter(s => s.componentId)) if (JSON.stringify(s.parts) !== JSON.stringify(libraryComponentParts(a, s.componentId!))) errors.push('子组件内容已变化,请刷新组件引用。');
|
||||
if (c.steps.length) errors.push(...assemblyProblems({ ...libraryComponentAssembly(a, c.id), parts: a.parts.filter(p => parts.includes(p.id)) }).map(p => `组件“${c.name}”:${p}`));
|
||||
} catch (e) { errors.push(e instanceof Error ? e.message : String(e)); }
|
||||
}
|
||||
for (const s of a.steps) {
|
||||
if (s.componentId) {
|
||||
const c = lib.components.find(c => c.id === s.componentId);
|
||||
if (!c) errors.push('总装引用的组件不存在。');
|
||||
try { if (!s.parts.length || JSON.stringify(s.parts) !== JSON.stringify(libraryComponentParts(a, s.componentId))) errors.push('总装中的组件引用与当前组件内容不一致。'); }
|
||||
catch (e) { errors.push(e instanceof Error ? e.message : String(e)); }
|
||||
}
|
||||
}
|
||||
return [...new Set(errors)];
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// 与 vibemake-site/js/assembly-motion.js 保持相同的局部坐标约定和四阶段动画。
|
||||
import { Group, Quaternion, Vector3 } from 'three';
|
||||
import type { AssemblyPart, AssemblyTool, ScrewInstallation, Quaternion as QuaternionTuple, Vector3 as VectorTuple } from '@/api/experience-types';
|
||||
|
||||
const ease = (t: number) => t * t * (3 - 2 * t);
|
||||
const clamp = (t: number) => Math.max(0, Math.min(1, t));
|
||||
import { screwDuration } from './assemblyToolConfig';
|
||||
export { screwDuration } from './assemblyToolConfig';
|
||||
export function alignedToolQuaternion(motion: ScrewInstallation, tool: AssemblyTool): Quaternion {
|
||||
const rotation = new Quaternion(...motion.toolQuaternion);
|
||||
if (!tool.tipAxis) throw new Error('工具缺少工作方向,请先校准工具工作端。');
|
||||
const current = new Vector3(...tool.tipAxis).applyQuaternion(rotation).normalize();
|
||||
return rotation.premultiply(new Quaternion().setFromUnitVectors(current, new Vector3(...motion.axis).normalize())).normalize();
|
||||
}
|
||||
export class ScrewTransition {
|
||||
readonly duration: number;
|
||||
private readonly motion: ScrewInstallation;
|
||||
private readonly target: Vector3;
|
||||
private readonly rotation: Quaternion;
|
||||
private readonly axis: Vector3;
|
||||
private readonly socket: Vector3;
|
||||
private readonly startOffset: Vector3;
|
||||
private readonly seatOffset: Vector3;
|
||||
private readonly dock: Vector3;
|
||||
constructor(private instance: Group, part: AssemblyPart, private tool: Group, config: AssemblyTool, private delay = 0) {
|
||||
this.motion = part.installation!;
|
||||
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);
|
||||
tool.quaternion.copy(alignedToolQuaternion(this.motion, config));
|
||||
this.dock = this.socket.clone().sub(new Vector3(...config.tipPosition).applyQuaternion(tool.quaternion));
|
||||
instance.add(tool); this.sample(0);
|
||||
}
|
||||
sample(elapsed: number) {
|
||||
const t = elapsed - this.delay, m = this.motion;
|
||||
this.instance.position.copy(this.target); this.instance.quaternion.copy(this.rotation); this.tool.visible = false;
|
||||
if (t < 0 || elapsed >= this.duration) return;
|
||||
const tighten = m.approachDuration + m.engageDuration, retract = tighten + m.tightenDuration;
|
||||
const offset = new Vector3();
|
||||
if (t < m.approachDuration) offset.lerpVectors(this.startOffset, this.seatOffset, ease(clamp(t / m.approachDuration)));
|
||||
else {
|
||||
const progress = ease(clamp((t - tighten) / m.tightenDuration));
|
||||
offset.copy(this.seatOffset).multiplyScalar(1 - progress);
|
||||
const spin = new Quaternion().setFromAxisAngle(this.axis, (m.direction === 'clockwise' ? 1 : -1) * Math.PI * 2 * m.turns * progress);
|
||||
if (progress < 1) {
|
||||
this.instance.quaternion.copy(this.rotation).multiply(spin);
|
||||
offset.add(this.socket.clone().applyQuaternion(spin).negate().add(this.socket).multiply(this.instance.scale).applyQuaternion(this.rotation));
|
||||
}
|
||||
let clearance = 0;
|
||||
if (t < tighten) clearance = m.toolClearance * (1 - ease(clamp((t - m.approachDuration) / m.engageDuration)));
|
||||
if (t >= retract) clearance = m.toolClearance * ease(clamp((t - retract) / m.retractDuration));
|
||||
this.tool.visible = true; this.tool.position.copy(this.dock).addScaledVector(this.axis, -clearance);
|
||||
}
|
||||
this.instance.position.add(offset);
|
||||
}
|
||||
dispose() { this.tool.removeFromParent(); }
|
||||
}
|
||||
|
||||
export function toolRotation(tipAxis: VectorTuple, inward: VectorTuple, rollDegrees = 0): QuaternionTuple {
|
||||
const local = new Vector3(...tipAxis).normalize();
|
||||
return new Quaternion().setFromUnitVectors(local, new Vector3(...inward).normalize()).multiply(new Quaternion().setFromAxisAngle(local, rollDegrees * Math.PI / 180)).normalize().toArray();
|
||||
}
|
||||
export function toolRoll(tool: AssemblyTool, motion: ScrewInstallation): number {
|
||||
if (!tool.tipAxis) return 0;
|
||||
const axis = new Vector3(...tool.tipAxis).normalize();
|
||||
const base = new Quaternion().setFromUnitVectors(axis, new Vector3(...motion.axis).normalize());
|
||||
const twist = base.invert().multiply(new Quaternion(...motion.toolQuaternion));
|
||||
return Math.round(2 * Math.atan2(new Vector3(twist.x, twist.y, twist.z).dot(axis), twist.w) * 180 / Math.PI * 100) / 100;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Matrix4, Quaternion, Vector3 } from 'three';
|
||||
import type { AssemblyPart } from '@/api/experience-types';
|
||||
import { sourcePart, type AssemblySession } from './assemblyEditor';
|
||||
|
||||
interface GlbNode { name?: string; mesh?: number; children?: number[]; matrix?: number[]; translation?: number[]; rotation?: number[]; scale?: number[] }
|
||||
interface GlbJson { nodes: GlbNode[]; meshes: { primitives: { attributes: { POSITION?: number } }[] }[]; accessors: { count: number; min?: number[]; max?: number[] }[] }
|
||||
async function glbJson(file: Blob): Promise<GlbJson> {
|
||||
const header = new DataView(await file.slice(0, 20).arrayBuffer());
|
||||
if (header.byteLength !== 20 || header.getUint32(0, true) !== 0x46546c67 || header.getUint32(4, true) !== 2
|
||||
|| header.getUint32(8, true) !== file.size || header.getUint32(16, true) !== 0x4e4f534a) throw new Error('整机或零件不是完整的 GLB 2.0 文件。');
|
||||
const json = JSON.parse(await file.slice(20, 20 + header.getUint32(12, true)).text());
|
||||
if (!Array.isArray(json.nodes) || !Array.isArray(json.meshes)) throw new Error('模型缺少节点信息,无法自动定位。');
|
||||
return json;
|
||||
}
|
||||
function nodeWorlds(json: GlbJson): Matrix4[] {
|
||||
const parents = new Map<number, number>(), done = new Map<number, Matrix4>();
|
||||
json.nodes.forEach((n, i) => n.children?.forEach(child => { if (parents.has(child)) throw new Error('模型节点父级不唯一。'); parents.set(child, i); }));
|
||||
const world = (i: number, seen = new Set<number>()): Matrix4 => {
|
||||
if (done.has(i)) return done.get(i)!;
|
||||
const n = json.nodes[i]; if (!n || seen.has(i)) throw new Error('模型节点层级无效。');
|
||||
const local = n.matrix ? new Matrix4().fromArray(n.matrix) : new Matrix4().compose(new Vector3().fromArray(n.translation ?? [0, 0, 0]), new Quaternion().fromArray(n.rotation ?? [0, 0, 0, 1]), new Vector3().fromArray(n.scale ?? [1, 1, 1]));
|
||||
const parent = parents.get(i), matrix = parent === undefined ? local : world(parent, new Set([...seen, i])).clone().multiply(local);
|
||||
done.set(i, matrix); return matrix;
|
||||
};
|
||||
return json.nodes.map((_, i) => world(i));
|
||||
}
|
||||
function geometryMatches(a: GlbJson, ai: number, b: GlbJson, bi: number) {
|
||||
const ap = a.meshes[ai]?.primitives, bp = b.meshes[bi]?.primitives;
|
||||
if (!ap || !bp || ap.length !== bp.length) return false;
|
||||
return ap.every((p, i) => {
|
||||
const av = a.accessors?.[p.attributes.POSITION ?? -1], bv = b.accessors?.[bp[i].attributes.POSITION ?? -1];
|
||||
// 整机与分件可能经过不同的顶点去重/压缩,顶点数量不要求相同。
|
||||
return av && bv && ['min', 'max'].every(key => {
|
||||
const x = av[key as 'min' | 'max'], y = bv[key as 'min' | 'max'];
|
||||
return x?.length === 3 && y?.length === 3 && x.every((v, j) => Math.abs(v - y[j]) <= Math.max(1, Math.abs(v)) * 1e-6);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** 通过唯一节点名与几何范围匹配整机位姿;不凭文件名或模糊名称猜测位置。 */
|
||||
export async function placeFromWhole(session: AssemblySession, whole: Blob, signal: AbortSignal): Promise<AssemblySession> {
|
||||
const reference = await glbJson(whole), worlds = nodeWorlds(reference);
|
||||
const names = new Map<string, number[]>();
|
||||
reference.nodes.forEach((n, i) => { if (n.name && n.mesh !== undefined) names.set(n.name, [...(names.get(n.name) ?? []), i]); });
|
||||
const known = new Map(session.assembly.parts.map(p => [p.assetId, p]));
|
||||
const unplaced: string[] = [], catalog: AssemblyPart[] = [];
|
||||
for (const source of session.sources.filter(s => s.asset.type === 'part-glb')) {
|
||||
signal.throwIfAborted();
|
||||
const part = structuredClone(known.get(source.asset.assetId) ?? sourcePart(source.asset));
|
||||
if (source.file) {
|
||||
try {
|
||||
const json = await glbJson(source.file), local = nodeWorlds(json);
|
||||
const meshes = json.nodes.map((n, i) => ({ n, i })).filter(({ n }) => n.mesh !== undefined);
|
||||
const candidates = meshes.map(({ n, i }) => {
|
||||
const matches = names.get(n.name ?? '');
|
||||
if (matches?.length !== 1 || !geometryMatches(json, n.mesh!, reference, reference.nodes[matches[0]].mesh!)) throw new Error('无唯一匹配');
|
||||
return worlds[matches[0]].clone().multiply(local[i].clone().invert());
|
||||
});
|
||||
if (!candidates.length || candidates.some(m => m.elements.some((v, i) => Math.abs(v - candidates[0].elements[i]) > 1e-5))) throw new Error('零件位姿不一致');
|
||||
const position = new Vector3(), rotation = new Quaternion(), scale = new Vector3();
|
||||
candidates[0].decompose(position, rotation, scale);
|
||||
if (![...position, ...rotation, ...scale].every(Number.isFinite) || scale.toArray().some(v => v <= 0)) throw new Error('位姿无效');
|
||||
const recomposed = new Matrix4().compose(position, rotation, scale);
|
||||
if (recomposed.elements.some((v, i) => Math.abs(v - candidates[0].elements[i]) > 1e-5)) throw new Error('位姿包含无法保留的剪切变换');
|
||||
part.parentId = null; part.position = position.toArray(); part.quaternion = rotation.normalize().toArray(); part.scale = scale.toArray();
|
||||
} catch { unplaced.push(part.id); }
|
||||
} else unplaced.push(part.id);
|
||||
catalog.push(part);
|
||||
}
|
||||
const byId = new Map(catalog.map(p => [p.id, p]));
|
||||
return { ...session, catalog, unplaced, assembly: { ...session.assembly, parts: session.assembly.parts.map(p => byId.get(p.id) ?? p) } };
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import * as THREE from 'three';
|
||||
|
||||
/** 仅缩小浏览器预览的解码贴图;上传原文件及其材质参数保持不变。 */
|
||||
export async function fitPreviewTextures(root: THREE.Object3D, fileCount: number, signal: AbortSignal) {
|
||||
const bySource = new Map<THREE.Source, THREE.Texture[]>();
|
||||
root.traverse(object => {
|
||||
const mesh = object as THREE.Mesh;
|
||||
for (const material of [mesh.material].flat().filter(Boolean)) for (const value of Object.values(material)) {
|
||||
if (value instanceof THREE.Texture && !(value as THREE.CompressedTexture).isCompressedTexture && !(value as THREE.VideoTexture).isVideoTexture) bySource.set(value.source, [...(bySource.get(value.source) ?? []), value]);
|
||||
}
|
||||
});
|
||||
const edge = Math.sqrt(128 * 1024 * 1024 / (Math.max(1, fileCount, bySource.size) * 2 * 4 * (1 + 4 / 3)));
|
||||
const limit = Math.max(64, Math.min(1024, 2 ** Math.floor(Math.log2(edge))));
|
||||
const originals = new Set([...bySource.keys()].map(source => source.data));
|
||||
try {
|
||||
for (const [source, textures] of bySource) {
|
||||
signal.throwIfAborted();
|
||||
const image = source.data;
|
||||
if (!image?.width || !image?.height || image.data || Math.max(image.width, image.height) <= limit) continue;
|
||||
const scale = limit / Math.max(image.width, image.height), width = Math.max(1, Math.round(image.width * scale)), height = Math.max(1, Math.round(image.height * scale));
|
||||
const small = await createImageBitmap(image, { resizeWidth: width, resizeHeight: height, resizeQuality: 'high', colorSpaceConversion: 'none', premultiplyAlpha: 'none' });
|
||||
if (signal.aborted) { small.close(); signal.throwIfAborted(); }
|
||||
source.data = small; textures.forEach(t => { t.needsUpdate = true; });
|
||||
}
|
||||
} finally {
|
||||
const live = new Set([...bySource.keys()].map(source => source.data));
|
||||
for (const image of originals) if (!live.has(image)) image?.close?.();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { AssemblyLibraryComponent, AssemblyStep } from '@/api/experience-types';
|
||||
import { copyAssembly, newEditorId, type Assembly } from './assemblyEditor';
|
||||
import { componentParts } from './assemblyWorkflow';
|
||||
import { libraryComponents, syncLibraryReferences } from './assemblyLibrary';
|
||||
|
||||
/** 把旧版“先分组再连接”整理为组件库;只在本地编辑,保存前不改服务器。 */
|
||||
export function simplifyAssembly(value: Assembly): Assembly {
|
||||
if (!value.componentPlan) return value;
|
||||
const next = copyAssembly(value), plan = next.componentPlan!;
|
||||
delete next.componentPlan; delete next.sceneSequence;
|
||||
if (!plan.components.length && !plan.connections.length) return next;
|
||||
const lib = next.componentLibrary ??= { version: 1, components: [] };
|
||||
const idMap = new Map([...plan.components, ...plan.connections].map(c => [c.id, newEditorId('library')]));
|
||||
const created: AssemblyLibraryComponent[] = [];
|
||||
const claimed = new Set(plan.components.flatMap(c => c.parts));
|
||||
for (const c of plan.components) {
|
||||
const steps = next.steps.flatMap(s => {
|
||||
const parts = s.parts.filter(id => c.parts.includes(id));
|
||||
return parts.length ? [{ ...structuredClone(s), parts }] : [];
|
||||
});
|
||||
const ids = new Set(steps.map(s => s.id));
|
||||
for (const s of steps) if (s.scene?.mode === 'continue' && (s.scene.base.kind !== 'step' || !ids.has(s.scene.base.id))) { delete s.scene; delete s.sceneMarker; }
|
||||
const id = idMap.get(c.id)!;
|
||||
for (const s of steps) if (s.componentId) {
|
||||
const child = lib.components.find(v => v.id === s.componentId);
|
||||
if (!child || child.parentId) throw new Error('旧流程的组件层级存在歧义,原流程已保留。');
|
||||
child.parentId = id;
|
||||
}
|
||||
created.push({ id, name: c.name, parentId: null, parts: steps.filter(s => !s.componentId).flatMap(s => s.parts), steps });
|
||||
}
|
||||
for (const c of plan.connections) {
|
||||
const id = idMap.get(c.id)!;
|
||||
for (const member of c.members) { const child = created.find(v => v.id === idMap.get(member)); if (!child) throw new Error('旧组件引用不完整,原流程已保留。'); child.parentId = id; }
|
||||
created.push({ id, name: c.name, parentId: null, parts: [], steps: c.members.map(member => ({ id: newEditorId('step'), label: `安装组件 ${created.find(v => v.id === idMap.get(member))!.name}`, parts: componentParts(plan, member), componentId: idMap.get(member)!, installOffset: [...c.installOffset] })) });
|
||||
}
|
||||
for (const c of created) {
|
||||
const originalName = c.name; let suffix = 2;
|
||||
while ([...lib.components, ...created.filter(v => v !== c && created.indexOf(v) < created.indexOf(c))].some(v => v.parentId === c.parentId && v.name === c.name)) c.name = `${originalName} (${suffix++})`;
|
||||
}
|
||||
lib.components.push(...created);
|
||||
const roots = created.filter(c => !c.parentId), steps: AssemblyStep[] = roots.map(c => ({ id: newEditorId('step'), label: `安装组件 ${c.name}`, parts: [], componentId: c.id, installOffset: [0, .08, 0] }));
|
||||
const rootForLegacy = (id: string) => {
|
||||
let c = created.find(c => c.id === idMap.get(id));
|
||||
while (c?.parentId) c = created.find(v => v.id === c!.parentId);
|
||||
return steps.find(s => s.componentId === c?.id);
|
||||
};
|
||||
for (const s of value.steps) {
|
||||
const parts = s.parts.filter(id => !claimed.has(id)); if (!parts.length) continue;
|
||||
const loose = { ...structuredClone(s), parts };
|
||||
if (loose.scene?.mode === 'continue') {
|
||||
const base = loose.scene.base;
|
||||
const legacyComponent = base.kind === 'connection' ? base.id : plan.components.find(c => value.steps.find(s => s.id === base.id)?.parts.some(p => c.parts.includes(p)))?.id;
|
||||
const target = legacyComponent && rootForLegacy(legacyComponent);
|
||||
if (target) loose.scene = { mode: 'continue', base: { kind: 'step', id: target.id } };
|
||||
}
|
||||
steps.push(loose);
|
||||
}
|
||||
next.steps = steps;
|
||||
return syncLibraryReferences(next);
|
||||
}
|
||||
|
||||
/** 相邻步骤的显式“接上一步”与默认累加等价,旧保存产生的冗余标记可清除。 */
|
||||
export function removeRedundantSceneMarkers(a: Assembly): Assembly {
|
||||
const next = copyAssembly(a);
|
||||
for (const steps of [next.steps, ...libraryComponents(next).map(c => c.steps)]) for (let i = 1; i < steps.length; i++) {
|
||||
const scene = steps[i].scene;
|
||||
if (!steps[i].sceneMarker && scene?.mode === 'continue' && scene.base.kind === 'step' && !scene.base.componentId && scene.base.id === steps[i - 1].id) delete steps[i].scene;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { ScrewInstallation, Vector3 } from '@/api/experience-types';
|
||||
import type { Assembly } from './assemblyEditor';
|
||||
|
||||
const object = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const vector = (v: unknown, length: number): v is number[] => Array.isArray(v) && v.length === length && v.every(x => typeof x === 'number' && Number.isFinite(x));
|
||||
const unit = (v: unknown): v is Vector3 => vector(v, 3) && Math.abs(Math.hypot(...v) - 1) <= .001;
|
||||
export function normalizedInstallation(value: unknown): ScrewInstallation {
|
||||
if (!object(value)) throw new Error('螺丝工具配置无效。');
|
||||
const m: Record<string, unknown> = { toolQuaternion: [0, 0, 0, 1], approachDuration: .45, engageDuration: .3, tightenDuration: 2.4, retractDuration: .35, toolClearance: .012, ...value };
|
||||
const range = (v: unknown, min: number, max: number) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
|
||||
if (m.type !== 'screw' || typeof m.toolId !== 'string' || !unit(m.axis) || !vector(m.socketPosition, 3)
|
||||
|| !vector(m.toolQuaternion, 4) || Math.abs(Math.hypot(...m.toolQuaternion) - 1) > .001
|
||||
|| !['clockwise', 'counterclockwise'].includes(String(m.direction)) || !range(m.turns, 1, 20) || !Number.isInteger(m.turns)
|
||||
|| !range(m.travel, .00001, .1) || !range(m.toolClearance, .001, .2)
|
||||
|| !range(m.approachDuration, .1, 5) || !range(m.engageDuration, .1, 5) || !range(m.tightenDuration, .5, 20) || !range(m.retractDuration, .1, 5)) throw new Error('请核对工具、拧入轴、插入点、旋转圈数与行程。');
|
||||
return m as unknown as ScrewInstallation;
|
||||
}
|
||||
export function toolConfigProblems(assembly: Assembly): string[] {
|
||||
const errors: string[] = [], ids = new Set<string>(), parts = new Map(assembly.parts.map(p => [p.id, p]));
|
||||
if ((assembly.tools?.length ?? 0) > 32) errors.push('当前播放器最多支持 32 个工具配置,请复用已校准的工具。');
|
||||
for (const tool of assembly.tools ?? []) {
|
||||
if (ids.has(tool.id) || !/^[a-zA-Z0-9_-]{1,100}$/.test(tool.id) || !vector(tool.tipPosition, 3) || tool.tipAxis !== undefined && !unit(tool.tipAxis)) errors.push('工具的编号、工作端或工作方向无效。');
|
||||
ids.add(tool.id);
|
||||
}
|
||||
for (const part of assembly.parts) {
|
||||
if (!part.installation) continue;
|
||||
try { normalizedInstallation(part.installation); } catch (e) { errors.push(`${part.name}:${(e as Error).message}`); }
|
||||
if (!ids.has(part.installation.toolId)) errors.push(`${part.name} 引用的工具尚未配置。`);
|
||||
const seen = new Set<string>();
|
||||
for (let node: typeof part | undefined = part; node && !seen.has(node.id); node = node.parentId ? parts.get(node.parentId) : undefined) {
|
||||
seen.add(node.id);
|
||||
if (Math.max(...node.scale) - Math.min(...node.scale) > 1e-8) errors.push(`${part.name} 及父零件必须等比缩放,才能正确对齐并旋转工具。`);
|
||||
}
|
||||
}
|
||||
return [...new Set(errors)];
|
||||
}
|
||||
|
||||
export const screwDuration = (m: ScrewInstallation) => m.approachDuration + m.engageDuration + m.tightenDuration + m.retractDuration;
|
||||
@@ -0,0 +1,258 @@
|
||||
import type { AssemblyComponentPlan, AssemblyPart, AssemblyStageRef, Vector3 } from '@/api/experience-types';
|
||||
import { assemblyProblems, copyAssembly, entryOffset, newEditorId, type Assembly } from './assemblyEditor';
|
||||
import { screwDuration } from './assemblyToolConfig';
|
||||
import { libraryProblems } from './assemblyLibrary';
|
||||
|
||||
export interface AssemblyStage {
|
||||
id: string; label: string; scope: string; scopeId: string; parts: string[]; entering: string[];
|
||||
offset?: Vector3; kind: 'part' | 'connection';
|
||||
ref: AssemblyStageRef; sceneMode: 'independent' | 'continue'; base?: AssemblyStageRef; problem?: string; resultNodes?: string[];
|
||||
sceneExplicit?: boolean;
|
||||
}
|
||||
export const installedParts = (assembly: Assembly) => new Set(assembly.steps.flatMap(s => s.parts));
|
||||
export function stageDuration(assembly: Assembly, stage: AssemblyStage | undefined): number {
|
||||
if (!stage || stage.kind === 'connection' || stage.offset) return .8;
|
||||
return Math.max(.8, stage.entering.reduce((sum, id) => { const motion = assembly.parts.find(p => p.id === id)?.installation; return sum + (motion ? screwDuration(motion) : 0); }, 0));
|
||||
}
|
||||
export const componentParts = (plan: AssemblyComponentPlan, id: string): string[] => {
|
||||
const walk = (key: string, ancestors: Set<string>): string[] => {
|
||||
if (ancestors.has(key)) throw new Error('组件连接不能形成循环。');
|
||||
const component = plan.components.find(c => c.id === key);
|
||||
if (component) return [...component.parts];
|
||||
const connection = plan.connections.find(c => c.id === key);
|
||||
if (!connection) throw new Error('组件连接引用了不存在的组件。');
|
||||
return connection.members.flatMap(member => walk(member, new Set([...ancestors, key])));
|
||||
};
|
||||
return walk(id, new Set());
|
||||
};
|
||||
export function componentPlanProblems(assembly: Assembly): string[] {
|
||||
const stages = assemblyStages(assembly);
|
||||
const sceneErrors = stages.flatMap(s => s.problem ? [s.problem] : []);
|
||||
if (assembly.sceneSequence !== undefined) {
|
||||
const refs = assembly.sceneSequence;
|
||||
if (!Array.isArray(refs) || !refs.every(validStageRef)) sceneErrors.push('步骤播放顺序无效。');
|
||||
else {
|
||||
const resolved = refs.map(ref => findReferencedStage(stages, ref));
|
||||
if (resolved.some(s => !s) || new Set(resolved).size !== resolved.length || resolved.length !== stages.length) sceneErrors.push('步骤播放顺序包含重复、缺失或不存在的步骤。');
|
||||
}
|
||||
}
|
||||
const plan = assembly.componentPlan;
|
||||
if (!plan) return sceneErrors;
|
||||
const errors: string[] = [...sceneErrors], nodes = new Set<string>(), claimed = new Set<string>(), consumed = new Set<string>();
|
||||
const installed = installedParts(assembly);
|
||||
if (plan.version !== 1) return ['组件流程版本不受支持。'];
|
||||
for (const c of plan.components) {
|
||||
if (!c.name.trim() || !c.parts.length || nodes.has(c.id)) errors.push('组件名称、零件或编号无效。');
|
||||
nodes.add(c.id);
|
||||
for (const id of c.parts) {
|
||||
if (!installed.has(id) || claimed.has(id)) errors.push('组件包含未安装或重复归属的零件。');
|
||||
claimed.add(id);
|
||||
}
|
||||
}
|
||||
const continued = new Set(stages.filter(s => s.kind === 'part' && s.sceneMode === 'continue' && !s.problem).flatMap(s => s.entering));
|
||||
if ([...installed].some(id => !claimed.has(id) && !continued.has(id))) errors.push('请先将当前工作区的零件完成并命名为组件,或将该步骤设为继续拼装。');
|
||||
for (const c of plan.connections) {
|
||||
if (!c.name.trim() || nodes.has(c.id) || c.members.length < 2 || new Set(c.members).size !== c.members.length
|
||||
|| c.members.some(id => !nodes.has(id) || consumed.has(id))) errors.push('连接需要至少两个尚未连接的组件,且必须先制作再连接。');
|
||||
if (c.installOffset.length !== 3 || !c.installOffset.every(Number.isFinite)) errors.push('组件进入方向无效。');
|
||||
c.members.forEach(id => consumed.add(id)); nodes.add(c.id);
|
||||
}
|
||||
const finalParts = new Set(stages.at(-1)?.parts ?? []);
|
||||
const continuesFinalAssembly = continued.size > 0 && [...installed].every(id => finalParts.has(id));
|
||||
if (continued.size > 0 && !continuesFinalAssembly) errors.push('最后一步没有包含全部已安装零件,请调整续装基准或完成总装。');
|
||||
if (plan.components.length > 1 && [...nodes].filter(id => !consumed.has(id)).length !== 1 && !continuesFinalAssembly) errors.push('还有组件未连接,请在“连接组件”中完成总装。');
|
||||
return [...new Set(errors)];
|
||||
}
|
||||
export const stageRefMatches = (stage: AssemblyStage, ref: AssemblyStageRef) => stage.ref.kind === ref.kind && stage.ref.id === ref.id
|
||||
&& (ref.kind !== 'step' || !ref.componentId || stage.ref.kind === 'step' && stage.ref.componentId === ref.componentId);
|
||||
function findReferencedStage(stages: AssemblyStage[], ref: AssemblyStageRef) {
|
||||
const exact = stages.find(s => stageRefMatches(s, ref));
|
||||
if (exact) return exact;
|
||||
const same = stages.filter(s => s.ref.kind === ref.kind && s.ref.id === ref.id);
|
||||
return same.length === 1 ? same[0] : undefined;
|
||||
}
|
||||
export function validStageRef(value: unknown): value is AssemblyStageRef {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const ref = value as Record<string, unknown>;
|
||||
return typeof ref.id === 'string' && !!ref.id && (ref.kind === 'connection' || ref.kind === 'step' && (ref.componentId === undefined || typeof ref.componentId === 'string'));
|
||||
}
|
||||
export function assemblyStages(assembly: Assembly): AssemblyStage[] {
|
||||
const stages: AssemblyStage[] = [];
|
||||
const append = (steps: Assembly['steps'], scope: string, members?: Set<string>, scopeId = scope) => {
|
||||
const visible = new Set<string>();
|
||||
steps.forEach(s => {
|
||||
const entering = members ? s.parts.filter(id => members.has(id)) : [...s.parts];
|
||||
if (!entering.length) return;
|
||||
entering.forEach(id => visible.add(id));
|
||||
stages.push({ id: `${scopeId}:${s.id}`, label: s.label, scope, scopeId, parts: [...visible], entering, kind: 'part', ...(s.componentId ? { offset: s.installOffset ?? [0, .08, 0] } : {}), ref: { kind: 'step', id: s.id, ...(members && scopeId !== 'working' ? { componentId: scopeId } : {}) }, sceneMode: 'independent' });
|
||||
});
|
||||
};
|
||||
const plan = assembly.componentPlan;
|
||||
if (!plan) append(assembly.steps, '整机');
|
||||
else {
|
||||
const completed = new Set<string>();
|
||||
const appendConnections = () => {
|
||||
let added = true;
|
||||
while (added) {
|
||||
added = false;
|
||||
plan.connections.forEach(c => {
|
||||
if (completed.has(c.id) || !c.members.every(id => completed.has(id))) return;
|
||||
stages.push({ id: c.id, label: c.name, scope: '组件总装', scopeId: c.id, kind: 'connection', parts: componentParts(plan, c.id), entering: c.members.slice(1).flatMap(id => componentParts(plan, id)), offset: c.installOffset, ref: { kind: 'connection', id: c.id }, sceneMode: 'continue' });
|
||||
completed.add(c.id); added = true;
|
||||
});
|
||||
}
|
||||
};
|
||||
plan.components.forEach(c => { append(assembly.steps, c.name, new Set(c.parts), c.id); completed.add(c.id); appendConnections(); });
|
||||
const claimed = new Set(plan.components.flatMap(c => c.parts));
|
||||
append(assembly.steps, '当前组件', new Set([...installedParts(assembly)].filter(id => !claimed.has(id))), 'working');
|
||||
}
|
||||
const ordered: AssemblyStage[] = [];
|
||||
if (Array.isArray(assembly.sceneSequence)) for (const ref of assembly.sceneSequence) {
|
||||
if (!validStageRef(ref)) continue;
|
||||
const stage = findReferencedStage(stages, ref);
|
||||
if (stage && !ordered.includes(stage)) ordered.push(stage);
|
||||
}
|
||||
ordered.push(...stages.filter(s => !ordered.includes(s)));
|
||||
const done: AssemblyStage[] = [], results = new Map<string, AssemblyStage>(), previous = new Map<string, AssemblyStage>();
|
||||
const inheritedNodes = new Map<string, Set<string>>();
|
||||
for (const stage of ordered) {
|
||||
const s = stage.ref.kind === 'step' ? assembly.steps.find(s => s.id === stage.ref.id) : undefined;
|
||||
const prior = previous.get(stage.scopeId);
|
||||
// 非分段起点自动接着本工作区的上一进度,不需要逐步写标记。
|
||||
const scene = s?.scene ?? (prior && stage.kind === 'part' ? { mode: 'continue' as const, base: prior.ref } : undefined);
|
||||
stage.sceneExplicit = !!s?.scene;
|
||||
let ancestry = new Set<string>();
|
||||
if (stage.kind === 'connection' && plan) {
|
||||
const connection = plan.connections.find(c => c.id === stage.id)!;
|
||||
const members = connection.members.map(id => results.get(id));
|
||||
const installed = new Set(done.flatMap(s => s.entering));
|
||||
if (members.some(s => !s) || connection.members.some(id => componentParts(plan, id).some(id => !installed.has(id)))) stage.problem = `“${stage.label}”须安排在成员组件完成之后。`;
|
||||
else {
|
||||
const full = members.map((s, i) => [...new Set([...componentParts(plan, connection.members[i]), ...s!.parts])]);
|
||||
stage.parts = [...new Set(full.flat())];
|
||||
const base = new Set(full[0]);
|
||||
stage.entering = [...new Set(full.slice(1).flat())].filter(id => !base.has(id));
|
||||
}
|
||||
} else if (scene?.mode === 'continue') {
|
||||
const base = validStageRef(scene.base) ? findReferencedStage(done, scene.base) : undefined;
|
||||
stage.sceneMode = 'continue'; stage.base = scene.base;
|
||||
if (!base || base.problem) stage.problem = `第 ${done.length + 1} 步的续装基准无效,请选择它之前已完成的步骤。`;
|
||||
else {
|
||||
stage.parts = [...new Set([...base.parts, ...stage.entering])];
|
||||
ancestry = new Set(inheritedNodes.get(base.id));
|
||||
}
|
||||
} else if (scene?.mode === 'independent') {
|
||||
stage.parts = [...stage.entering];
|
||||
} else if (scene) stage.problem = '步骤的展示方式无效,请重新选择独立组装或继续拼装。';
|
||||
ancestry.add(stage.scopeId); stage.resultNodes = [...ancestry]; inheritedNodes.set(stage.id, ancestry);
|
||||
for (const id of ancestry) results.set(id, stage);
|
||||
if (stage.kind === 'part') previous.set(stage.scopeId, stage);
|
||||
done.push(stage);
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
export function assemblyResultParts(assembly: Assembly, nodeId: string) {
|
||||
return assemblyStages(assembly).filter(s => s.resultNodes?.includes(nodeId)).at(-1)?.parts
|
||||
?? (assembly.componentPlan ? componentParts(assembly.componentPlan, nodeId) : []);
|
||||
}
|
||||
|
||||
export function setStepScene(assembly: Assembly, stepId: string, mode: 'independent' | 'continue', base?: AssemblyStageRef): Assembly {
|
||||
const stages = assemblyStages(assembly), target = stages.find(s => s.ref.kind === 'step' && s.ref.id === stepId);
|
||||
if (!target) throw new Error('请先选择一个零件安装步骤。');
|
||||
if (mode === 'continue' && (!base || !validStageRef(base) || !findReferencedStage(stages.slice(0, stages.indexOf(target)), base))) throw new Error('请选择当前步骤之前的进度作为续装基准。');
|
||||
const next = copyAssembly(assembly);
|
||||
next.sceneSequence = stages.map(s => structuredClone(s.ref));
|
||||
next.steps.find(s => s.id === stepId)!.scene = mode === 'continue' ? { mode, base: structuredClone(base!) } : { mode };
|
||||
next.steps.find(s => s.id === stepId)!.sceneMarker = true;
|
||||
const problem = assemblyStages(next).find(s => s.ref.kind === 'step' && s.ref.id === stepId)?.problem;
|
||||
if (problem) throw new Error(problem);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function assertStageNotReferenced(assembly: Assembly, refs: AssemblyStageRef[]) {
|
||||
const dependent = assemblyStages(assembly).find(s => s.sceneExplicit && s.base && refs.some(ref => s.base!.kind === ref.kind && s.base!.id === ref.id));
|
||||
if (dependent) throw new Error(`“${dependent.label}”正在接着此进度拼装,请先修改它的续装基准,再删除。`);
|
||||
}
|
||||
|
||||
/** 上传只包含已编排零件;零件库的剩余文件仍原样保留,允许逐步完成流程。 */
|
||||
export function workflowForSave(assembly: Assembly): Assembly {
|
||||
const next = copyAssembly(assembly), installed = installedParts(next);
|
||||
next.componentLibrary?.components.forEach(c => c.parts.forEach(id => installed.add(id)));
|
||||
const stages = assemblyStages(next);
|
||||
// 仅保存用户明确设置的分段标记;普通后续步骤由播放器按上一进度累加。
|
||||
if (next.sceneSequence || next.steps.some(s => s.scene)) next.sceneSequence = stages.map(s => structuredClone(s.ref));
|
||||
next.parts = next.parts.filter(p => installed.has(p.id));
|
||||
const errors = [...assemblyProblems(next), ...componentPlanProblems(next), ...libraryProblems(next)];
|
||||
if (errors.length) throw new Error(errors[0]);
|
||||
return next;
|
||||
}
|
||||
|
||||
export function installPart(assembly: Assembly, part: AssemblyPart): Assembly {
|
||||
if (installedParts(assembly).has(part.id)) return assembly;
|
||||
const next = copyAssembly(assembly);
|
||||
if (!next.parts.some(p => p.id === part.id)) next.parts.push(structuredClone(part));
|
||||
next.steps.push({ id: newEditorId('step'), label: `安装 ${part.name}`, parts: [part.id] });
|
||||
return next;
|
||||
}
|
||||
|
||||
/** 将当前工作区先收成组件,再作为下一步接到已完成的组件/总装上。 */
|
||||
export function connectCurrentComponent(assembly: Assembly, options: { componentId?: string | null; name: string; targetId: string }) {
|
||||
const next = copyAssembly(assembly), plan = next.componentPlan;
|
||||
if (!plan) throw new Error('请先切换到组件装配。');
|
||||
const consumed = new Set(plan.connections.flatMap(c => c.members));
|
||||
const target = [...plan.components, ...plan.connections].find(c => c.id === options.targetId);
|
||||
if (!target || consumed.has(target.id)) throw new Error('请选择尚未连接的组件,或选择它已完成的总装。');
|
||||
let component = options.componentId ? plan.components.find(c => c.id === options.componentId) : undefined;
|
||||
if (options.componentId && !component) throw new Error('当前组件不存在,请重新选择。');
|
||||
if (component && (component.id === target.id || consumed.has(component.id))) throw new Error('当前组件已参与连接,请选择它已完成的总装继续拼接。');
|
||||
const name = options.name.trim();
|
||||
if (!name || plan.components.some(c => c.name === name && c.id !== component?.id)) throw new Error('请为当前组件填写一个不重复的名称。');
|
||||
if (!component) {
|
||||
const claimed = new Set(plan.components.flatMap(c => c.parts));
|
||||
const continued = new Set(assemblyStages(next).filter(s => s.kind === 'part' && s.sceneMode === 'continue' && !s.problem).flatMap(s => s.entering));
|
||||
const parts = [...installedParts(next)].filter(id => !claimed.has(id) && !continued.has(id));
|
||||
if (!parts.length) throw new Error('请先点选当前组件的零件。');
|
||||
component = { id: newEditorId('component'), name, parts }; plan.components.push(component);
|
||||
} else component.name = name;
|
||||
const connection = { id: newEditorId('connection'), name: `${target.name} + ${component.name}`, members: [target.id, component.id], installOffset: entryOffset('y+', 80) };
|
||||
plan.connections.push(connection);
|
||||
return { assembly: next, connectionId: connection.id };
|
||||
}
|
||||
|
||||
function removeComponentParts(next: Assembly, removed: Set<string>) {
|
||||
if (next.componentPlan) {
|
||||
const plan = next.componentPlan;
|
||||
plan.components.forEach(c => { c.parts = c.parts.filter(id => !removed.has(id)); });
|
||||
const empty = new Set(plan.components.filter(c => !c.parts.length).map(c => c.id));
|
||||
plan.components = plan.components.filter(c => !empty.has(c.id));
|
||||
plan.connections = plan.connections.filter(c => { if (c.members.some(id => empty.has(id))) { empty.add(c.id); return false; } return true; });
|
||||
assertStageNotReferenced(next, [...empty].map(id => ({ kind: 'connection', id })));
|
||||
}
|
||||
}
|
||||
|
||||
/** 从流程移除一个零件,保留同一步的其他零件和原文件。 */
|
||||
export function removeWorkflowPart(assembly: Assembly, partId: string): Assembly {
|
||||
if (!installedParts(assembly).has(partId)) return assembly;
|
||||
assertStageNotReferenced(assembly, assembly.steps.filter(s => s.parts.includes(partId) && s.parts.length === 1).map(s => ({ kind: 'step', id: s.id })));
|
||||
const installed = installedParts(assembly), byId = new Map(assembly.parts.map(p => [p.id, p]));
|
||||
for (const p of assembly.parts.filter(p => installed.has(p.id) && p.id !== partId)) {
|
||||
const seen = new Set<string>();
|
||||
for (let id = p.parentId; id && !seen.has(id); id = byId.get(id)?.parentId ?? null) {
|
||||
if (id === partId) throw new Error(`请先移除子零件“${p.name}”,再移除此零件。`);
|
||||
seen.add(id);
|
||||
}
|
||||
}
|
||||
const next = copyAssembly(assembly);
|
||||
next.steps = next.steps.map(s => ({ ...s, parts: s.parts.filter(id => id !== partId) })).filter(s => s.parts.length);
|
||||
removeComponentParts(next, new Set([partId]));
|
||||
return next;
|
||||
}
|
||||
|
||||
export function removeWorkflowStep(assembly: Assembly, stepId: string): Assembly {
|
||||
assertStageNotReferenced(assembly, [{ kind: 'step', id: stepId }]);
|
||||
const next = copyAssembly(assembly), removed = new Set(next.steps.find(s => s.id === stepId)?.parts ?? []);
|
||||
next.steps = next.steps.filter(s => s.id !== stepId);
|
||||
removeComponentParts(next, removed);
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import type { ProjectView, SelectedFile } from '@/api/types';
|
||||
import { assemblyProblems, copyAssembly, prepareAssemblySession, type Assembly, type AssemblyDocument, type AssemblySession } from './assemblyEditor';
|
||||
import type { ExperienceFileSelections } from './experienceFiles';
|
||||
import { experiencePathProblem, safeExperienceUrl } from './modelAssets';
|
||||
import { componentPlanProblems, validStageRef } from './assemblyWorkflow';
|
||||
import { normalizedInstallation } from './assemblyToolConfig';
|
||||
import { libraryProblems } from './assemblyLibrary';
|
||||
|
||||
const record = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const vector = (value: unknown, length: number) => Array.isArray(value) && value.length === length && value.every(v => typeof v === 'number' && Number.isFinite(v));
|
||||
|
||||
/** 只接受编辑器能理解的版本;读取失败绝不退回空流程,以免覆盖已上传数据。 */
|
||||
export function restoreAssemblyDocument(value: unknown, session: AssemblySession): AssemblySession {
|
||||
if (!record(value) || value.schemaVersion !== 1 || value.kind !== 'assembly' || value.unit !== 'meter'
|
||||
|| typeof value.title !== 'string' || !vector(value.displayQuaternion, 4)
|
||||
|| !Array.isArray(value.files) || !Array.isArray(value.parts) || !Array.isArray(value.steps)) {
|
||||
throw new Error('当前装配 JSON 格式暂不支持可视化编辑,原流程已保留。请使用 schemaVersion=1、kind=assembly、unit=meter 的流程。');
|
||||
}
|
||||
const byPath = new Map(session.sources.map(s => [s.asset.relativePath, s.asset]));
|
||||
const declared = new Set<string>();
|
||||
for (const item of value.files) {
|
||||
if (!record(item) || typeof item.path !== 'string' || experiencePathProblem(item.path) || declared.has(item.path)
|
||||
|| typeof item.bytes !== 'number' || !Number.isSafeInteger(item.bytes) || item.bytes <= 0
|
||||
|| typeof item.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(item.sha256)) throw new Error('当前装配 JSON 的文件清单无效,原流程已保留。');
|
||||
declared.add(item.path);
|
||||
const source = byPath.get(item.path);
|
||||
if (!source) throw new Error(`装配流程缺少零件文件:${item.path}。请先补充上传,原流程已保留。`);
|
||||
if (source.bytes !== item.bytes || source.sha256 !== item.sha256) throw new Error(`装配流程与当前零件内容不一致:${item.path}。请核对后重试,原流程已保留。`);
|
||||
}
|
||||
const library = value.componentLibrary;
|
||||
if (library !== undefined && (!record(library) || library.version !== 1 || !Array.isArray(library.components) || !Array.isArray(library.parts)
|
||||
|| !library.components.every(c => record(c) && typeof c.id === 'string' && typeof c.name === 'string' && (c.parentId === null || typeof c.parentId === 'string')
|
||||
&& Array.isArray(c.parts) && c.parts.every(id => typeof id === 'string') && Array.isArray(c.steps)))) throw new Error('组件库数据无效,原流程已保留。');
|
||||
const parts = [...value.parts, ...(record(library) ? library.parts as unknown[] : [])].map(item => {
|
||||
if (!record(item) || typeof item.id !== 'string' || typeof item.file !== 'string' || !declared.has(item.file)
|
||||
|| !(item.parentId === null || typeof item.parentId === 'string')
|
||||
|| item.name !== undefined && typeof item.name !== 'string'
|
||||
|| !vector(item.position, 3) || !vector(item.quaternion, 4) || !vector(item.scale, 3) || !vector(item.installOffset, 3)) {
|
||||
throw new Error('当前装配 JSON 的零件数据无效,原流程已保留。');
|
||||
}
|
||||
return { ...item, assetId: byPath.get(item.file)!.assetId, name: item.name ?? item.file.split('/').pop()!.replace(/\.glb$/i, ''), ...(item.installation === undefined ? {} : { installation: normalizedInstallation(item.installation) }) } as Assembly['parts'][number];
|
||||
});
|
||||
const readSteps = (values: unknown[]) => values.map(item => {
|
||||
if (!record(item) || typeof item.id !== 'string' || typeof item.label !== 'string'
|
||||
|| !Array.isArray(item.parts) || !item.parts.every(p => typeof p === 'string')) throw new Error('当前装配 JSON 的步骤数据无效,原流程已保留。');
|
||||
if (item.scene !== undefined && (!record(item.scene) || !['independent', 'continue'].includes(String(item.scene.mode)) || item.scene.mode === 'continue' && !validStageRef(item.scene.base))) throw new Error('当前装配 JSON 的步骤展示方式无效,原流程已保留。');
|
||||
if (item.componentId !== undefined && typeof item.componentId !== 'string') throw new Error('组件引用格式无效,原流程已保留。');
|
||||
if (item.sceneMarker !== undefined && (item.sceneMarker !== true || item.scene === undefined)) throw new Error('拼装分段标记无效,原流程已保留。');
|
||||
if (item.installOffset !== undefined && !vector(item.installOffset, 3)) throw new Error('组件进入方向无效,原流程已保留。');
|
||||
return { ...item, id: item.id, label: item.label, parts: [...item.parts] as string[] };
|
||||
});
|
||||
const steps = readSteps(value.steps);
|
||||
const assembly: Assembly = {
|
||||
enabled: true, title: value.title, unit: 'meter', referenceAssetId: null,
|
||||
displayQuaternion: value.displayQuaternion as Assembly['displayQuaternion'], parts, steps, editorGroups: [],
|
||||
};
|
||||
if (record(library)) assembly.componentLibrary = { version: 1, components: (library.components as Record<string, unknown>[]).map(c => ({ id: c.id as string, name: c.name as string, parentId: c.parentId as string | null, parts: [...c.parts as string[]], steps: readSteps(c.steps as unknown[]) })) };
|
||||
if (value.sceneSequence !== undefined) {
|
||||
if (!Array.isArray(value.sceneSequence) || !value.sceneSequence.every(validStageRef)) throw new Error('步骤播放顺序无效,原流程已保留。');
|
||||
assembly.sceneSequence = structuredClone(value.sceneSequence);
|
||||
}
|
||||
if (value.tools !== undefined) {
|
||||
if (!Array.isArray(value.tools)) throw new Error('工具清单无效,原流程已保留。');
|
||||
assembly.tools = value.tools.map(tool => {
|
||||
if (!record(tool) || typeof tool.id !== 'string' || typeof tool.file !== 'string' || !declared.has(tool.file) || !vector(tool.tipPosition, 3)
|
||||
|| tool.tipAxis !== undefined && !vector(tool.tipAxis, 3)) throw new Error('工具工作端配置无效,原流程已保留。');
|
||||
return { id: tool.id, assetId: byPath.get(tool.file)!.assetId, tipPosition: tool.tipPosition as [number, number, number], ...(tool.tipAxis ? { tipAxis: tool.tipAxis as [number, number, number] } : {}), ...(typeof tool.name === 'string' ? { name: tool.name } : {}) };
|
||||
});
|
||||
}
|
||||
if (value.componentPlan !== undefined) {
|
||||
const p = value.componentPlan;
|
||||
if (!record(p) || p.version !== 1 || !Array.isArray(p.components) || !Array.isArray(p.connections)
|
||||
|| !p.components.every(c => record(c) && typeof c.id === 'string' && typeof c.name === 'string' && Array.isArray(c.parts) && c.parts.every(id => typeof id === 'string'))
|
||||
|| !p.connections.every(c => record(c) && typeof c.id === 'string' && typeof c.name === 'string' && Array.isArray(c.members) && c.members.every(id => typeof id === 'string') && vector(c.installOffset, 3))) throw new Error('组件流程数据无效,原流程已保留。');
|
||||
assembly.componentPlan = structuredClone(p) as unknown as Assembly['componentPlan'];
|
||||
}
|
||||
const problems = [...assemblyProblems(assembly), ...componentPlanProblems(assembly), ...libraryProblems(assembly)];
|
||||
if (problems.length) throw new Error(`当前流程无法编辑:${problems[0]} 原流程已保留。`);
|
||||
return { ...session, assembly: copyAssembly(assembly), manifest: structuredClone(value) as AssemblyDocument, catalog: copyAssembly(assembly).parts };
|
||||
}
|
||||
|
||||
export async function prepareBoundAssemblySession(project: ProjectView, files: ExperienceFileSelections, plan: AssemblySession | null, signal: AbortSignal, progress: (message: string) => void): Promise<AssemblySession> {
|
||||
signal.throwIfAborted();
|
||||
if (plan) return prepareAssemblySession(plan, plan.assembly, [], files);
|
||||
const download = async (value: string | null | undefined, label: string) => {
|
||||
const url = safeExperienceUrl(value);
|
||||
if (!url) throw new Error(`${label}下载地址无效`);
|
||||
const response = await fetch(url, { signal, credentials: 'omit' });
|
||||
if (!response.ok) throw new Error(`${label}下载失败(${response.status}),请重试`);
|
||||
return response;
|
||||
};
|
||||
let manifest: unknown;
|
||||
if (project.assemblyJsonUrl) {
|
||||
progress('正在读取已上传的装配流程…');
|
||||
const response = await download(project.assemblyJsonUrl, '装配流程');
|
||||
try { manifest = JSON.parse((await response.text()).replace(/^\uFEFF/, '')); }
|
||||
catch { throw new Error('装配 JSON 无法解析,原流程已保留。请核对文件后重试。'); }
|
||||
}
|
||||
let sourceFiles = files;
|
||||
if (!files.parts.selected.length && project.modelPartsFiles?.length) {
|
||||
const resources = project.modelPartsFiles;
|
||||
const selected: SelectedFile[] = new Array(resources.length);
|
||||
let index = 0, done = 0, failed = false;
|
||||
progress(`正在载入已上传零件 0 / ${resources.length}…`);
|
||||
const worker = async () => {
|
||||
while (!failed && index < resources.length) {
|
||||
const i = index++, resource = resources[i];
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
const response = await download(resource.url, `零件 ${resource.relativePath}`);
|
||||
const blob = await response.blob();
|
||||
if (blob.size !== resource.sizeBytes) throw new Error(`零件大小与绑定记录不一致:${resource.relativePath}`);
|
||||
selected[i] = { relativePath: resource.relativePath, file: new File([blob], resource.relativePath.split('/').pop()!, { type: 'model/gltf-binary' }) };
|
||||
progress(`正在载入已上传零件 ${++done} / ${resources.length}…`);
|
||||
} catch (cause) { failed = true; throw cause; }
|
||||
}
|
||||
};
|
||||
const outcomes = await Promise.allSettled(Array.from({ length: Math.min(4, resources.length) }, worker));
|
||||
const failure = outcomes.find((r): r is PromiseRejectedResult => r.status === 'rejected');
|
||||
if (failure) throw failure.reason;
|
||||
sourceFiles = { ...files, parts: { ...files.parts, selected, problems: [], checking: false } };
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
progress('正在校验零件并准备装配编辑器…');
|
||||
let session = await prepareAssemblySession(null, null, [], sourceFiles);
|
||||
signal.throwIfAborted();
|
||||
if (!session.sources.length) throw new Error('请先上传零件模型,再制作装配流程。');
|
||||
if (project.assemblyJsonUrl) session = restoreAssemblyDocument(manifest, session);
|
||||
const known = new Map(session.assembly.parts.map(p => [p.assetId, p]));
|
||||
const tools = record(manifest) && Array.isArray(manifest.tools) ? new Set(manifest.tools.filter(record).map(t => t.file)) : new Set();
|
||||
const extra = session.sources.filter(s => !known.has(s.asset.assetId) && !tools.has(s.asset.relativePath));
|
||||
if (project.modelGlbUrl && (!project.assemblyJsonUrl || extra.length)) {
|
||||
progress('正在读取整机 GLB,匹配零件安装位置…');
|
||||
const whole = await (await download(project.modelGlbUrl, '整机模型')).blob();
|
||||
const { placeFromWhole } = await import('./assemblyPlacement');
|
||||
const placed = await placeFromWhole(session, whole, signal);
|
||||
if (project.assemblyJsonUrl) {
|
||||
placed.assembly = session.assembly;
|
||||
placed.catalog = placed.catalog?.filter(p => !tools.has(session.sources.find(s => s.asset.assetId === p.assetId)?.asset.relativePath)).map(p => known.get(p.assetId) ?? p);
|
||||
placed.unplaced = placed.unplaced?.filter(id => !session.assembly.parts.some(p => p.id === id));
|
||||
}
|
||||
session = placed;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import * as THREE from 'three';
|
||||
|
||||
// 自包含的小型 GLB,不依赖用户文件或运行时导出器。
|
||||
function binaryGlb(root: THREE.Object3D) {
|
||||
root.updateMatrixWorld(true);
|
||||
const chunks: Uint8Array[] = [], views: object[] = [], accessors: object[] = [], meshes: object[] = [], nodes: object[] = [], materials: object[] = [];
|
||||
let offset = 0;
|
||||
root.traverse(object => {
|
||||
const mesh = object as THREE.Mesh; if (!mesh.isMesh) return;
|
||||
const geometry = mesh.geometry.index ? mesh.geometry.toNonIndexed() : mesh.geometry;
|
||||
const attrs: Record<string, number> = {};
|
||||
for (const [name, semantic] of [['position', 'POSITION'], ['normal', 'NORMAL']]) {
|
||||
const attr = geometry.getAttribute(name); if (!attr) continue;
|
||||
const array = new Float32Array(attr.count * 3), min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
||||
for (let i = 0; i < attr.count; i++) for (let j = 0; j < 3; j++) { const value = [attr.getX(i), attr.getY(i), attr.getZ(i)][j]; array[i * 3 + j] = value; min[j] = Math.min(min[j], value); max[j] = Math.max(max[j], value); }
|
||||
const bytes = new Uint8Array(array.buffer); chunks.push(bytes); views.push({ buffer: 0, byteOffset: offset, byteLength: bytes.length }); offset += bytes.length;
|
||||
attrs[semantic] = accessors.length; accessors.push({ bufferView: views.length - 1, componentType: 5126, count: attr.count, type: 'VEC3', ...(name === 'position' ? { min, max } : {}) });
|
||||
}
|
||||
const material = mesh.material as THREE.MeshStandardMaterial;
|
||||
materials.push({ pbrMetallicRoughness: { baseColorFactor: [...material.color.toArray(), 1], metallicFactor: material.metalness, roughnessFactor: material.roughness } });
|
||||
meshes.push({ primitives: [{ attributes: attrs, material: materials.length - 1 }] }); nodes.push({ name: `node-${nodes.length}`, mesh: meshes.length - 1, matrix: mesh.matrixWorld.toArray() });
|
||||
if (geometry !== mesh.geometry) geometry.dispose();
|
||||
});
|
||||
const raw = new TextEncoder().encode(JSON.stringify({ asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: nodes.map((_, i) => i) }], nodes, meshes, materials, accessors, bufferViews: views, buffers: [{ byteLength: offset }] }));
|
||||
const jsonLength = Math.ceil(raw.length / 4) * 4, bytes = new Uint8Array(28 + jsonLength + offset), h = new DataView(bytes.buffer);
|
||||
h.setUint32(0, 0x46546c67, true); h.setUint32(4, 2, true); h.setUint32(8, bytes.length, true); h.setUint32(12, jsonLength, true); h.setUint32(16, 0x4e4f534a, true); bytes.fill(32, 20, 20 + jsonLength); bytes.set(raw, 20);
|
||||
h.setUint32(20 + jsonLength, offset, true); h.setUint32(24 + jsonLength, 0x004e4942, true); let at = 28 + jsonLength; for (const chunk of chunks) { bytes.set(chunk, at); at += chunk.length; }
|
||||
return Array.from(bytes);
|
||||
}
|
||||
export async function toolFixtures() {
|
||||
const screw = new THREE.Group(), steel = new THREE.MeshStandardMaterial({ color: '#b6c5d8', metalness: .75, roughness: .3 });
|
||||
const shaft = new THREE.Mesh(new THREE.CylinderGeometry(.001, .001, .014, 32), steel); shaft.position.y = -.002;
|
||||
const head = new THREE.Mesh(new THREE.CylinderGeometry(.003, .003, .003, 32), steel); head.position.y = .0065; screw.add(shaft, head);
|
||||
const driver = new THREE.Group(), toolShaft = new THREE.Mesh(new THREE.CylinderGeometry(.0008, .0008, .02, 24), steel); toolShaft.rotation.x = Math.PI / 2; toolShaft.position.z = .02;
|
||||
const handle = new THREE.Mesh(new THREE.CylinderGeometry(.004, .004, .022, 24), new THREE.MeshStandardMaterial({ color: '#e1a230', roughness: .4 })); handle.rotation.x = Math.PI / 2; handle.position.z = .041; driver.add(toolShaft, handle);
|
||||
return { screw: binaryGlb(screw), driver: binaryGlb(driver) };
|
||||
}
|
||||
+566
-72
@@ -1,5 +1,6 @@
|
||||
import { expect, test, type Page, type Route } from '@playwright/test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { createServer } from 'node:http';
|
||||
@@ -461,15 +462,16 @@ function editorGlb(x = 0, color = [0.18, 0.65, 0.45, 1]) {
|
||||
}
|
||||
async function editorDialog(page: Page) {
|
||||
await page.getByRole('button', { name: '制作装配流程', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: '制作装配流程 可视化编辑' });
|
||||
const dialog = page.getByRole('dialog', { name: '装配流程 可视化编排' });
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(dialog).toHaveCSS('animation-name', 'none');
|
||||
await expect(dialog.locator('.assembly-loading')).toHaveCount(0, { timeout: 15000 });
|
||||
await expect(dialog.locator('.assembly-preview-problem')).toHaveCount(0);
|
||||
return dialog;
|
||||
}
|
||||
async function generatedManifest(page: Page) {
|
||||
const dialog = page.getByRole('dialog', { name: '制作装配流程 可视化编辑' });
|
||||
await dialog.getByText('高级:导出步骤 JSON', { exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: '装配流程 可视化编排' });
|
||||
if (!await dialog.getByRole('button', { name: '下载系统生成的 JSON' }).isVisible()) await dialog.getByText('更多操作', { exact: true }).click();
|
||||
const download = page.waitForEvent('download');
|
||||
await dialog.getByRole('button', { name: '下载系统生成的 JSON' }).click();
|
||||
const stream = await (await download).createReadStream();
|
||||
@@ -477,58 +479,81 @@ async function generatedManifest(page: Page) {
|
||||
return JSON.parse(Buffer.concat(chunks).toString());
|
||||
}
|
||||
|
||||
test('本地 GLB 可三维点选、分组、编辑排序、撤销和生成 JSON,无需后端接口', async ({ page }, testInfo) => {
|
||||
test('简化装配:默认空场景,右侧搜索点选即安装,顺序可调整撤销,原材质文件保留', async ({ page }, testInfo) => {
|
||||
const state = await workspace(page, { missing: true });
|
||||
await expect(page.getByRole('button', { name: '选择拼装步骤 JSON', exact: true })).toBeHidden();
|
||||
const parts = ['左腿', '躯干', '右腿'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb((i - 1) * .35) }));
|
||||
await chooseFiles(page, parts, '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
const canvas = dialog.locator('canvas');
|
||||
await canvas.click();
|
||||
await expect(dialog.locator('.assembly-part-row input:checked')).toHaveCount(1);
|
||||
await dialog.getByRole('button', { name: '清空选择', exact: true }).click();
|
||||
await dialog.getByRole('checkbox', { name: '选择零件 左腿', exact: true }).check();
|
||||
await dialog.getByRole('checkbox', { name: '选择零件 躯干', exact: true }).check();
|
||||
await dialog.getByRole('textbox', { name: '零件分组名称' }).fill('主体与左腿');
|
||||
await dialog.getByRole('button', { name: '存为组', exact: true }).click();
|
||||
await expect(dialog.getByRole('button', { name: '主体与左腿 · 2' })).toBeVisible();
|
||||
await dialog.getByText('Y 正侧 → 原位', { exact: true }).click();
|
||||
await page.getByText('X 负侧 → 原位', { exact: true }).click();
|
||||
await dialog.getByRole('spinbutton', { name: '进入距离(毫米)', exact: true }).fill('120');
|
||||
await expect(dialog.getByText('所选零件进入预览', { exact: true })).toBeVisible();
|
||||
await dialog.getByRole('textbox', { name: '新步骤名称' }).fill('安装主体与左腿');
|
||||
await dialog.getByRole('button', { name: '添加步骤', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '尚未安排', exact: true }).click();
|
||||
await dialog.getByRole('textbox', { name: '新步骤名称' }).fill('安装右腿');
|
||||
await dialog.getByRole('button', { name: '添加步骤', exact: true }).click();
|
||||
await expect(dialog.getByRole('button', { name: '保存装配流程', exact: true })).toBeEnabled();
|
||||
await dialog.getByRole('button', { name: '复制第 1 步设置', exact: true }).click();
|
||||
await expect(dialog.getByRole('button', { name: '保存装配流程', exact: true })).toBeDisabled();
|
||||
await expect(dialog.getByText('第 2 步还没有选择零件。', { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText('从第一个选择开始')).toBeVisible();
|
||||
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeDisabled();
|
||||
await dialog.getByRole('textbox', { name: '搜索组件或零件' }).fill('躯干');
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(1);
|
||||
await dialog.getByRole('button', { name: '安装零件 躯干', exact: true }).click();
|
||||
await expect(dialog.getByText('1 / 1 · 安装 躯干')).toBeVisible();
|
||||
await dialog.getByRole('textbox', { name: '搜索组件或零件' }).fill('');
|
||||
await dialog.getByRole('button', { name: '安装零件 左腿', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '查看零件 躯干', exact: true }).click();
|
||||
await dialog.getByRole('tab', { name: '步骤 2', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '上移第 2 步' }).click();
|
||||
await expect(dialog.locator('.assembly-step-list > li').first()).toContainText('左腿');
|
||||
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
const rows = dialog.locator('.assembly-step-list > li');
|
||||
await rows.nth(1).dragTo(rows.nth(0));
|
||||
await expect(rows.nth(0)).toContainText('安装右腿');
|
||||
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
await expect(rows.nth(0)).toContainText('安装主体与左腿');
|
||||
await expect(dialog.locator('.assembly-step-list > li').first()).toContainText('躯干');
|
||||
await dialog.getByRole('button', { name: '重做', exact: true }).click();
|
||||
await expect(rows.nth(0)).toContainText('安装右腿');
|
||||
const manifest = await generatedManifest(page);
|
||||
expect(manifest.schemaVersion).toBe(1);
|
||||
expect(manifest.steps.map((s: any) => s.label)).toEqual(['安装右腿', '安装主体与左腿']);
|
||||
expect(manifest.parts).toHaveLength(3);
|
||||
for (const part of manifest.parts) {
|
||||
expect(part.installOffset).toEqual([-.12, 0, 0]); expect(part.quaternion).toEqual([0,0,0,1]); expect(part.position).toEqual([0,0,0]);
|
||||
}
|
||||
const { createHash } = await import('node:crypto');
|
||||
manifest.files.forEach((file: any) => { const input = parts.find((p) => p.name === file.path)!; expect(file.bytes).toBe(input.buffer.length); expect(file.sha256).toBe(createHash('sha256').update(input.buffer).digest('hex')); });
|
||||
await dialog.getByRole('button', { name: '播放完整流程', exact: true }).click();
|
||||
await expect(dialog.getByText('预览第 2 步:安装主体与左腿', { exact: true })).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath('assembly-editor.png'), fullPage: true });
|
||||
expect(manifest.steps.map((s: any) => s.label)).toEqual(['安装 左腿', '安装 躯干']);
|
||||
expect(manifest.parts).toHaveLength(2);
|
||||
expect(manifest.componentPlan).toBeUndefined();
|
||||
manifest.files.forEach((f: any) => { const input = parts.find(p => p.name === f.path)!; expect(f.bytes).toBe(input.buffer.length); expect(f.sha256).toBe(createHash('sha256').update(input.buffer).digest('hex')); });
|
||||
await dialog.getByRole('button', { name: '播放全部步骤' }).click();
|
||||
await expect(dialog.getByText('2 / 2 · 安装 躯干')).toBeVisible();
|
||||
await page.screenshot({ path: testInfo.outputPath('assembly-editor-dark.png'), fullPage: true });
|
||||
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
|
||||
await expect(page.getByText(/装配流程已在本页保留/)).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: '保存设置', exact: true })).toBeDisabled();
|
||||
expect(state.calls.filter((call) => call.method !== 'GET')).toHaveLength(0);
|
||||
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('双视窗:左侧参考可点选隐藏、搜索恢复,显隐与右侧步骤、撤销和保存相互独立', async ({ page }, testInfo) => {
|
||||
await workspace(page, { missing: true });
|
||||
const files = ['左腿', '躯干', '右腿'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb((i - 1) * .35) }));
|
||||
await chooseFiles(page, files, '选择零件文件夹');
|
||||
const dialog = await editorDialog(page), reference = dialog.locator('.assembly-reference-stage'), work = dialog.locator('.assembly-stage');
|
||||
await expect(reference.locator('canvas[aria-label="整机参考三维预览"]')).toBeVisible();
|
||||
await expect(work.locator('canvas[aria-label="装配模型三维预览"]')).toBeVisible();
|
||||
await expect(reference.getByText('3 / 3 显示', { exact: true })).toBeVisible();
|
||||
await expect(work.getByText('从第一个选择开始', { exact: true })).toBeVisible();
|
||||
// Locator 点击会等待弹窗位置稳定,避免在展开动画中取到临时坐标。
|
||||
await reference.locator('canvas').click();
|
||||
await expect(reference.getByText('2 / 3 显示', { exact: true })).toBeVisible();
|
||||
await reference.getByRole('button', { name: '参考零件显隐', exact: true }).click();
|
||||
const visibility = page.getByRole('group', { name: '参考模型零件显隐' });
|
||||
await visibility.getByRole('button', { name: '显示参考零件 躯干', exact: true }).click();
|
||||
await visibility.getByRole('textbox', { name: '搜索参考零件', exact: true }).fill('左腿');
|
||||
await visibility.getByRole('button', { name: '隐藏参考零件 左腿', exact: true }).click();
|
||||
await visibility.locator('.ant-segmented').getByText('已隐藏', { exact: true }).click();
|
||||
await expect(visibility.locator('.assembly-reference-visibility-list > button')).toHaveCount(1);
|
||||
await reference.getByRole('button', { name: '参考零件显隐', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '恢复整机参考', exact: true }).click();
|
||||
await expect(reference.getByText('3 / 3 显示', { exact: true })).toBeVisible();
|
||||
await reference.getByRole('button', { name: '参考零件显隐', exact: true }).click();
|
||||
await visibility.locator('.ant-segmented').getByText('全部', { exact: true }).click();
|
||||
await visibility.getByRole('textbox', { name: '搜索参考零件', exact: true }).fill('躯干');
|
||||
await visibility.getByRole('button', { name: '隐藏参考零件 躯干', exact: true }).click();
|
||||
await reference.getByRole('button', { name: '参考零件显隐', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '安装零件 左腿', exact: true }).click();
|
||||
await expect(reference.getByText('2 / 3 显示', { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText('1 / 1 · 安装 左腿', { exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
await expect(reference.getByText('2 / 3 显示', { exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '重做', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '查看零件 左腿', exact: true }).click();
|
||||
const json = await generatedManifest(page);
|
||||
expect(json.parts.map((p: any) => p.name)).toEqual(['左腿']); expect(json.steps).toHaveLength(1);
|
||||
expect(json.files[0].sha256).toBe(createHash('sha256').update(files[0].buffer).digest('hex'));
|
||||
expect(Object.keys(json).some(key => /hidden|visibility/i.test(key))).toBe(false);
|
||||
await reference.getByRole('button', { name: '全部显示', exact: true }).click();
|
||||
await expect(dialog.getByText('1 / 1 · 安装 左腿', { exact: true })).toBeVisible();
|
||||
await page.setViewportSize({ width: 1366, height: 768 });
|
||||
await expect.poll(() => dialog.locator('.ant-modal-body').evaluate(el => el.scrollHeight <= el.clientHeight + 1)).toBe(true);
|
||||
await page.screenshot({ path: testInfo.outputPath('assembly-dual-view.png'), fullPage: true });
|
||||
});
|
||||
|
||||
test('可视化编辑保留导入位姿和父子关系,保存为真实草稿并校验父件顺序', async ({ page }) => {
|
||||
@@ -541,6 +566,7 @@ test('可视化编辑保留导入位姿和父子关系,保存为真实草稿
|
||||
], steps: [{ id: 'step-base', label: '安装底座', parts: ['base'] }, { id: 'step-leg', label: '安装左腿', parts: ['leg'] }] };
|
||||
const state = await workspace(page, { assets, view: draftView({ assembly }) });
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByRole('tab', { name: '步骤 2', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '上移第 2 步', exact: true }).click();
|
||||
await expect(dialog.getByText('请把 左腿 的父零件安排在同一步或更早安装。', { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByRole('button', { name: '保存装配流程', exact: true })).toBeDisabled();
|
||||
@@ -563,8 +589,7 @@ test('本地制作流程在零件上传后自动关联服务器资源,构建
|
||||
await page.route('https://uploads.example.com/**', (route) => route.fulfill({ status: 204 }));
|
||||
await chooseFiles(page, [{ name: 'leg.glb', mimeType: 'model/gltf-binary', buffer: bytes }], '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByRole('button', { name: '全选结果', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '添加步骤', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '安装零件 leg', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
|
||||
await expect(page.getByRole('button', { name: '保存设置', exact: true })).toBeDisabled();
|
||||
expect(state.calls.filter((c) => c.method === 'PUT')).toHaveLength(0);
|
||||
@@ -586,9 +611,7 @@ test('新建项目中制作的装配流程与原文件一起带入项目管理',
|
||||
const bytes = editorGlb();
|
||||
await chooseFiles(page, [{ name: '零件.glb', mimeType: 'model/gltf-binary', buffer: bytes }], '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByRole('button', { name: '全选结果', exact: true }).click();
|
||||
await dialog.getByRole('textbox', { name: '新步骤名称' }).fill('安装主体');
|
||||
await dialog.getByRole('button', { name: '添加步骤', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '安装零件 零件', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
|
||||
await expect(page.getByText('已制作 1 个步骤,创建项目后会保留。', { exact: true })).toBeVisible();
|
||||
await page.route('**/admin-api/projects', (route) => ok(route, { projectCode: 'project-a' }));
|
||||
@@ -597,28 +620,107 @@ test('新建项目中制作的装配流程与原文件一起带入项目管理',
|
||||
await expect(page.getByRole('cell', { name: '零件.glb', exact: true })).toBeVisible();
|
||||
await expect(page.getByText('1 个零件实例 · 1 步', { exact: true })).toBeVisible();
|
||||
const reopened = await editorDialog(page);
|
||||
await expect(reopened.locator('.assembly-step-list')).toContainText('安装主体');
|
||||
await reopened.getByRole('tab', { name: '步骤 1', exact: true }).click();
|
||||
await expect(reopened.locator('.assembly-step-list')).toContainText('安装 零件');
|
||||
expect(state.calls.filter((c) => c.method === 'PUT')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('复制步骤后可用另一组零件填充副本,批量进入设置不会重复安装', async ({ page }) => {
|
||||
test('统一编排:组件和散件同屏选择,组件成员自动选中,重复成员不能再加入', async ({ page }, testInfo) => {
|
||||
await workspace(page, { missing: true });
|
||||
await chooseFiles(page, ['left', 'right'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb(i * .4) })), '选择零件文件夹');
|
||||
await chooseFiles(page, ['头壳', '头盖', '躯干', '手臂'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb(i * .2) })), '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByRole('checkbox', { name: '选择零件 left', exact: true }).check();
|
||||
await dialog.getByRole('spinbutton', { name: '进入距离(毫米)', exact: true }).fill('160');
|
||||
await dialog.getByRole('textbox', { name: '新步骤名称' }).fill('安装左侧');
|
||||
await dialog.getByRole('button', { name: '添加步骤', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '复制第 1 步设置', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '尚未安排', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '替换此步零件', exact: true }).click();
|
||||
await dialog.getByRole('textbox', { name: '当前步骤名称' }).fill('安装右侧');
|
||||
const manifest = await generatedManifest(page);
|
||||
expect(manifest.steps).toHaveLength(2);
|
||||
expect(manifest.steps[0].parts).toHaveLength(1);
|
||||
expect(manifest.steps[1].parts).toHaveLength(1);
|
||||
expect(manifest.steps[0].parts[0]).not.toBe(manifest.steps[1].parts[0]);
|
||||
manifest.parts.forEach((part: any) => expect(part.installOffset).toEqual([0, .16, 0]));
|
||||
await dialog.getByRole('button', { name: '创建组件', exact: true }).first().click();
|
||||
await page.getByRole('textbox', { name: '独立组件名称' }).fill('头部');
|
||||
await page.getByRole('button', { name: '创建并制作' }).click();
|
||||
for (const name of ['头壳', '头盖']) await dialog.getByRole('button', { name: `安装零件 ${name}`, exact: true }).click();
|
||||
await dialog.getByText('步骤编排', { exact: true }).first().click();
|
||||
await expect(dialog.getByText('直接装配', { exact: true })).toHaveCount(0);
|
||||
await expect(dialog.getByText('组件装配', { exact: true })).toHaveCount(0);
|
||||
const component = dialog.getByRole('checkbox', { name: '选择组件 头部', exact: true });
|
||||
await component.check();
|
||||
await expect(component).toBeChecked();
|
||||
await expect(dialog.getByRole('button', { name: '查看零件 头壳', exact: true })).toHaveAttribute('aria-pressed', 'true');
|
||||
await expect(dialog.getByRole('button', { name: '查看零件 头盖', exact: true })).toHaveAttribute('aria-pressed', 'true');
|
||||
await dialog.getByRole('button', { name: '查看零件 头壳', exact: true }).click();
|
||||
await expect(dialog.getByRole('tab', { name: '步骤 1', exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '安装零件 躯干', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '安装零件 手臂', exact: true }).click();
|
||||
const json = await generatedManifest(page);
|
||||
expect(json.steps.map((s: any) => s.label)).toEqual(['安装组件 头部', '安装 躯干', '安装 手臂']);
|
||||
expect(json.steps.flatMap((s: any) => s.parts)).toHaveLength(4);
|
||||
expect(new Set(json.steps.flatMap((s: any) => s.parts)).size).toBe(4);
|
||||
expect(json.steps.every((s: any) => s.scene === undefined)).toBe(true);
|
||||
await component.uncheck();
|
||||
await expect(dialog.getByRole('button', { name: '安装零件 头壳', exact: true })).toHaveAttribute('aria-pressed', 'false');
|
||||
await dialog.getByRole('button', { name: '安装零件 头壳', exact: true }).click();
|
||||
await expect(component).toBeDisabled();
|
||||
await dialog.getByRole('button', { name: '查看零件 头壳', exact: true }).click({ button: 'right' });
|
||||
await expect(component).toBeEnabled();
|
||||
await component.check();
|
||||
const changed = await generatedManifest(page);
|
||||
expect(changed.steps.map((s: any) => s.label)).toEqual(['安装 躯干', '安装 手臂', '安装组件 头部']);
|
||||
await page.setViewportSize({ width: 1366, height: 768 });
|
||||
await expect.poll(() => dialog.locator('.ant-modal-body').evaluate(el => el.scrollHeight <= el.clientHeight + 1)).toBe(true);
|
||||
await page.screenshot({ path: testInfo.outputPath('unified-assembly-picker.png'), fullPage: true });
|
||||
});
|
||||
|
||||
test('分段标记:新拼装只重置起点,后续自动累加;继续拼装可接回旧进度,保存回读不展开逐步标记', async ({ page }) => {
|
||||
await workspace(page, { missing: true });
|
||||
await chooseFiles(page, ['A', 'B', 'C', 'D', 'E', 'F'].map(name => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb() })), '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
for (const name of ['A', 'B', 'C', 'D', 'E', 'F']) await dialog.getByRole('button', { name: `安装零件 ${name}`, exact: true }).click();
|
||||
await dialog.getByRole('tab', { name: '步骤 6', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '查看第 3 步 安装 C', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '标记新拼装', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '查看第 5 步 安装 E', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '标记继续拼装', exact: true }).click();
|
||||
await dialog.getByRole('combobox', { name: '续装基准步骤' }).press('ArrowDown');
|
||||
await page.getByRole('option', { name: '第 2 步 · 安装 B', exact: true }).click();
|
||||
const json = await generatedManifest(page);
|
||||
expect(json.steps.filter((s: any) => s.scene)).toHaveLength(2);
|
||||
expect(json.steps[2].scene).toEqual({ mode: 'independent' });
|
||||
expect(json.steps[4].scene).toEqual({ mode: 'continue', base: { kind: 'step', id: json.steps[1].id } });
|
||||
expect(json.steps[5].scene).toBeUndefined();
|
||||
const resolved = await page.evaluate(async document => {
|
||||
const rp = '/src/utils/boundAssembly.ts', wp = '/src/utils/assemblyWorkflow.ts', ep = '/src/utils/assemblyEditor.ts';
|
||||
const { restoreAssemblyDocument } = await import(rp), { assemblyStages, workflowForSave, removeWorkflowStep } = await import(wp), { assemblyManifest } = await import(ep);
|
||||
const sources = document.files.map((f: any) => ({ asset: { assetId: f.path, type: 'part-glb', relativePath: f.path, bytes: f.bytes, sha256: f.sha256, status: 'READY' } }));
|
||||
const session = restoreAssemblyDocument(document, { sources });
|
||||
let protectedMessage = ''; try { removeWorkflowStep(session.assembly, session.assembly.steps[1].id); } catch (e) { protectedMessage = String(e); }
|
||||
const removed = removeWorkflowStep(session.assembly, session.assembly.steps[3].id);
|
||||
return { counts: assemblyStages(session.assembly).map((s: any) => s.parts.length), entering: assemblyStages(session.assembly).map((s: any) => s.entering.length), json: assemblyManifest(workflowForSave(session.assembly), sources, document), protectedMessage, afterRemove: assemblyStages(removed).map((s: any) => s.parts.length) };
|
||||
}, json);
|
||||
expect(resolved.counts).toEqual([1, 2, 1, 2, 3, 4]); expect(resolved.entering).toEqual([1,1,1,1,1,1]);
|
||||
expect(resolved.json).toEqual(json); expect(resolved.protectedMessage).toContain('续装基准'); expect(resolved.afterRemove).toEqual([1,2,1,3,4]);
|
||||
await dialog.getByRole('button', { name: '查看第 4 步 安装 D', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '预览到此步', exact: true }).click();
|
||||
await expect(dialog.getByText('1 / 6 · 安装 A', { exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '暂停预览', exact: true }).click();
|
||||
await expect(dialog.getByText('从第 1 步预览至第 4 步 · 已暂停', { exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '继续预览', exact: true }).click();
|
||||
await expect(dialog.getByText('4 / 6 · 安装 D', { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByRole('button', { name: '预览到此步', exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '查看第 3 步 安装 C', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '取消标记', exact: true }).click();
|
||||
const inherited = await generatedManifest(page);
|
||||
expect(inherited.steps.filter((s: any) => s.scene)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('旧版组件整理:分组与嵌套连接变为组件层级,总装不重复安装成员,位姿和文件保持不变', async ({ page }) => {
|
||||
await workspace(page, { resourceApi: true });
|
||||
const checked = await page.evaluate(async () => {
|
||||
const sp = '/src/utils/assemblySimplify.ts', wp = '/src/utils/assemblyWorkflow.ts';
|
||||
const { simplifyAssembly } = await import(sp), { assemblyStages, workflowForSave } = await import(wp);
|
||||
const part = (id: string) => ({ id, name: id, assetId: id, parentId: null, position: [1,2,3], quaternion: [0,0,0,1], scale: [1,1,1], installOffset: [0,.08,0] });
|
||||
const old: any = { enabled: true, title: '旧版', unit: 'meter', referenceAssetId: null, displayQuaternion: [0,0,0,1], parts: ['head','body','leg'].map(part), steps: [{id:'h',label:'头',parts:['head']},{id:'b',label:'躯干',parts:['body']},{id:'l',label:'腿',parts:['leg'],scene:{mode:'continue',base:{kind:'connection',id:'joined'}}}], componentPlan:{version:1,components:[{id:'hc',name:'头',parts:['head']},{id:'bc',name:'躯干',parts:['body']}],connections:[{id:'joined',name:'头与躯干',members:['bc','hc'],installOffset:[0,.08,0]}]} };
|
||||
const converted = workflowForSave(simplifyAssembly(old));
|
||||
return { original: old, converted, counts: assemblyStages(converted).map((s: any) => s.parts.length) };
|
||||
});
|
||||
expect(checked.original.componentPlan.connections).toHaveLength(1);
|
||||
expect(checked.converted.componentPlan).toBeUndefined(); expect(checked.converted.componentLibrary.components).toHaveLength(3);
|
||||
expect(checked.converted.steps).toHaveLength(2); expect(checked.counts).toEqual([2,3]);
|
||||
expect(checked.converted.parts).toEqual(checked.original.parts);
|
||||
expect(new Set(checked.converted.steps.flatMap((s: any) => s.parts)).size).toBe(3);
|
||||
});
|
||||
|
||||
test('资源自动关联拒绝版本歧义,上传成功后不再改绑已确定的资源', async ({ page }) => {
|
||||
@@ -909,9 +1011,9 @@ test('文件夹仅保留 GLB 和相对路径,装配直接使用同一批零件
|
||||
page.on('filechooser', () => extraChoosers++);
|
||||
const dialog = await editorDialog(page);
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(2);
|
||||
await expect(dialog.getByText('整机', { exact: true })).toHaveCount(0);
|
||||
await dialog.getByRole('button', { name: '全选结果', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '添加步骤', exact: true }).click();
|
||||
await expect(dialog.getByText('从第一个选择开始')).toBeVisible();
|
||||
await dialog.locator('.assembly-part-row').nth(0).click();
|
||||
await dialog.locator('.assembly-part-row').nth(1).click();
|
||||
const manifest = await generatedManifest(page);
|
||||
expect(manifest.files.map((f: any) => f.path).sort()).toEqual(['left/leg.glb', 'right/leg.GLB']);
|
||||
expect(manifest.parts).toHaveLength(2);
|
||||
@@ -1374,3 +1476,395 @@ test('零件管理:绑定结果未知不自动重复提交,刷新核对后
|
||||
await expect(page.getByRole('button', { name: '上传单个零件', exact: true })).toBeEnabled();
|
||||
expect(puts).toBe(1); expect(state.confirmations).toHaveLength(0);
|
||||
});
|
||||
|
||||
async function boundAssemblyWorkspace(page: Page, issue?: 'missing' | 'mismatch' | 'json') {
|
||||
const bytes = editorGlb();
|
||||
const digest = createHash('sha256').update(bytes).digest('hex');
|
||||
const manifest = {
|
||||
schemaVersion: 1, kind: 'assembly', title: '已有装配流程', unit: 'meter', displayQuaternion: [0, 0, 0, 1],
|
||||
files: ['leg.glb', '内六角扳手.glb'].map(path => ({ path, bytes: bytes.length, sha256: digest })),
|
||||
parts: [{ id: 'leg', file: 'leg.glb', parentId: null, position: [.2, .1, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [.05, 0, 0], customPart: 'preserved' }],
|
||||
steps: [{ id: 'step-1', label: '原安装步骤', parts: ['leg'], toolId: 'hex-key', duration: 1200 }],
|
||||
tools: [{ id: 'hex-key', file: '内六角扳手.glb', tipPosition: [0, .01, 0], tipAxis: [0, 0, -1] }], custom: { preserve: true },
|
||||
};
|
||||
const files = (issue === 'missing' ? ['leg.glb'] : ['leg.glb', '内六角扳手.glb']).map(relativePath => ({ relativePath, sizeBytes: bytes.length, url: `https://bound.example.com/${relativePath}` }));
|
||||
await page.route('https://bound.example.com/**', async route => {
|
||||
expect(route.request().headers().authorization).toBeUndefined();
|
||||
const path = decodeURIComponent(new URL(route.request().url()).pathname.slice(1));
|
||||
return route.fulfill({ status: 200, body: path === 'assembly.json' ? issue === 'json' ? '{' : JSON.stringify(manifest) : issue === 'mismatch' ? editorGlb(1) : bytes });
|
||||
});
|
||||
const errors: string[] = [];
|
||||
page.on('console', message => { if (message.type() === 'error' || message.text().includes('Future Flag Warning')) errors.push(message.text()); });
|
||||
const state = await workspace(page, { resourceApi: true, project: { modelPartsBaseUrl: 'https://bound.example.com/', modelPartsFiles: files, assemblyJsonUrl: 'https://bound.example.com/assembly.json' } });
|
||||
return { manifest, state, errors };
|
||||
}
|
||||
|
||||
test('已有装配:打开后读取原步骤与位姿,保存保留工具文件和扩展字段,不重新上传零件', async ({ page }) => {
|
||||
const { manifest, state, errors } = await boundAssemblyWorkspace(page);
|
||||
await expect(page.getByText('编辑装配流程', { exact: true })).toBeVisible();
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByRole('tab', { name: '步骤 1', exact: true }).click();
|
||||
await expect(dialog.locator('.assembly-step-list')).toContainText('原安装步骤');
|
||||
const generated = await generatedManifest(page);
|
||||
expect(generated.tools).toEqual(manifest.tools);
|
||||
expect(generated.files).toEqual(manifest.files);
|
||||
expect(generated.parts[0]).toMatchObject(manifest.parts[0]);
|
||||
expect(generated.steps).toEqual(manifest.steps);
|
||||
expect(generated.custom).toEqual(manifest.custom);
|
||||
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
expect(errors).toEqual([]);
|
||||
let signatures = 0, confirmations = 0, uploaded = '';
|
||||
await page.route('**/resources/assembly-json/signature', route => {
|
||||
signatures++;
|
||||
return ok(route, { batchCode: 'assembly-edited', uploadUrl: 'https://assembly-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: route.request().postDataJSON().files.map((f: any) => ({ relativePath: f.relativePath, formFields: { key: f.relativePath } })) });
|
||||
});
|
||||
await page.route('https://assembly-upload.example.com/**', route => { uploaded = route.request().postData()!; return route.fulfill({ status: 200 }); });
|
||||
await page.route('**/resources/assembly-json', route => { confirmations++; return ok(route, { projectCode: 'project-a', repoStatus: 'READY', modelGlbUrl: null, assemblyJsonUrl: 'https://bound.example.com/new.json' }); });
|
||||
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
|
||||
await expect.poll(() => confirmations).toBe(1);
|
||||
expect(signatures).toBe(1);
|
||||
expect(uploaded).toContain('内六角扳手.glb');
|
||||
expect(uploaded).toContain('customPart');
|
||||
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
|
||||
for (const issue of ['missing', 'mismatch', 'json'] as const) test(`已有装配:${issue} 时明确报错且保留绑定,不打开空流程或提交覆盖`, async ({ page }) => {
|
||||
const { state } = await boundAssemblyWorkspace(page, issue);
|
||||
await page.getByRole('button', { name: '制作装配流程', exact: true }).click();
|
||||
await expect(page.getByText(/原流程已保留/)).toBeVisible();
|
||||
await expect(page.getByRole('dialog')).toHaveCount(0);
|
||||
await expect(page.getByRole('button', { name: '制作装配流程', exact: true })).toBeEnabled();
|
||||
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
await expect(page.locator('.experience-upload-assembly').getByText('当前已绑定', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('整机定位:新流程用唯一同名节点的世界变换,匹配失败不猜位置,原文件不变', async ({ page }) => {
|
||||
await workspace(page, { resourceApi: true });
|
||||
const result = await page.evaluate(async () => {
|
||||
const path = '/src/utils/assemblyPlacement.ts', { placeFromWhole } = await import(path);
|
||||
const makeGlb = (nodes: unknown[]) => {
|
||||
const json = new TextEncoder().encode(JSON.stringify({ nodes, meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }], accessors: [{ count: 8, min: [-1, -1, -1], max: [1, 1, 1] }] }));
|
||||
const size = Math.ceil(json.length / 4) * 4, bytes = new Uint8Array(20 + size), h = new DataView(bytes.buffer);
|
||||
h.setUint32(0, 0x46546c67, true); h.setUint32(4, 2, true); h.setUint32(8, bytes.length, true); h.setUint32(12, size, true); h.setUint32(16, 0x4e4f534a, true); bytes.fill(32, 20); bytes.set(json, 20);
|
||||
return new File([bytes], 'model.glb');
|
||||
};
|
||||
const source = (id: string, name: string) => ({ file: makeGlb([{ name, mesh: 0, translation: [.2, 0, 0] }]), asset: { assetId: id, type: 'part-glb', relativePath: `${id}.glb`, bytes: 1, sha256: 'a'.repeat(64), status: 'READY', downloadUrl: null } });
|
||||
const sources = [source('left', 'left-mesh'), source('unknown', 'no-matching-node')];
|
||||
const part = (id: string) => ({ id, name: id, assetId: id, parentId: null, position: [0, 0, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [0, .08, 0] });
|
||||
const session = { sources, assembly: { title: '定位测试', enabled: true, unit: 'meter', displayQuaternion: [0, 0, 0, 1], referenceAssetId: null, parts: sources.map(s => part(s.asset.assetId)), steps: [] } };
|
||||
const whole = makeGlb([{ translation: [1, 2, 3], children: [1] }, { name: 'left-mesh', mesh: 0, translation: [.6, 0, 0] }]);
|
||||
const placed = await placeFromWhole(session, whole, new AbortController().signal);
|
||||
return { position: placed.catalog[0].position, unplaced: placed.unplaced, sourcePosition: session.assembly.parts[0].position, filesUnchanged: placed.sources.every((s: any, i: number) => s.file === sources[i].file) };
|
||||
});
|
||||
expect(result.position[0]).toBeCloseTo(1.4); expect(result.position.slice(1)).toEqual([2, 3]);
|
||||
expect(result.unplaced).toEqual(['unknown']); expect(result.sourcePosition).toEqual([0, 0, 0]); expect(result.filesUnchanged).toBe(true);
|
||||
});
|
||||
|
||||
test('组件总装:支持嵌套连接,拒绝重复消费、未连接与循环,切换普通模式保留步骤', async ({ page }) => {
|
||||
await workspace(page, { resourceApi: true });
|
||||
const result = await page.evaluate(async () => {
|
||||
const path = '/src/utils/assemblyWorkflow.ts', { assemblyStages, componentPlanProblems } = await import(path);
|
||||
const a = { parts: ['h', 'b', 'a'].map(id => ({ id })), steps: ['h', 'b', 'a'].map(id => ({ id: `s-${id}`, parts: [id], label: id })), componentPlan: { version: 1, components: ['h', 'b', 'a'].map(id => ({ id: `c-${id}`, name: id, parts: [id] })), connections: [{ id: 'hb', name: '头部与身体', members: ['c-h', 'c-b'], installOffset: [0, .1, 0] }, { id: 'all', name: '加装手臂', members: ['hb', 'c-a'], installOffset: [0, .1, 0] }] } };
|
||||
const valid = componentPlanProblems(a), stages = assemblyStages(a);
|
||||
const duplicate = structuredClone(a); duplicate.componentPlan.connections[1].members = ['hb', 'c-b'];
|
||||
const cycle = structuredClone(a); cycle.componentPlan.connections[0].members = ['all', 'c-h'];
|
||||
const unfinished = structuredClone(a); unfinished.componentPlan.connections.pop();
|
||||
const direct = structuredClone(a); delete (direct as any).componentPlan;
|
||||
return { valid, visibility: stages.map((s: any) => s.parts), duplicate: componentPlanProblems(duplicate), cycle: componentPlanProblems(cycle), unfinished: componentPlanProblems(unfinished), direct: assemblyStages(direct).map((s: any) => s.parts) };
|
||||
});
|
||||
expect(result.valid).toEqual([]);
|
||||
expect(result.visibility).toEqual([['h'], ['b'], ['h', 'b'], ['a'], ['h', 'b', 'a']]);
|
||||
expect(result.direct).toEqual([['h'], ['h', 'b'], ['h', 'b', 'a']]);
|
||||
expect(result.duplicate.length).toBeGreaterThan(0); expect(result.cycle.length).toBeGreaterThan(0); expect(result.unfinished.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('部分编排保存后再次打开仍保留未用零件原文件,可以继续制作下一组件', async ({ page }) => {
|
||||
await workspace(page, { resourceApi: true });
|
||||
const counts = await page.evaluate(async () => {
|
||||
const editorPath = '/src/utils/assemblyEditor.ts', filesPath = '/src/utils/experienceFiles.ts';
|
||||
const { prepareAssemblySession } = await import(editorPath), { emptyExperienceFiles } = await import(filesPath);
|
||||
const files = emptyExperienceFiles(); files.parts.selected = ['head', 'body'].map(name => ({ relativePath: `${name}.glb`, file: new File(['original'], `${name}.glb`) }));
|
||||
const initial = await prepareAssemblySession(null, null, [], files);
|
||||
const partial = { ...initial, catalog: initial.assembly.parts, assembly: { ...initial.assembly, parts: [initial.assembly.parts[0]], steps: [{ id: 's1', label: '头部', parts: [initial.assembly.parts[0].id] }] } };
|
||||
const reopened = await prepareAssemblySession(partial, partial.assembly, [], emptyExperienceFiles());
|
||||
return { sources: reopened.sources.length, catalog: reopened.catalog.length, steps: reopened.assembly.steps.length };
|
||||
});
|
||||
expect(counts).toEqual({ sources: 2, catalog: 2, steps: 1 });
|
||||
});
|
||||
|
||||
test('零件选择:左键添加、右键仅移除目标,筛选可叠加搜索并随选择更新,撤销可恢复', async ({ page }) => {
|
||||
const state = await workspace(page, { missing: true });
|
||||
await chooseFiles(page, ['left', 'right', 'head'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb(i * .2) })), '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByText('已选中', { exact: true }).click();
|
||||
await expect(dialog.getByText('还没有选中零件', { exact: true })).toBeVisible();
|
||||
await dialog.getByText('未选中', { exact: true }).click();
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(3);
|
||||
await dialog.getByRole('button', { name: '安装零件 left', exact: true }).click({ button: 'right' });
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(3);
|
||||
await dialog.getByRole('button', { name: '安装零件 left', exact: true }).click();
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(2);
|
||||
await dialog.getByRole('button', { name: '安装零件 right', exact: true }).click();
|
||||
await dialog.getByText('已选中', { exact: true }).click();
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(2);
|
||||
await dialog.getByRole('textbox', { name: '搜索组件或零件' }).fill('LEFT');
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(1);
|
||||
await dialog.getByRole('button', { name: '查看零件 left', exact: true }).click({ button: 'right' });
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(0);
|
||||
await dialog.getByRole('textbox', { name: '搜索组件或零件' }).fill('');
|
||||
await expect(dialog.getByRole('button', { name: '查看零件 right', exact: true })).toHaveAttribute('aria-pressed', 'true');
|
||||
const json = await generatedManifest(page);
|
||||
expect(json.parts).toHaveLength(1); expect(json.parts[0].file).toBe('right.glb');
|
||||
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(2);
|
||||
await dialog.getByRole('button', { name: '重做', exact: true }).click();
|
||||
await expect(dialog.locator('.assembly-part-row')).toHaveCount(1);
|
||||
await dialog.getByText('未选中', { exact: true }).click();
|
||||
await expect(dialog.getByRole('button', { name: '安装零件 left', exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '安装零件 left', exact: true }).click();
|
||||
const reselected = await generatedManifest(page);
|
||||
expect(reselected.steps.map((s: any) => s.label)).toEqual(['安装 right', '安装 left']);
|
||||
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('单零件移除:保留同一步其余零件,清理空组件和依赖连接,父件引用仍有保护', async ({ page }) => {
|
||||
await workspace(page, { resourceApi: true });
|
||||
const result = await page.evaluate(async () => {
|
||||
const path = '/src/utils/assemblyWorkflow.ts', { removeWorkflowPart } = await import(path);
|
||||
const original = { parts: ['left', 'right', 'body'].map(id => ({ id, name: id, parentId: null })), steps: [{ id: 's1', label: '双腿', parts: ['left', 'right'], duration: 1000 }, { id: 's2', label: '身体', parts: ['body'] }], componentPlan: { version: 1, components: [{ id: 'legs', name: '双腿', parts: ['left', 'right'] }, { id: 'body-c', name: '身体', parts: ['body'] }], connections: [{ id: 'joined', name: '总装', members: ['legs', 'body-c'], installOffset: [0, .1, 0] }] } };
|
||||
const one = removeWorkflowPart(original, 'left'), two = removeWorkflowPart(one, 'right');
|
||||
const child = structuredClone(original); child.parts[1].parentId = 'left';
|
||||
let protectedMessage = ''; try { removeWorkflowPart(child, 'left'); } catch (e) { protectedMessage = (e as Error).message; }
|
||||
return { one, two, original, protectedMessage, unchanged: removeWorkflowPart(original, 'not-selected') === original };
|
||||
});
|
||||
expect(result.one.steps[0]).toEqual({ id: 's1', label: '双腿', parts: ['right'], duration: 1000 });
|
||||
expect(result.one.componentPlan.connections).toHaveLength(1);
|
||||
expect(result.two.componentPlan.components.map((c: any) => c.id)).toEqual(['body-c']);
|
||||
expect(result.two.componentPlan.connections).toEqual([]);
|
||||
expect(result.original.steps[0].parts).toEqual(['left', 'right']);
|
||||
expect(result.protectedMessage).toContain('先移除子零件'); expect(result.unchanged).toBe(true);
|
||||
});
|
||||
|
||||
test('创建组件:内部步骤独立,选择后整体进入总装,撤销重做保留组件内容', async ({ page }) => {
|
||||
await workspace(page, { missing: true });
|
||||
await chooseFiles(page, ['头壳', '面罩', '支架'].map(name => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb() })), '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByRole('button', { name: '创建组件', exact: true }).first().click();
|
||||
await page.getByRole('textbox', { name: '独立组件名称' }).fill('头部');
|
||||
await page.getByRole('button', { name: '创建并制作' }).click();
|
||||
for (const name of ['面罩', '支架', '头壳']) await dialog.getByRole('button', { name: `安装零件 ${name}`, exact: true }).click();
|
||||
const privateJson = await generatedManifest(page);
|
||||
expect(privateJson.steps).toEqual([]);
|
||||
expect(privateJson.componentLibrary.components[0].steps.map((s: any) => s.label)).toEqual(['安装 面罩', '安装 支架', '安装 头壳']);
|
||||
await dialog.getByText('步骤编排', { exact: true }).first().click();
|
||||
await dialog.getByRole('checkbox', { name: '选择组件 头部', exact: true }).check();
|
||||
await expect(dialog.getByRole('tab', { name: '步骤 1', exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
await expect(dialog.getByRole('tab', { name: '步骤 0', exact: true })).toBeVisible();
|
||||
await expect(dialog.getByRole('button', { name: '编辑库组件 头部', exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '重做', exact: true }).click();
|
||||
const total = await generatedManifest(page);
|
||||
expect(total.steps).toHaveLength(1); expect(total.steps[0].parts).toHaveLength(3);
|
||||
expect(total.componentLibrary.components).toEqual(privateJson.componentLibrary.components);
|
||||
});
|
||||
|
||||
test('六向与工具:进入设置直接可见,GLB 工具校准后自动识别螺丝头并写入原有前台格式', async ({ page }, testInfo) => {
|
||||
await workspace(page, { missing: true });
|
||||
const fixture = await page.evaluate(async () => { const path = '/tests/assembly-fixtures.ts'; return (await import(path)).toolFixtures(); });
|
||||
await chooseFiles(page, [{ name: '螺丝.glb', mimeType: 'model/gltf-binary', buffer: Buffer.from(fixture.screw) }, { name: '螺丝刀.glb', mimeType: 'model/gltf-binary', buffer: Buffer.from(fixture.driver) }], '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByRole('button', { name: '安装零件 螺丝', exact: true }).click();
|
||||
for (const label of ['X', 'Y', 'Z', '−X', '−Y', '−Z']) await expect(dialog.getByRole('button', { name: `从 ${label} 进入`, exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '从 −X 进入', exact: true }).click();
|
||||
await dialog.getByRole('spinbutton', { name: '进入距离(毫米)' }).fill('25');
|
||||
const ordinary = await generatedManifest(page); expect(ordinary.parts[0].installOffset).toEqual([-.025, 0, 0]);
|
||||
await dialog.getByRole('switch', { name: '使用工具拧入' }).click();
|
||||
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeDisabled();
|
||||
await dialog.getByRole('combobox', { name: '安装工具 GLB' }).click();
|
||||
await page.getByRole('option', { name: '螺丝刀.glb', exact: true }).click();
|
||||
const calibration = page.getByRole('dialog', { name: '校准工具工作端' });
|
||||
await calibration.getByRole('spinbutton', { name: '校准点 X(毫米)' }).fill('0');
|
||||
await calibration.getByRole('spinbutton', { name: '校准点 Y(毫米)' }).fill('0');
|
||||
await calibration.getByRole('spinbutton', { name: '校准点 Z(毫米)' }).fill('10');
|
||||
await calibration.getByRole('button', { name: '−Z', exact: true }).click();
|
||||
await calibration.getByRole('button', { name: '使用此工作端' }).click();
|
||||
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeEnabled();
|
||||
await expect(dialog.getByRole('button', { name: '安装零件 螺丝刀', exact: true })).toHaveCount(0);
|
||||
const json = await generatedManifest(page);
|
||||
expect(json.files.map((f: any) => f.path).sort()).toEqual(['螺丝.glb', '螺丝刀.glb']);
|
||||
expect(json.parts).toHaveLength(1); expect(json.tools).toHaveLength(1);
|
||||
expect(json.tools[0].tipPosition).toEqual([0, 0, .01]); expect(json.tools[0].tipAxis).toEqual([0, 0, -1]);
|
||||
expect(json.parts[0].installation.axis[1]).toBeCloseTo(-1, 5);
|
||||
expect(json.parts[0].installation.socketPosition[1]).toBeCloseTo(.00765, 5);
|
||||
expect(json.parts[0].installation).toMatchObject({ type: 'screw', toolId: json.tools[0].id, turns: 3, direction: 'clockwise', travel: .0012 });
|
||||
await dialog.getByRole('spinbutton', { name: '旋转圈数' }).fill('5');
|
||||
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeDisabled();
|
||||
await dialog.getByRole('button', { name: '应用工具并预览' }).click();
|
||||
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeEnabled();
|
||||
expect((await generatedManifest(page)).parts[0].installation.turns).toBe(5);
|
||||
const configured = await generatedManifest(page);
|
||||
const restored = await page.evaluate(async raw => {
|
||||
const restorePath = '/src/utils/boundAssembly.ts', editorPath = '/src/utils/assemblyEditor.ts';
|
||||
const sources = raw.files.map((f: any) => ({ asset: { assetId: f.path, type: 'part-glb', relativePath: f.path, bytes: f.bytes, sha256: f.sha256, status: 'READY' } }));
|
||||
const session = (await import(restorePath)).restoreAssemblyDocument(raw, { sources });
|
||||
return (await import(editorPath)).assemblyManifest(session.assembly, sources, session.manifest);
|
||||
}, configured);
|
||||
expect(restored.tools).toEqual(configured.tools); expect(restored.parts[0].installation).toEqual(configured.parts[0].installation);
|
||||
await dialog.getByRole('switch', { name: '使用工具拧入' }).click();
|
||||
const withoutTool = await generatedManifest(page); expect(withoutTool.parts[0].installation).toBeUndefined();
|
||||
expect(withoutTool.tools).toHaveLength(1);
|
||||
await page.screenshot({ path: testInfo.outputPath('tool-installation-editor.png'), fullPage: true });
|
||||
});
|
||||
|
||||
test('工具坐标:六向螺丝在任意父级旋转下尖端始终贴合插入点,旋转后回到精确最终位姿', async ({ page }) => {
|
||||
await workspace(page, { resourceApi: true });
|
||||
const result = await page.evaluate(async () => {
|
||||
const threePath = '/node_modules/three/build/three.module.js', motionPath = '/src/utils/assemblyMotion.ts', configPath = '/src/utils/assemblyToolConfig.ts';
|
||||
const { Group, Vector3, Quaternion } = await import(threePath), { ScrewTransition } = await import(motionPath), { normalizedInstallation } = await import(configPath);
|
||||
let maxError = 0, maxAxisError = 0, finals = true;
|
||||
for (const axis of [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]) {
|
||||
const toolConfig = { id: 'driver', assetId: 'tool', tipPosition: [.005, 0, .01], tipAxis: [0, 0, -1] };
|
||||
const part = { id: 'screw', name: '螺丝', assetId: 'screw', parentId: null, position: [.2, .3, .1], quaternion: new Quaternion().setFromAxisAngle(new Vector3(1, 1, 0).normalize(), .7).toArray(), scale: [1, 1, 1], installOffset: [.02, .03, .01], installation: normalizedInstallation({ type: 'screw', toolId: 'driver', axis, socketPosition: [.003, .007, .001], toolQuaternion: new Quaternion().setFromUnitVectors(new Vector3(0, 0, 1), new Vector3(...axis)).toArray(), turns: 3, direction: 'clockwise', travel: .0012 }) };
|
||||
const parent = new Group(), instance = new Group(), tool = new Group(); parent.add(instance); parent.scale.setScalar(2); parent.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), 1.1);
|
||||
instance.scale.fromArray(part.scale); const transition = new ScrewTransition(instance, part, tool, toolConfig), m = part.installation;
|
||||
for (let i = 0; i <= 100; i++) {
|
||||
transition.sample(m.approachDuration + m.engageDuration + m.tightenDuration * i / 100); parent.updateMatrixWorld(true);
|
||||
maxError = Math.max(maxError, tool.localToWorld(new Vector3(...toolConfig.tipPosition)).distanceTo(instance.localToWorld(new Vector3(...m.socketPosition))));
|
||||
const working = new Vector3(...toolConfig.tipAxis).applyQuaternion(tool.quaternion).normalize(); maxAxisError = Math.max(maxAxisError, working.distanceTo(new Vector3(...axis)));
|
||||
}
|
||||
transition.sample(100); finals &&= instance.position.toArray().every((v: number, i: number) => v === part.position[i]) && instance.quaternion.toArray().every((v: number, i: number) => v === part.quaternion[i]) && !tool.visible;
|
||||
transition.dispose();
|
||||
}
|
||||
return { maxError, maxAxisError, finals };
|
||||
});
|
||||
expect(result.maxError).toBeLessThan(1e-10); expect(result.maxAxisError).toBeLessThan(1e-10); expect(result.finals).toBe(true);
|
||||
});
|
||||
|
||||
test('独立组件库:空父组件与嵌套子组件单独制作,显式加入总装后才产生总装步骤,保存回读保留层级', async ({ page }, testInfo) => {
|
||||
await workspace(page, { missing: true });
|
||||
await chooseFiles(page, ['躯干1零件', '躯干2零件', '腿'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb(i * .2) })), '选择零件文件夹');
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByText('组件制作', { exact: true }).first().click();
|
||||
const create = async (name: string, child = false) => {
|
||||
await dialog.getByRole('button', { name: child ? '创建子组件' : '创建组件', exact: true }).first().click();
|
||||
const form = page.getByRole('dialog', { name: child ? '创建子组件' : '创建组件', exact: true });
|
||||
await form.getByRole('textbox', { name: '独立组件名称' }).fill(name);
|
||||
await form.getByRole('button', { name: '创建并制作' }).click();
|
||||
};
|
||||
await create('躯干');
|
||||
await create('躯干1', true);
|
||||
await dialog.getByRole('button', { name: '安装零件 躯干1零件', exact: true }).click();
|
||||
await expect(dialog.getByRole('tab', { name: '内部步骤 1', exact: true })).toBeVisible();
|
||||
await expect(dialog.locator('.assembly-operation-context')).toContainText('总装 0 步保持独立');
|
||||
await dialog.getByRole('button', { name: '编辑库组件 躯干', exact: true }).click();
|
||||
await create('躯干2', true);
|
||||
await dialog.getByRole('button', { name: '安装零件 躯干2零件', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '安装零件 躯干1零件', exact: true }).click();
|
||||
await expect(page.getByText(/零件已属于“躯干 \/ 躯干1”/)).toBeVisible();
|
||||
await expect(dialog.getByRole('tab', { name: '内部步骤 1', exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '编辑库组件 躯干', exact: true }).click();
|
||||
await dialog.getByRole('checkbox', { name: '选择组件 躯干2', exact: true }).check();
|
||||
await dialog.getByRole('checkbox', { name: '选择组件 躯干1', exact: true }).check();
|
||||
await expect(dialog.getByRole('tab', { name: '内部步骤 2', exact: true })).toBeVisible();
|
||||
const privateOnly = await generatedManifest(page);
|
||||
expect(privateOnly.steps).toEqual([]); expect(privateOnly.parts).toEqual([]);
|
||||
expect(privateOnly.componentLibrary.components.map((c: any) => c.name)).toEqual(['躯干', '躯干1', '躯干2']);
|
||||
expect(privateOnly.componentLibrary.parts).toHaveLength(2);
|
||||
const torso = privateOnly.componentLibrary.components[0];
|
||||
expect(torso.steps.map((s: any) => s.label)).toEqual(['安装组件 躯干2', '安装组件 躯干1']);
|
||||
await dialog.getByText('步骤编排', { exact: true }).click();
|
||||
await expect(dialog.getByRole('tab', { name: '步骤 0', exact: true })).toBeVisible();
|
||||
await dialog.getByRole('checkbox', { name: '选择组件 躯干', exact: true }).check();
|
||||
await expect(dialog.getByRole('tab', { name: '步骤 1', exact: true })).toBeVisible();
|
||||
await dialog.getByRole('button', { name: '从 −X 进入', exact: true }).click();
|
||||
const total = await generatedManifest(page);
|
||||
expect(total.steps).toHaveLength(1); expect(total.steps[0].componentId).toBe(torso.id);
|
||||
expect(total.steps[0].installOffset).toEqual([-.08, 0, 0]);
|
||||
expect(total.parts).toHaveLength(2); expect(total.componentLibrary.parts).toEqual([]);
|
||||
expect(total.componentLibrary.components[0].steps).toEqual(torso.steps);
|
||||
const restored = await page.evaluate(async ({ privateOnly, total }) => {
|
||||
const rp = '/src/utils/boundAssembly.ts', ep = '/src/utils/assemblyEditor.ts', wp = '/src/utils/assemblyWorkflow.ts';
|
||||
const { restoreAssemblyDocument } = await import(rp), { assemblyManifest } = await import(ep), { workflowForSave, assemblyStages } = await import(wp);
|
||||
const make = (json: any) => {
|
||||
const sources = json.files.map((f: any) => ({ asset: { assetId: f.path, type: 'part-glb', relativePath: f.path, bytes: f.bytes, sha256: f.sha256, status: 'READY' } }));
|
||||
const session = restoreAssemblyDocument(json, { sources });
|
||||
return { json: assemblyManifest(workflowForSave(session.assembly), sources, json), stages: assemblyStages(session.assembly).map((s: any) => ({ parts: s.parts, offset: s.offset })) };
|
||||
};
|
||||
return { privateOnly: make(privateOnly), total: make(total) };
|
||||
}, { privateOnly, total });
|
||||
expect(restored.privateOnly.json).toEqual(privateOnly); expect(restored.privateOnly.stages).toEqual([]);
|
||||
expect(restored.total.json).toEqual(total); expect(restored.total.stages).toHaveLength(1);
|
||||
expect(restored.total.stages[0].offset).toEqual([-.08, 0, 0]);
|
||||
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
|
||||
await expect(dialog.getByRole('tab', { name: '步骤 0', exact: true })).toBeVisible();
|
||||
await expect(dialog.getByRole('button', { name: '编辑库组件 躯干', exact: true })).toBeVisible();
|
||||
await page.setViewportSize({ width: 1366, height: 768 });
|
||||
await dialog.getByText('组件制作', { exact: true }).first().click();
|
||||
await expect.poll(() => dialog.locator('.ant-modal-body').evaluate(el => el.scrollHeight <= el.clientHeight + 1)).toBe(true);
|
||||
await page.screenshot({ path: testInfo.outputPath('independent-component-library.png'), fullPage: true });
|
||||
});
|
||||
|
||||
test('独立组件库校验:重复零件、循环层级、非法子组件引用和删除引用目标均拒绝,保存组件不要求总装', async ({ page }) => {
|
||||
await workspace(page, { resourceApi: true });
|
||||
const checked = await page.evaluate(async () => {
|
||||
const lp = '/src/utils/assemblyLibrary.ts', wp = '/src/utils/assemblyWorkflow.ts';
|
||||
const { libraryProblems, deleteLibraryComponent, createLibraryComponent, editLibraryComponent, insertLibraryComponent, libraryComponentAssembly } = await import(lp), { workflowForSave } = await import(wp);
|
||||
const part = (id: string) => ({ id, name: id, assetId: id, parentId: null, position: [0,0,0], quaternion: [0,0,0,1], scale: [1,1,1], installOffset: [0,.08,0] });
|
||||
let a: any = { enabled: true, title: '独立组件', unit: 'meter', referenceAssetId: null, displayQuaternion: [0,0,0,1], parts: [part('p1'), part('p2')], steps: [] };
|
||||
const parent = createLibraryComponent(a, '躯干', null); a = parent.assembly;
|
||||
const child = createLibraryComponent(a, '躯干1', parent.componentId); a = child.assembly;
|
||||
const local = libraryComponentAssembly(a, child.componentId); local.steps = [{ id: 'inside', label: '安装p1', parts: ['p1'] }];
|
||||
a = editLibraryComponent(a, child.componentId, local);
|
||||
const validPrivate = workflowForSave(a);
|
||||
const parentLocal = insertLibraryComponent(libraryComponentAssembly(a, parent.componentId), a, child.componentId, parent.componentId);
|
||||
a = editLibraryComponent(a, parent.componentId, parentLocal);
|
||||
const total = insertLibraryComponent(a, a, parent.componentId, null);
|
||||
const duplicate = structuredClone(a); duplicate.componentLibrary.components[0].steps.push({ id: 'duplicate', label: '重复', parts: ['p1'] }); duplicate.componentLibrary.components[0].parts.push('p1');
|
||||
const cycle = structuredClone(a); cycle.componentLibrary.components[0].parentId = child.componentId;
|
||||
const invalid = structuredClone(a); invalid.componentLibrary.components[0].steps[0].componentId = parent.componentId;
|
||||
let deletion = ''; try { deleteLibraryComponent(total, child.componentId); } catch (e) { deletion = String(e); }
|
||||
let repeated = ''; try { insertLibraryComponent(total, total, parent.componentId, null); } catch (e) { repeated = String(e); }
|
||||
return { privateSteps: validPrivate.steps.length, privateParts: validPrivate.parts.map((p: any) => p.id), valid: libraryProblems(a), duplicate: libraryProblems(duplicate), cycle: libraryProblems(cycle), invalid: libraryProblems(invalid), deletion, repeated };
|
||||
});
|
||||
expect(checked.privateSteps).toBe(0); expect(checked.privateParts).toEqual(['p1']); expect(checked.valid).toEqual([]);
|
||||
expect(checked.duplicate.join()).toContain('不能归属多个组件'); expect(checked.cycle.join()).toContain('循环');
|
||||
expect(checked.invalid.length).toBeGreaterThan(0); expect(checked.deletion).toContain('已被步骤引用'); expect(checked.repeated).toContain('不能重复加入');
|
||||
});
|
||||
|
||||
test('组件库上传协议:保存空父子组件仅上传一次JSON,原总装步骤不变,刷新后从资源接口恢复组件层级', async ({ page }) => {
|
||||
const { manifest, state } = await boundAssemblyWorkspace(page);
|
||||
const dialog = await editorDialog(page);
|
||||
await dialog.getByText('组件制作', { exact: true }).first().click();
|
||||
await dialog.getByRole('button', { name: '创建组件', exact: true }).first().click();
|
||||
await page.getByRole('textbox', { name: '独立组件名称' }).fill('手臂');
|
||||
await page.getByRole('button', { name: '创建并制作' }).click();
|
||||
await dialog.getByRole('button', { name: '创建子组件', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: '独立组件名称' }).fill('前臂');
|
||||
await page.getByRole('button', { name: '创建并制作' }).click();
|
||||
let uploaded: any, signatures = 0, confirmations = 0;
|
||||
await page.route('**/resources/assembly-json/signature', route => {
|
||||
signatures++;
|
||||
return ok(route, { batchCode: 'library-only', uploadUrl: 'https://library-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: route.request().postDataJSON().files.map((f: any) => ({ relativePath: f.relativePath, formFields: { key: f.relativePath } })) });
|
||||
});
|
||||
await page.route('https://library-upload.example.com/**', route => {
|
||||
const raw = route.request().postData()!;
|
||||
uploaded = JSON.parse(raw.slice(raw.indexOf('{\n'), raw.lastIndexOf('\n}') + 2));
|
||||
Object.assign(manifest, uploaded);
|
||||
return route.fulfill({ status: 200 });
|
||||
});
|
||||
await page.route('**/resources/assembly-json', route => {
|
||||
confirmations++;
|
||||
return ok(route, { projectCode: 'project-a', repoStatus: 'READY', modelGlbUrl: null, modelPartsBaseUrl: 'https://bound.example.com/', modelPartsFiles: ['leg.glb', '内六角扳手.glb'].map(relativePath => ({ relativePath, sizeBytes: editorGlb().length, url: `https://bound.example.com/${relativePath}` })), assemblyJsonUrl: 'https://bound.example.com/assembly.json' });
|
||||
});
|
||||
await dialog.getByRole('button', { name: '保存组件库', exact: true }).click();
|
||||
await expect.poll(() => confirmations).toBe(1);
|
||||
expect(signatures).toBe(1); expect(uploaded.steps).toEqual([{ id: 'step-1', label: '原安装步骤', parts: ['leg'], toolId: 'hex-key', duration: 1200 }]);
|
||||
expect(uploaded.componentLibrary.components.map((c: any) => c.name)).toEqual(['手臂', '前臂']);
|
||||
await page.reload();
|
||||
await page.getByRole('tab', { name: '装配与仿真' }).click();
|
||||
const reopened = await editorDialog(page);
|
||||
await expect(reopened.getByRole('button', { name: '编辑库组件 前臂', exact: true })).toBeVisible();
|
||||
await expect(reopened.getByRole('tab', { name: '步骤 1', exact: true })).toBeVisible();
|
||||
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user