合并 origin/main,保留 STEP 与装配仿真功能
This commit is contained in:
@@ -6,7 +6,7 @@ React 18 + TypeScript + Vite 6 + Ant Design 5 + React Router 6。对接 `communi
|
||||
|
||||
| 环境 | 前端 | 后端 |
|
||||
| --- | --- | --- |
|
||||
| 本地开发 | http://localhost:5188 | 代理到测试环境后端 |
|
||||
| 本地开发 | http://localhost:8091 | 代理到测试环境后端 |
|
||||
| 测试 | https://dev-vibemake-admin.robotquan.com | https://dev-vibemake-api.robotquan.com |
|
||||
| 线上 | https://vibemake-admin.robotquan.com | https://vibemake-api.robotquan.com |
|
||||
|
||||
@@ -45,6 +45,18 @@ DevTools 中 `preflight` 是浏览器发送的 OPTIONS 跨域预检,`fetch`
|
||||
|
||||
## 功能
|
||||
|
||||
零件列表支持名称/目录搜索、单个 GLB 自动上传、同路径确认替换及逐行删除;单项增删通过现有整批接口合并保留其他零件。
|
||||
|
||||
当前文件/模型上传已对接 admin-api(7) 第 8.3 节:四类资源签名→OSS 原文件上传→确认绑定,成功立即更新社区详情,无需重新发布。行走资源直接选择完整文件夹,不要求 robot.json。旧草稿与分功能构建方案仅保留兼容实现,当前实际接口不提供策略运行校验。详见 [当前接口及联调记录](docs/model-experiences-api.md)。
|
||||
|
||||
装配与仿真第一阶段:项目详情可上传整机 GLB、零件 GLB 文件夹、装配步骤 JSON,以及行走表单文件或 ZIP,保存独立草稿并通过构建版本发布。新增接口待后端接入,字段和异步任务完整约定见 [模型与演示接口](docs/model-experiences-api.md)。前端不限制文件大小和机器人型号,后端负责文件完整性与兼容性校验。
|
||||
|
||||
装配流程支持可视化制作:新建项目和项目管理中,在“零件模型”选择零件文件夹后点击“制作装配流程”,在三维模型或列表中多选、分组,设置进入方向/距离并添加步骤;支持即时预览、完整流程播放、拖动排序、撤销/重做、复制步骤设置、最终位姿对齐。系统生成 JSON,已有步骤仅通过“高级导入(JSON)”接入,零件直接使用上方零件模型,无需重复上传。原 GLB 字节和材质不变;本地文件上传后自动关联资源编号。尚未上传的流程只保留在本页内存中,可先导出 JSON 备份,后端接入后才能持久保存和发布。
|
||||
|
||||
行走资源可直接选择工程文件夹,自动识别基础配置并保留子目录,无需先压缩。行走演示默认采用“四项基础文件+可选功能”表单:配置 JSON、MJCF、实际引用文件、primary ONNX;踢球、转头、起身等逐项勾选和绑定,文件与技能可复用。额外资源保留草稿,发布时确认已通过的功能子集;足球预设来自后端,不要求上传标准足球模型。保留 ZIP 导入与独立的旧版兼容区。新建项目选择的文件和设置会带入管理页;前端不限制大小。新接口适配与联调字段见 [接口文档第 12 节](docs/model-experiences-api.md#12-行走表单-v3本次后台与后端联调约定待后端实现)。接口未接入时明确提示,不能伪上传、保存或校验。社区播放器能力拆分、实际推理和发布联调尚待后端与前台共同实现。示例位于 public/examples,构建时会包含在 dist 中。
|
||||
|
||||
新建项目与项目管理均按“整机模型、零件模型、拼装步骤、行走演示”分区选择文件,整机和零件可以同时保留。新建后直接进入模型页继续上传;管理页上传整机即自动选用,包文件自动读取,普通操作按“上传 → 检查并预览 → 发布到前台”完成,无需手动填写资源编号。
|
||||
|
||||
- 登录 / 退出 / 修改密码(401 自动回登录页并保留返回路径)
|
||||
- 用户管理:列表筛选、详情、名下项目、编辑昵称、启用/禁用(不可禁用自己与官方账号)
|
||||
- 项目管理:列表筛选、新建(封面 OSS 直传、归属官方或普通用户)、编辑、删除
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
> **2026-10-28 联调更新:以 admin-api(7).md 第 8.3 节为准。** 当前 dev 返回 modelGlbUrl 等新字段时,默认使用 ProjectResourcesPanel 与 /resources/{resourceType}/signature、PUT /resources/{resourceType}、DELETE /resources/{resourceType}。确认即更新社区绑定,无需草稿、构建或重新发布。下面旧版 experience-draft / walking-editor 属于此前拟议方案,仅保留兼容代码,不是本次后端实现。
|
||||
|
||||
## 2026-10-29 零件单项管理
|
||||
|
||||
- 当前零件列表支持按文件名/目录搜索(忽略大小写),显示匹配数,逐行删除。
|
||||
- “上传单个零件”选择 GLB 后自动添加,可指定相对目录,默认根目录;完全相同路径需要确认替换。同名但不同目录按不同零件处理。
|
||||
- 后端目前只有整批签名/绑定、整类清除接口。单项增删通过读取原清单、四路下载保留文件、合并后四路上传新批次、完整绑定实现;删除最后一个零件直接清除零件绑定。不会调用不存在的单文件接口,不会把新增一个文件误提交成整组清单。旧 OSS 对象仍保留。
|
||||
- 代价:零件数量较多时,单项变更也会传输保留的零件,页面显示进度;若后端增加原子增删/保留对象引用接口,可替换该兼容流程以减少流量和内存使用。
|
||||
- 下载失败不提交新绑定;失败允许手动重试并复用已成功的文件。确认结果未知时必须先刷新核对,不自动重复提交。开始操作及确认前核对绑定是否变化;后端尚无版本号/CAS,这不是跨客户端原子并发锁。
|
||||
- 删除零件不自动改写已有步骤 JSON,界面提示管理员同步调整引用该零件的步骤。
|
||||
|
||||
- 验证:新增 8 项零件管理测试及原 7 项自动上传测试通过,dev 构建通过。真实 dev 联调项目 b7drj14qq1nf 添加测试零件(275 → 276)后删除(276 → 275),刷新确认生效;保留的 275 个零件逐一下载比对 SHA256,与 Microban 原文件全部一致。未操作用户截图中的 gcw47xwyyhr8 项目资源。
|
||||
|
||||
## 当前四类资源接口
|
||||
|
||||
- model-glb:单个 GLB;model-parts:文件夹内 GLB,保留子目录;assembly-json:单个 JSON,后端不解析业务内容;walking-resources:全部目录文件,无 robot.json 要求。
|
||||
- 签名提交 files[{relativePath,sizeBytes}];OSS 按原 formFields + File 直传,最多四路,不携带管理 Token;全部成功后 PUT {batchCode,files}。返回平铺 ProjectView,合入详情的 project。
|
||||
- 允许零字节,不设前端大小/数量配额。只校验扩展名和文档路径规则;可视化编辑另需能解析真实 GLB。
|
||||
- 同批成功文件手动重试不重传;网络不确定/过期使用新批,确认结果不明先刷新核对。替换整类资源需要完整清单;DELETE 幂等清除绑定但不删除对象。
|
||||
- 详情页选好文件即自动签名、直传并确认绑定;失败保留选择,仅显示手动重试,不自动循环重试。新建页先选文件,项目创建且 READY 后按类别依次自动上传。装配编辑器保存时生成 JSON 并自动上传;零件仍通过 model-parts 独立绑定。
|
||||
- 2026-10-28 dev 真实联调:本地入口改为 http://localhost:8091,项目 b7drj14qq1nf(未发布)。使用 Microban-后台上传资料-20261028,整机 GLB 1 个、零件 GLB 275 个、步骤 JSON 1 个、运动目录文件 32 个均已自动上传并确认绑定,刷新后保留。逐个从 OSS 下载比对 SHA256:309/309 与本地原文件一致。保留 parts/、assets/、policies/ 等相对路径。此前 localhost:5188 的 OSS CORS 阻塞在 8091 下未复现。
|
||||
- 自动化覆盖四类资源自动上传、零字节与目录、失败后仅重试未成功文件、新建项目多类串行上传、仓库 READY 后开始且不重复,共 7 项通过。可视化编辑生成 JSON 后自动上传也已在 dev 实测成功。
|
||||
- 本次不宣称行走策略已执行、前台仿真成功或 JSON 播放契约已验证,接口仅核验对象存在及大小。
|
||||
|
||||
# 模型与演示:后台已实现的第一阶段接口约定
|
||||
|
||||
日期:2026-10-28。用于后端实现和前后台联调;以下新增接口尚未上线,前端已按本约定接入,不能将 UI 或模拟测试通过视为真实上传成功。
|
||||
|
||||
协议来源:`vibemake-site/docs/admin-model-assembly-walking-spec.md`。根据本次需求,**前端不限制文件大小,不限制机器人型号和 runtimeProfile**;文件限额、ZIP 解压保护、完整性及运行器兼容性均由后端校验并返回具体结果。
|
||||
|
||||
## 1. 本期范围
|
||||
|
||||
项目详情新增“模型与演示”:整机 GLB、零件 GLB 文件夹、装配步骤 JSON、行走 ZIP 上传;资源库;JSON 文件映射;候选导入确认;草稿启停/清空;版本构建;打开平台预览;完整快照发布。
|
||||
|
||||
装配的主入口是“制作装配流程”:支持本地/已上传 GLB 的三维点选与列表多选、分组、轴向进入距离预览、拖动排序、批量进入设置、撤销/重做、复制步骤设置和完整流程播放。“高级导入(JSON)”仅导入步骤配置;零件从上方“零件模型”选择。保存时程序生成 v1 装配清单,用户不用输入编号、四元数或哈希。不做通用自动几何对齐或策略训练;坐标不一致的零件可用移动/旋转控件手动对齐。原始 GLB 直传 OSS,保留材质、颜色、贴图与文件字节。
|
||||
|
||||
本地文件也可先制作流程(无前端大小限制)。SHA256 由 Web Crypto 对原文件计算;未上传的临时资源编号只保留在页面内存中,不向保存接口提交。上传确认后,按类型、完整相对路径、字节数、SHA256 唯一匹配服务器 assetId,存在歧义时不自动替换。新建项目到详情页的一次 SPA 跳转同时保留文件和流程;浏览器刷新前需要上传并保存,或先导出系统生成的 JSON。
|
||||
|
||||
界面按“整机模型、零件模型、拼装步骤、行走演示”四个独立区域组织,不让管理员在资源类型下拉框反复切换。新建页可同时选择整机和零件,创建后保留这些 File 并直接进入模型页继续上传;实际上传仍使用当前项目的签名接口,不将文件序列化进创建项目 JSON。文件选择仅在本次页面操作中保留,刷新页面需重新选择。
|
||||
|
||||
整机上传确认后自动选用到本地展示设置;完整包上传后自动发起读取;独立 JSON 仅逐路径核对“零件模型”已上传的 part-glb,不将整机 GLB 当作零件候选;缺少/有歧义时才提示管理员核对。导入确认仅更新对应的装配或行走区域,保留已选择的整机与另一种演示。按钮“检查并预览”会先保存本地修改,再生成检查版本;最终仍需单独确认发布。
|
||||
|
||||
所有新增路径均带 `/admin-api` 前缀,沿用当前 Bearer Token 和 `{code,message,data,requestId}` 响应。下面列出的结构是 **data 内容**。精确 TypeScript 定义:`src/api/experience-types.ts`;请求实现:`src/api/experiences.ts`。
|
||||
|
||||
## 2. 资源类型与上传
|
||||
|
||||
当前上传入口仅使用 `whole-glb`、`part-glb`、`assembly-manifest`、`walking-zip`。零件只通过文件夹选择,批量签名和原文件直传仍使用 part-glb;保留文件夹内相对路径,过滤非 GLB 与 macOS 的 `._` 伴随文件。前端不设置大小/数量限额。`parts-zip/assembly-zip` 类型仅为历史兼容保留,不再提供新的上传或读取入口;旧资源不物理删除。
|
||||
|
||||
### POST /projects/{projectCode}/model-assets/signature
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "part-glb",
|
||||
"files": [{"relativePath":"left/arm.glb","sizeBytes":18876964}]
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"batchCode":"batch-001",
|
||||
"uploadUrl":"https://oss.example.com",
|
||||
"expiresAt":"2026-10-28T08:00:00",
|
||||
"files":[{
|
||||
"relativePath":"left/arm.glb",
|
||||
"objectKey":"project/immutable-key/left/arm.glb",
|
||||
"formFields":{"key":"project/immutable-key/left/arm.glb","policy":"SIGNED_POLICY","signature":"SIGNED_VALUE"}
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
`formFields` 是服务端签名结果,上例仅说明结构。客户端原样构建 OSS FormData;不携带后台 Authorization,不重写 Content-Type。最多 4 路并发;全部在途文件结束后才允许重试。明确失败时只补传同批次未成功的文件;签名过期或传输结果未知时使用新批次,避免覆盖旧对象。已经传输完成但 complete 返回丢失时,仅再次确认同一 batchCode。
|
||||
|
||||
### POST /projects/{projectCode}/model-assets/complete
|
||||
|
||||
请求仅为 `{"batchCode":"batch-001"}`,不接受任意客户端 objectKey。返回第 4 节的 ExperienceOperation,可同步返回资源,也可返回 jobId。
|
||||
|
||||
服务端核对项目归属、实际字节与 SHA256;ZIP 解压、GLB 元数据分析等可异步执行。**相同 batchCode 重复确认必须幂等**,返回同一资源/任务,不能重复创建资源。不要在签名接口自动绑定项目或发布。
|
||||
|
||||
### GET /projects/{projectCode}/model-assets?cursor=...&type=part-glb
|
||||
|
||||
`cursor/type` 可选。使用游标分页,不是已有用户/项目列表的 page 分页:
|
||||
|
||||
```json
|
||||
{
|
||||
"items":[{
|
||||
"assetId":"asset-arm-left",
|
||||
"type":"part-glb",
|
||||
"relativePath":"left/arm.glb",
|
||||
"bytes":18876964,
|
||||
"sha256":"5976d400a8f87877fee0be58731e13b8c1db84271b24d35ed889f255e56f894a",
|
||||
"status":"READY",
|
||||
"downloadUrl":null,
|
||||
"metadata":{"meshCount":12,"triangleCount":15000}
|
||||
}],
|
||||
"nextCursor":null
|
||||
}
|
||||
```
|
||||
|
||||
状态为 `PROCESSING/READY/FAILED`。已上传 GLB 的 `downloadUrl` 需返回可供后台跨域读取的 HTTP(S) 原文件地址(可短期签名并支持刷新获取),才能在可视化编辑器中载入;不能是任意脚本 URL。为 null 时明确显示无法预览,允许重新选择本地原文件。单独 JSON 的资源还需返回 `metadata.manifestFiles: [{path,bytes,sha256}]`,供管理员逐路径映射已有 GLB。行走元数据可返回 `robotId/runtimeProfile`,后台只展示识别结果,不硬编码值。
|
||||
|
||||
## 3. 草稿
|
||||
|
||||
### GET /projects/{projectCode}/experience-draft
|
||||
|
||||
新项目也应返回 HTTP 200、revision=0 和三个 null 绑定;**不要用 404 表示空草稿**。后台遇到 404/405/501 会展示“接口待接入”,并禁止伪保存。
|
||||
|
||||
```json
|
||||
{
|
||||
"projectCode":"project-a",
|
||||
"revision":0,
|
||||
"wholeModel":null,
|
||||
"assembly":null,
|
||||
"walking":null,
|
||||
"report":null,
|
||||
"latestBuild":null,
|
||||
"published":null
|
||||
}
|
||||
```
|
||||
|
||||
### PUT /projects/{projectCode}/experience-draft
|
||||
|
||||
完整替换:三个字段必须出现,null 表示清空;不是“省略即清空”。
|
||||
|
||||
```json
|
||||
{
|
||||
"expectedRevision":12,
|
||||
"wholeModel":{"assetId":"asset-robot","displayQuaternion":[0,0,0,1]},
|
||||
"assembly":{
|
||||
"enabled":true,"title":"机器人装配","unit":"meter",
|
||||
"referenceAssetId":"asset-robot","displayQuaternion":[0,0,0,1],
|
||||
"parts":[{
|
||||
"id":"base","name":"底座","assetId":"asset-base","parentId":null,
|
||||
"position":[0,0,0],"quaternion":[0,0,0,1],"scale":[1,1,1],"installOffset":[0,0.08,0]
|
||||
}],
|
||||
"steps":[{"id":"step-1","label":"安装底座","parts":["base"]}],
|
||||
"editorGroups":[{"id":"group-base","name":"底座组件","parts":["base"]}]
|
||||
},
|
||||
"walking":null
|
||||
}
|
||||
```
|
||||
|
||||
行走非空时:`{enabled,packageAssetId,robotId,runtimeProfile}`。各项目使用自己的标识和资源,不套用 Microduck 样例。保存成功递增 revision,并返回完整 ExperienceDraftView。冲突返回 HTTP 409/`REVISION_CONFLICT`,不得自动覆盖。
|
||||
|
||||
`assembly.editorGroups` 是可选的编辑器分组,保存后原样返回,用于再次编辑;不放入公开 manifest,也不改变播放语义。其他装配字段沿用 v1,不需要新增“上传步骤 JSON”才能保存可视化流程。构建时由 parts.assetId 获取不可变原文件的真实 bytes/SHA256,生成公开 JSON 与文件映射。相同资源的多个实例只声明一次文件;同路径的不同资源应生成无冲突的包内路径。实例位置/四元数/缩放使用父节点局部坐标,保留 GLB 内部节点变换;进入动画从 position + installOffset 到 position,不改最终方向或材质。
|
||||
|
||||
步骤需覆盖所有实例、每个实例安装一次,父零件必须在同一步或更早的步骤中。编辑器在排序、替换步骤零件后会校验;后端仍需独立校验。复制步骤只复制名称和进入设置,提示另选一组零件,防止产生重复安装。单个 GLB 内部的多个网格保留为同一个文件实例;若希望独立选择,应上传分件 GLB。
|
||||
|
||||
`enabled=false` 保留草稿内容;重新生成并发布版本后对应社区字段为 null。清空绑定不物理删除历史发布正在引用的对象。
|
||||
|
||||
## 4. 统一异步结果
|
||||
|
||||
complete/import/build 三类 POST 均返回 ExperienceOperation。所有可空字段请显式返回 null,数组返回 []:
|
||||
|
||||
```json
|
||||
{
|
||||
"jobId":"job-001",
|
||||
"assets":[],
|
||||
"draftCandidate":null,
|
||||
"build":null,
|
||||
"report":null
|
||||
}
|
||||
```
|
||||
|
||||
同步完成时 `jobId=null`,其余字段放对应结果。异步任务:
|
||||
|
||||
### GET /projects/{projectCode}/experience-jobs/{jobId}
|
||||
|
||||
```json
|
||||
{
|
||||
"jobId":"job-001",
|
||||
"status":"RUNNING",
|
||||
"phase":"VALIDATING",
|
||||
"message":"正在校验包内引用",
|
||||
"report":null,
|
||||
"result":null
|
||||
}
|
||||
```
|
||||
|
||||
状态:`QUEUED/RUNNING/SUCCEEDED/FAILED`。成功时 result 必须为 `{assets,draftCandidate,build,report}`;不是整个响应信封。失败保留 report 中的定位信息。前端串行约 3 秒查询,不捏造百分比;查询失败显示恢复查询,离开项目时停止,不自动重发 POST。
|
||||
|
||||
Report:`{status: "PENDING" | "PASSED" | "FAILED", errors: Issue[], warnings: Issue[]}`;Issue:`{code,message,path?,partId?,stepId?}`。类型、错误码可自由扩展;前端显示未知错误码的原文。
|
||||
|
||||
## 5. 导入
|
||||
|
||||
### POST /projects/{projectCode}/experience-imports
|
||||
|
||||
```json
|
||||
{
|
||||
"sourceAssetId":"asset-assembly-json",
|
||||
"kind":"assembly",
|
||||
"expectedRevision":12,
|
||||
"assetBindings":[{"path":"left/arm.glb","assetId":"asset-arm-left"}]
|
||||
}
|
||||
```
|
||||
|
||||
`kind=parts/assembly/walking`。完整 ZIP 自带映射,不需要 assetBindings;独立装配 JSON 必须逐路径绑定本项目已上传资源。后端核对 bytes/sha256,不能仅按 basename 匹配。
|
||||
|
||||
返回统一异步结果。parts 导入只返回 assets,不凭空创建位姿;assembly/walking 返回基于 expectedRevision 的**完整** draftCandidate 和校验报告,不直接覆盖服务端草稿。只有 report.status=PASSED 时后台才允许应用候选;应用后仍需用户保存草稿。
|
||||
|
||||
后端应分别报告文件完整性、运行器兼容性、仿真验收结果。后台允许任何型号/运行器的包上传,不据 `microduck-alpha-v1` 建白名单;不兼容或未验收的包如何进入候选/发布,由后端报告决定,不能把“上传成功”当作“仿真已验收”。
|
||||
|
||||
## 6. 构建与预览
|
||||
|
||||
### POST /projects/{projectCode}/experience-builds
|
||||
|
||||
请求:`{"draftRevision":13}`,返回统一异步结果,结果内 build 为:
|
||||
|
||||
```json
|
||||
{
|
||||
"buildId":"build-013","draftRevision":13,"status":"READY",
|
||||
"publishable":true,"publicationMessage":null,
|
||||
"report":{"status":"PASSED","errors":[],"warnings":[]},
|
||||
"outputs":{
|
||||
"glbMainUrl":null,"glbConfig":null,
|
||||
"assemblyManifestUrl":"https://assets.example.com/project-a/assembly/a1/manifest.json",
|
||||
"walkingManifestUrl":null
|
||||
},
|
||||
"previewUrls":{"wholeModel":null,"assembly":"https://community.example.com/preview/controlled-ticket","walking":null}
|
||||
}
|
||||
```
|
||||
|
||||
`status=READY/FAILED`。publishable=false 时 publicationMessage 应说明尚未完成的校验/验收。空配置也允许构建,用于发布清空后的快照。
|
||||
|
||||
**previewUrls 是前台同协议播放器的受控预览页面地址,不是 ZIP 或 GLB 下载地址。** 后台不自行执行 ZIP 中的 HTML/JS/WASM,不假造预览。后端需与前台确定正式预览路由和整包鉴权方式;原前台 `/examples/experience-preview.html` 只在本地存在,不可当线上地址返回。manifest 的单独查询签名不能自动解决所有相对资源的私有访问。
|
||||
|
||||
outputs 中 manifest 字段必须是可加载的解压后 JSON 地址,引用文件与清单同版本;生成 build 不等于公开发布。后台下载/预览链接应受控或带有效期,社区接口只返回已发布快照的公开地址。
|
||||
|
||||
## 7. 原子发布
|
||||
|
||||
扩展已有 `PUT /projects/{projectCode}/publication`:
|
||||
|
||||
```json
|
||||
{
|
||||
"commitSha":"当前 main SHA",
|
||||
"experienceBuildId":"build-013",
|
||||
"expectedDraftRevision":13
|
||||
}
|
||||
```
|
||||
|
||||
服务端重新确认项目、main SHA、草稿 revision、构建归属、文件完整性及验收结果,原子写入代码与资源快照。失败保留旧发布版本。**允许 commitSha 不变、只更新资源快照。**
|
||||
|
||||
兼容旧请求只传 commitSha:保留当前已发布的资源,不能清空,也不能自动选择最新上传文件。后台原有顶部发布按钮走此兼容语义;“模型与演示”的“发布此资源版本”才携带资源构建参数。
|
||||
|
||||
GET 草稿的 published 返回:`{releaseId,commitSha,draftRevision,experienceBuildId,publishedAt,glbMainUrl,glbConfig,assemblyManifestUrl,walkingManifestUrl}` 或 null。相关 URL/config 同时加入后台 ProjectView 和社区项目详情。
|
||||
|
||||
社区规则:已发布的 assemblyManifestUrl/walkingManifestUrl 非空才展示对应入口,null 隐藏;关闭开关或清空绑定必须发布后才影响社区。各项目独立,不能按名称匹配或自动补其他项目的演示。
|
||||
|
||||
## 8. 交接前仍需对齐
|
||||
|
||||
1. 上述新增接口的完整返回结构及 HTTP 202 异步语义,由后端按此契约实现或反馈差异。
|
||||
2. 前台新增 glbMainUrl/glbConfig 主展示读取;装配/行走目前已读取两个 manifest 字段。
|
||||
3. 前台行走加载器当前固定 microduck-alpha-v1。后台已取消型号限制;其他机器人真实播放仍需前台/算法提供匹配运行器并注册,上传文件不能自动生成运行器。
|
||||
4. 受控平台预览路由、预览票据与全部依赖文件的访问方式。
|
||||
5. 后端各文件类型的大小/数量限制及错误码,返回时前端展示后端 message/requestId,不内置前端大小上限。
|
||||
6. 正式联调关闭前台本地样例补全,验证“未上传/关闭/清空 → 发布 → null → 隐藏入口”,并验收实际设备上的装配及行走行为。
|
||||
|
||||
## 9. 旧版 Microduck v1 兼容报告(仅此格式;通用规则见第 10 节)
|
||||
|
||||
后台仍采用完整 `walking-zip` 上传/导入/构建链路,不开放未接通的逐项上传或自动补策略。`src/config/walking-upload-requirements.json` 仅为旧版 Microduck v1 模板,只有明确识别旧格式或用户主动查看专用示例时使用,不作为默认上传清单。该 JSON 是 UI 展示配置,不是社区 manifest,不是 API。
|
||||
|
||||
已将实际完整样例随项目静态发布:`public/examples/microduck-alpha-v1/7114a32b7a3e/microduck-walking.zip`,12,786,579 字节,SHA256 `7114a32b7a3e7b6264312e83dc88aa9d38760230c866eacdeadf9fba3e59bcd4`。已核对完整包及清单声明的 164 个资源的真实字节数/哈希;此核对不等同于后台实际浏览器仿真验收。ZIP 含 166 个文件(另有目录条目),这些数字不作为其他包验收条件。下载链接是同源静态路径,Vite 构建会复制进 dist,无需本机绝对路径或新的下载 API;部署时必须包含该目录。文件要求亦可下载为面向准备人员的文本。
|
||||
|
||||
旧版 ExperienceReport 的总状态不能推断各个文件、阶段已经通过。为 complete/import/job/build/draft 中的 ExperienceReport 增加可选 `walking`:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "FAILED",
|
||||
"errors": [{"code":"MISSING_POLICY","message":"缺少左脚踢球策略","path":"policies/ball_kick_left.onnx"}],
|
||||
"warnings": [],
|
||||
"walking": {
|
||||
"sourceAssetId": "walking-zip-001",
|
||||
"robotId": "microduck-alpha",
|
||||
"runtimeProfile": "microduck-alpha-v1",
|
||||
"items": [
|
||||
{"key":"robot/mjlab/microduck.glb","path":"robot/mjlab/microduck.glb","state":"found_pending_validation"},
|
||||
{"key":"policies/ball_kick_left.onnx","path":"policies/ball_kick_left.onnx","state":"missing","suggestion":"请补齐同一演示工程的左脚踢球 ONNX 后重新上传。"},
|
||||
{"key":"meshes","state":"not_checked"},
|
||||
{"key":"assets","state":"not_checked"},
|
||||
{"key":"provenance","state":"not_checked"}
|
||||
],
|
||||
"stages": [
|
||||
{"id":"identify","state":"passed"},
|
||||
{"id":"integrity","state":"mismatch","message":"资源包缺少必需策略"},
|
||||
{"id":"compatibility","state":"not_checked"},
|
||||
{"id":"runtime","state":"not_checked"},
|
||||
{"id":"review","state":"not_checked"}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `sourceAssetId` 必须是本次检查的不可变行走 ZIP 资源;不能使用项目编码代替版本。后台仅对匹配资源显示逐项状态;重新选择的 File 不复用同名旧 ZIP 的结果。发布预览仍绑定同一草稿 revision/buildId。
|
||||
- 单文件 `key` 使用完整包内路径;若提供 `path`,同样必须是完整路径。依赖组 key 使用 `meshes/assets/provenance`,滚轮扩展可用 `rollers` 或具体路径;扩展结果放完整报告,不列为七策略基础必备。
|
||||
- `items[].state` 和 `stages[].state`:`not_checked/found_pending_validation/missing/checking/passed/mismatch/runtime_failed`。阶段 id:`identify/integrity/compatibility/runtime/review`。每项可带 `message/suggestion`。未返回的项显示“未检查”;未执行的试运行和预览显示“未执行”,不会用总的 PASSED 补绿。
|
||||
- report.walking 同样可随失败响应的 `data` 返回(与 `errors/warnings` 并列),或随异步任务的 report 返回,以便失败时保留中文错误、完整路径和 requestId。缺项报告不会应用候选草稿;失败不清除所选 ZIP,也不改旧发布资源。
|
||||
- `meshes` 按实际引用检查,不规定 STL 数量。`assets/` 和来源说明保留模板内容;不要把模板素材通过检查等同于所有用户新策略可运行。全部七个基础策略启动必需,另外两个滚轮策略只作扩展。
|
||||
- 兼容性检查需检查完整 controller 控制语义与映射,不能只比较 ONNX 张量维度;实际试运行需使用同版本浏览器运行器。没有执行不得返回 passed。
|
||||
- 没有后端服务或只做了 ZIP 扩展名/文件头检查时,后台显示尚未检查内容,下载与说明仍可使用。后台不实施仿真、不伪造逐项结果。接口是否可发布最终仍由当前版本的 build.publishable/publication 接口判断。
|
||||
- Microduck 说明只代表当前提供的模板;沿用用户要求,后台不按机器人 ID 硬编码禁止其他项目上传,也不设文件大小上限。其他机器人是否能播放由对应运行器与服务端兼容性结果决定。
|
||||
|
||||
## 10. 通用机器人运动演示:按包报告展示(取代固定默认清单)
|
||||
|
||||
默认页面与准备说明现在是通用的;没有识别包时,不预填“左脚踢球”等策略。`src/config/walking-upload-profiles.json` 是模板/格式说明索引,不是播放器协议或已部署能力注册表。只有旧格式 `legacy-walking-v1`(兼容未返回 format、但明确 runtimeProfile=microduck-alpha-v1 的老报告)使用第 9 节清单。机器人名称不作为判断条件,显式 Robot Package 格式优先于旧 profile,不能把新版 Microduck 的九策略声明降成旧七策略。
|
||||
|
||||
后端应沿用播放器原生 robot.json schema 与跨字段规则解析,按 model、assets.path/VFS、skills.controller.policy、render.source 和平台维护的 adapter 依赖规则生成 requirements。ONNX 路径去重并保留引用技能;oscillator 无额外策略文件。不要按 id=microban 等名称分支套文件数、模型名或策略路径;不要向后台再引入一套不同控制配置。
|
||||
|
||||
现有 `ExperienceReport.walking` 扩展如下(字段定义见 experience-types.ts):
|
||||
|
||||
```json
|
||||
{
|
||||
"sourceAssetId":"immutable-robot-package-asset",
|
||||
"robotId":"robot-from-config",
|
||||
"runtimeProfile":"generic",
|
||||
"format":"robot-package",
|
||||
"entry":"robot.json",
|
||||
"adapter":"generic",
|
||||
"requirements":[
|
||||
{"key":"entry","label":"机器人配置","path":"robot.json","category":"config","required":true},
|
||||
{"key":"model","label":"物理模型","path":"model.xml","category":"model","required":true},
|
||||
{"key":"walk-policy","label":"行走策略","path":"policies/walk.onnx","category":"policy","required":true,"skills":["行走"]}
|
||||
],
|
||||
"capabilities":[
|
||||
{"id":"walk","label":"行走","controller":"onnx","policyPath":"policies/walk.onnx","supported":true},
|
||||
{"id":"head","label":"转头","controller":"oscillator","supported":true}
|
||||
],
|
||||
"items":[{"key":"policies/walk.onnx","path":"policies/walk.onnx","state":"found_pending_validation"}],
|
||||
"stages":[{"id":"identify","state":"passed"},{"id":"runtime","state":"not_checked"}],
|
||||
"communityRuntime":{"status":"pending","message":"社区的通用包入口尚未部署"}
|
||||
}
|
||||
```
|
||||
|
||||
示例省略模型的实际网格闭包;真实报告必须返回该包实际依赖,而非固定填 25 个。requirements.category 为 config/model/dependency/policy/render/provenance/adapter,另可带 help/preparedBy;required 仅表示该包需要。capabilities 只列配置实际声明的动作,supported 表示内置运行器能力支持,不代表试运行通过,更不代表社区已经部署。未知适配器或能力明确返回不支持并说明,不执行包内自带 JS。
|
||||
|
||||
format 可为 legacy-walking-v1 / robot-package / walking-transport-v2 / unknown。后两种新格式的报告必须明确社区接入情况。communityRuntime.status 为 supported/pending/unsupported:pending 或未返回支持确认时,后台对 Robot Package 不开放资源预览与发布,即使上传成功或总报告 PASSED,也不能据此宣称旧社区可播放。草稿上传与保存仍允许;实际发布接口必须再次校验。
|
||||
|
||||
通用阶段为 identify/integrity/contract/runtime_support/runtime/review;旧 compatibility 保留兼容。未返回结果仍显示未检查,runtime/review 未执行。源资源仍以不可变 sourceAssetId 绑定,关联 ModelAsset 的字节/哈希与构建 revision;同名新 File 不复用旧结果。没有后端解析服务时仅展示通用说明和 ZIP 文件头检查结果,不伪造 robot.json 已解析。
|
||||
|
||||
明确的带路径错误优先于“文件存在”状态。LFS_POINTER 等错误显示“资源未下载完整”,不能以文件存在或扩展名正确显示通过;缺策略时指出实际引用动作与路径。检测内容、引用闭包、schema、跨字段、控制契约、ONNX 实际推理及仿真仍由后端/运行器完成。
|
||||
|
||||
旧版示例 ZIP 仍保留在显式选择的“旧版 Microduck v1 专用兼容示例”内。Microban 仅提供原样 robot.json 配置参考,现有下载副本包含 26 个 Git LFS 指针,不能制作“可运行示例”。切换参考模板不会修改当前包的 requirements 或上传文件。
|
||||
|
||||
Robot Package 发布外壳 transport v2 仍为拟议协议,本次未实现前后台传输与播放接入,未修改社区播放器或覆盖 sandbox。后续需共同确认外壳、依赖闭包、同源受控入口与路径规范化;不能全局放宽路径穿越检查,不能把下载工程本地运行等同于 OSS 动态资源可播放。
|
||||
|
||||
## 11. 装配操作入口简化
|
||||
|
||||
零件模型只保留“选择零件文件夹”与“上传零件文件夹”,无单文件多选和 ZIP。目录中的子文件夹路径保持不变,只检查/上传 GLB;其他文件明确提示已忽略。没有 GLB 的文件夹显示错误,不允许制作空流程。制作装配流程直接使用本项目上方已选/已上传的零件,编辑器不另设上传入口;整机只用于参考,不进入新增零件候选。旧流程已引用的数据保留,避免界面简化破坏已有流程。
|
||||
|
||||
高级导入仅 JSON。清单文件引用逐项按完整路径、字节数与 SHA256 核对本项目 part-glb;映射对话框也仅提供零件模型,不提供整机。批量上传顺序保持整机→零件→步骤 JSON,生成版本前仍检查真实资源关联与草稿修订。API 无需新增目录或 ZIP 解压协议,继续签名批量 GLB 原文件。
|
||||
|
||||
## 12. 行走表单 v3:本次后台与后端联调约定(待后端实现)
|
||||
|
||||
本节为新版默认入口,覆盖前面“仅 ZIP”的交互说明;旧 ZIP 接口继续用于显式兼容区。来源为 `admin-walking-upload-generic-spec.md` 与 `src/config/walking-upload-profiles.json` v3。本仓库完成后台表单、上传适配与前端流程;下面的接口是待双方确认并实施的约定,不表示服务器已部署,也不表示社区播放器已完成能力拆分。
|
||||
|
||||
### 表单与资源
|
||||
|
||||
基础四项为机器人控制配置、MJCF、模型实际引用文件、配套 primary ONNX。无外部引用的 MJCF 不要求上传空目录。客户端读取 schema=1 的 robot.json 来辅助绑定实际 skill id 和路径;完整 schema、引用闭包、关节/观测/动作维度、推理及仿真检查由后端执行。前端没有文件大小上限,后端的限制需通过结构化错误返回。
|
||||
|
||||
十项可选功能默认关闭:head、sit_stand、roll、kick_left、kick_right、recovery、ground_pick、rollers、roller_crouch、visual_model。按选中功能要求资源;oscillator 不强制 ONNX,多个技能允许共用一个策略。roller_crouch 依赖 rollers。恢复自动触发须另行明确开启。额外素材保存在资源库,不能仅因存在文件就新增功能或加载到前台。
|
||||
|
||||
足球和拾取物的预设由后端提供 id、不可变 version、label、kind、parameters,禁止客户端猜测物理参数。左右踢球共用一个足球;未选踢球且未明确拾取足球时不显示足球。上传足球 GLB 仅替换外观,不能替代物理预设。社区最终只展示所发布能力,按能力懒加载依赖。
|
||||
|
||||
### 路由与请求
|
||||
|
||||
管理 API 根路径仍是 `/admin-api`,统一响应封套沿用现有接口。下表路径均相对 `/projects/{projectCode}/walking-editor`。完整、逐字段类型以 `src/api/walking-editor-types.ts` 为准,调用实现在 `src/api/walking-editor.ts`。
|
||||
|
||||
| 方法与路径 | 请求 | 返回 data |
|
||||
| --- | --- | --- |
|
||||
| GET 空路径 | 无 | WalkingEditorView |
|
||||
| PUT 空路径 | expectedRevision、expectedExperienceDraftRevision、draft | WalkingEditorView |
|
||||
| POST /resource-signatures | files: [{clientId, relativePath, originalPath, sizeBytes, kind}] | batchCode、uploadUrl、expiresAt、files: [{clientId, relativePath, formFields}] |
|
||||
| POST /resource-completions | {batchCode} | {resources: WalkingResource[]} |
|
||||
| POST /checks | expectedRevision、expectedExperienceDraftRevision | WalkingEditorOperation |
|
||||
| POST /builds | expectedRevision、expectedExperienceDraftRevision、checkId、capabilityIds | WalkingEditorOperation |
|
||||
| POST /imports | expectedRevision、sourceResourceId | WalkingEditorOperation,含 importCandidate |
|
||||
| GET /jobs/{jobId} | 无 | WalkingEditorJob |
|
||||
|
||||
签名中的 clientId 原样回传,关联本地文件;不能按叶文件名匹配。文件直传到 uploadUrl,使用各自 formFields + 原 File,最多四路并发,不重新编码或改变材质。complete 由服务器核验真实对象,返回 clientId、resourceId、relativePath、originalPath、bytes、sha256、kind、status(READY/PROCESSING/FAILED)。hash 必须为服务器核验的 64 位 SHA256。相同 batchCode 的 complete 必须幂等,不能重复新增资源。签名过期/结果未知的新批次使用新对象,不覆盖旧对象;确认接口不得信任客户端哈希或文件索引。
|
||||
|
||||
### 草稿、并发与异步
|
||||
|
||||
WalkingEditorView 必须包含 apiVersion=1、revision、experienceDraftRevision、sourceVersion、draft、resources、skills、presets、featureSupport、check、latestBuild、experienceDraft。未检查/未构建使用 null,不能伪填 PASSED。404/405/501 在后台显示“接口待接入”,用户仍能选择文件但不能上传/保存。
|
||||
|
||||
草稿结构包括 enabled、entryResource、modelResource、dependencyResources、walkPolicyResource、walkSkillId、features、football、pickupTarget、resourceIds。所有 Resource 字段提交真实 resourceId;resourceIds 可包含未绑定素材。features 每项包含 enabled、skillIds、configResource、policyResources、modelResource、dependencyResources、mappingResource、autoTrigger。足球绑定为 {presetId, version, visualResource},拾取物额外有 kind。允许保存不完整草稿,缺文件不等于能构建或发布。资源引用必须属于当前项目,未启用功能不阻断基础校验。
|
||||
|
||||
PUT 同时校验独立行走 revision 和全项目 experienceDraftRevision,原子更新两者。返回新的完整 experienceDraft 快照;其中 walkingEditorRevision 指向已保存的行走表单版本。普通整机/装配草稿写入必须保留此令牌,不能因为旧 walking 字段为 null 就清除新表单。构建以该令牌组合整机、装配和行走,绑定全项目修订号。禁用新行走模块应通过新版 draft.enabled=false 保存;不得让旧版入口意外覆盖新版本。PUT 返回与接受值语义一致的 draft,若需要规范化或补充功能绑定,返回显式导入候选供确认,不能静默修改用户选择。
|
||||
|
||||
冲突返回 409,后台保留本地文件与表单,刷新核对后才可再次提交。网络/5xx 的写入结果不明时先查状态,不自动重发。长任务返回 jobId,后台串行查询(两秒间隔),离开页停止;查询失败可继续查询相同任务,不再次创建操作。Job 状态为 QUEUED/RUNNING/SUCCEEDED/FAILED;完成返回 view,失败保留旧发布版本并带具体报告。sourceVersion 覆盖配置和资源内容,任一变化使旧 check/build 失效。
|
||||
|
||||
ZIP 导入先上传 archive,再解析;返回 view.resources 和 importCandidate。候选确认只应用本地表单,后续仍需保存、校验;不直接覆盖已发布数据。未绑定额外文件保留草稿。无效路径、符号链接、重复路径、解压限制、LFS 指针等由服务端检验,不能信任 ZIP 内自带 manifest 的哈希或能力声明。
|
||||
|
||||
### 分功能检查与部分发布
|
||||
|
||||
check 包括 checkId、draftRevision、sourceVersion、base、features[]、communityRuntime。base/feature 各有 capabilityId、status、message、issues[];issue 带 scope(base/feature)、capabilityId、code、path、message。status 为 PENDING/PASSED/FAILED/UNSUPPORTED/NOT_RUN。PASSED 需代表实际契约和运行检查完成,不能仅检查文件名。未部署运行器为 pending/unsupported,禁止生成可发布演示。
|
||||
|
||||
基础失败阻断整次发布,选填功能失败只影响该功能。后台明确列出失败项,并让用户确认已通过子集 capabilityIds;必须包含 walk,包含全部功能依赖,且均属于本次同一 sourceVersion 的有效检查。服务端再次验证子集,按它重新编译 robot.skills、输入绑定、道具和依赖闭包。失败或未选的功能与额外素材保留草稿,不进入发布依赖,不自动删除。
|
||||
|
||||
build 返回 WalkingEditorBuild(draftRevision、sourceVersion、checkId、capabilityIds、experienceBuild)。experienceBuild 沿用全项目模型构建结构及最终 SHA/revision 发布接口。只有同版本检查通过、运行器 supported、构建 publishable 且 report PASSED 才能预览/发布。后端必须重新核验这些条件,不能信任 UI 的按钮禁用。发布为不可变快照,用户修改草稿不会改变当前线上演示。
|
||||
|
||||
联调顺序:GET 初始化与预设 → 签名/直传/确认 → PUT 乐观锁 → 分功能检查 → 子集构建/预览 → 原子发布 → 社区按能力展示。前端自动化使用模拟接口验证流程;真实文件推理、预设物理效果、社区资源按需加载及生产接口需要后续联合验收。
|
||||
|
||||
### 工程文件夹入口与页面命名补充
|
||||
|
||||
后台入口统一命名为“装配与仿真”。行走表单支持直接选择工程根文件夹,不要求压缩为 ZIP;目录文件复用上述批量签名/直传/确认接口,无需新增解压接口。去掉所选外层目录名,保留包内子路径;原路径保留在 originalPath。识别根 robot.json,绑定明确的 model 路径;只有唯一 primary ONNX 时自动绑定基础策略,多个 primary 时由用户选择。已有基础绑定保留,额外动作默认关闭。所有目录资源均可上传,服务端应从这些资源按 MJCF/配置的真实引用解析基础依赖闭包,未绑定且未被引用的素材不进入发布版本。目录不含 robot.json 时提示补充,不能冒充已完成配置。ZIP 继续作为可选导入。
|
||||
Generated
+74
-1
@@ -13,13 +13,15 @@
|
||||
"dayjs": "^1.11.13",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.28.0"
|
||||
"react-router-dom": "^6.28.0",
|
||||
"three": "^0.180.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.64.1",
|
||||
"@types/node": "^22.10.1",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/three": "^0.180.0",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^6.0.3"
|
||||
@@ -423,6 +425,13 @@
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/@dimforge/rapier3d-compat": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
|
||||
"integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@emotion/hash": {
|
||||
"version": "0.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@emotion/hash/-/hash-0.8.0.tgz",
|
||||
@@ -1450,6 +1459,13 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@tweenjs/tween.js": {
|
||||
"version": "23.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
|
||||
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/babel__core": {
|
||||
"version": "7.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
||||
@@ -1541,6 +1557,36 @@
|
||||
"@types/react": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/stats.js": {
|
||||
"version": "0.17.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
|
||||
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/three": {
|
||||
"version": "0.180.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/three/-/three-0.180.0.tgz",
|
||||
"integrity": "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dimforge/rapier3d-compat": "~0.12.0",
|
||||
"@tweenjs/tween.js": "~23.1.3",
|
||||
"@types/stats.js": "*",
|
||||
"@types/webxr": "*",
|
||||
"@webgpu/types": "*",
|
||||
"fflate": "~0.8.2",
|
||||
"meshoptimizer": "~0.22.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/webxr": {
|
||||
"version": "0.5.24",
|
||||
"resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
|
||||
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@vitejs/plugin-react": {
|
||||
"version": "4.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.4.tgz",
|
||||
@@ -1561,6 +1607,13 @@
|
||||
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@webgpu/types": {
|
||||
"version": "0.1.74",
|
||||
"resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.74.tgz",
|
||||
"integrity": "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/antd": {
|
||||
"version": "5.22.2",
|
||||
"resolved": "https://registry.npmjs.org/antd/-/antd-5.22.2.tgz",
|
||||
@@ -1812,6 +1865,13 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
@@ -1900,6 +1960,13 @@
|
||||
"yallist": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/meshoptimizer": {
|
||||
"version": "0.22.0",
|
||||
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz",
|
||||
"integrity": "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
@@ -2783,6 +2850,12 @@
|
||||
"integrity": "sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/three": {
|
||||
"version": "0.180.0",
|
||||
"resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz",
|
||||
"integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/throttle-debounce": {
|
||||
"version": "5.0.2",
|
||||
"resolved": "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-5.0.2.tgz",
|
||||
|
||||
+3
-1
@@ -21,13 +21,15 @@
|
||||
"dayjs": "^1.11.13",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.28.0"
|
||||
"react-router-dom": "^6.28.0",
|
||||
"three": "^0.180.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.64.1",
|
||||
"@types/node": "^22.10.1",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/three": "^0.180.0",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^6.0.3"
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,333 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"id": "microban",
|
||||
"name": "Microban",
|
||||
"family": "microban",
|
||||
"adapter": "generic",
|
||||
"model": "model.xml",
|
||||
"assets": [
|
||||
{
|
||||
"path": "assets/hip_dbl_block__configuration_right.stl",
|
||||
"vfs": "assets/hip_dbl_block__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/ankle_dbl_block__configuration_right.stl",
|
||||
"vfs": "assets/ankle_dbl_block__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/arm_bearing_support__configuration_right.stl",
|
||||
"vfs": "assets/arm_bearing_support__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/dc15_a01_idle_cap_dummy.stl",
|
||||
"vfs": "assets/dc15_a01_idle_cap_dummy.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/head__configuration_right.stl",
|
||||
"vfs": "assets/head__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/shoulder.stl",
|
||||
"vfs": "assets/shoulder.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/xl330_without_horn.stl",
|
||||
"vfs": "assets/xl330_without_horn.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/humerus.stl",
|
||||
"vfs": "assets/humerus.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/pelvis__configuration_right.stl",
|
||||
"vfs": "assets/pelvis__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/dc15_a01_horn_idle2_dummy.stl",
|
||||
"vfs": "assets/dc15_a01_horn_idle2_dummy.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/spacer__configuration_right.stl",
|
||||
"vfs": "assets/spacer__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/battery.stl",
|
||||
"vfs": "assets/battery.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/tibia__configuration_right.stl",
|
||||
"vfs": "assets/tibia__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/tibia__configuration_left.stl",
|
||||
"vfs": "assets/tibia__configuration_left.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/bts2_m2_6x8.stl",
|
||||
"vfs": "assets/bts2_m2_6x8.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/radius.stl",
|
||||
"vfs": "assets/radius.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/xl330.stl",
|
||||
"vfs": "assets/xl330.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/hip__configuration_right.stl",
|
||||
"vfs": "assets/hip__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/femur__configuration_left.stl",
|
||||
"vfs": "assets/femur__configuration_left.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/femur__configuration_right.stl",
|
||||
"vfs": "assets/femur__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/switch.stl",
|
||||
"vfs": "assets/switch.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/hip_dbl_block__configuration_left.stl",
|
||||
"vfs": "assets/hip_dbl_block__configuration_left.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/chest__configuration_right.stl",
|
||||
"vfs": "assets/chest__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/foot__configuration_right.stl",
|
||||
"vfs": "assets/foot__configuration_right.stl"
|
||||
},
|
||||
{
|
||||
"path": "assets/trunk_top__configuration_right.stl",
|
||||
"vfs": "assets/trunk_top__configuration_right.stl"
|
||||
}
|
||||
],
|
||||
"base": {
|
||||
"type": "floating",
|
||||
"root_body": "trunk",
|
||||
"freejoint": "trunk_freejoint",
|
||||
"spawn": {
|
||||
"pos": [
|
||||
0,
|
||||
0,
|
||||
0.165
|
||||
],
|
||||
"yaw": 0
|
||||
},
|
||||
"initial": {
|
||||
"head": 0,
|
||||
"right_shoulder_pitch": 0.17453292519943295,
|
||||
"right_shoulder_roll": -0.17453292519943295,
|
||||
"right_elbow": -0.3490658503988659,
|
||||
"right_hip_yaw": 0,
|
||||
"right_hip_roll": -0.08726646259971647,
|
||||
"right_hip_pitch": -0.17453292519943295,
|
||||
"right_knee": 0,
|
||||
"right_ankle_pitch": 0,
|
||||
"right_ankle_roll": 0.08726646259971647,
|
||||
"left_shoulder_pitch": 0.17453292519943295,
|
||||
"left_shoulder_roll": 0.17453292519943295,
|
||||
"left_elbow": -0.3490658503988659,
|
||||
"left_hip_yaw": 0,
|
||||
"left_hip_roll": 0.08726646259971647,
|
||||
"left_hip_pitch": -0.17453292519943295,
|
||||
"left_knee": 0,
|
||||
"left_ankle_pitch": 0,
|
||||
"left_ankle_roll": -0.08726646259971647
|
||||
}
|
||||
},
|
||||
"sim": {
|
||||
"timestep": 0.005,
|
||||
"decimation": 4
|
||||
},
|
||||
"joints": {
|
||||
"groups": {
|
||||
"policy": [
|
||||
"right_shoulder_pitch",
|
||||
"right_shoulder_roll",
|
||||
"right_elbow",
|
||||
"right_hip_yaw",
|
||||
"right_hip_roll",
|
||||
"right_hip_pitch",
|
||||
"right_knee",
|
||||
"right_ankle_pitch",
|
||||
"right_ankle_roll",
|
||||
"left_shoulder_pitch",
|
||||
"left_shoulder_roll",
|
||||
"left_elbow",
|
||||
"left_hip_yaw",
|
||||
"left_hip_roll",
|
||||
"left_hip_pitch",
|
||||
"left_knee",
|
||||
"left_ankle_pitch",
|
||||
"left_ankle_roll"
|
||||
],
|
||||
"head": [
|
||||
"head"
|
||||
]
|
||||
},
|
||||
"defaults": {
|
||||
"head": 0
|
||||
},
|
||||
"source": "onnx_metadata"
|
||||
},
|
||||
"observations": {
|
||||
"obs": {
|
||||
"terms": [
|
||||
{
|
||||
"type": "gyro",
|
||||
"sensor": "angular-velocity"
|
||||
},
|
||||
{
|
||||
"type": "projected_gravity",
|
||||
"body": "trunk"
|
||||
},
|
||||
{
|
||||
"type": "joint_pos_rel",
|
||||
"group": "policy"
|
||||
},
|
||||
{
|
||||
"type": "joint_vel",
|
||||
"group": "policy"
|
||||
},
|
||||
{
|
||||
"type": "last_action",
|
||||
"group": "policy"
|
||||
},
|
||||
{
|
||||
"type": "command",
|
||||
"size": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"type": "joint_position",
|
||||
"group": "policy",
|
||||
"scale": 1,
|
||||
"offset": "default"
|
||||
}
|
||||
],
|
||||
"actuation": {
|
||||
"type": "joint_pd",
|
||||
"kp": 0.3,
|
||||
"kd": 0.02,
|
||||
"torque_limit": 0.65
|
||||
},
|
||||
"commands": {
|
||||
"size": 3,
|
||||
"limits": [
|
||||
0.15,
|
||||
-0.1,
|
||||
0.6
|
||||
]
|
||||
},
|
||||
"skills": [
|
||||
{
|
||||
"id": "walk",
|
||||
"kind": "primary",
|
||||
"owns": "policy",
|
||||
"controller": {
|
||||
"type": "onnx",
|
||||
"policy": "policies/walk.onnx"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "head",
|
||||
"kind": "overlay",
|
||||
"owns": "head",
|
||||
"controller": {
|
||||
"type": "oscillator",
|
||||
"frequency": 0.35,
|
||||
"amplitude": 0.7853981633974483,
|
||||
"blend": 0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
"input": {
|
||||
"bindings": [
|
||||
{
|
||||
"action": "move_forward",
|
||||
"codes": [
|
||||
"ArrowUp",
|
||||
"KeyW"
|
||||
],
|
||||
"label": "Forward"
|
||||
},
|
||||
{
|
||||
"action": "move_backward",
|
||||
"codes": [
|
||||
"ArrowDown",
|
||||
"KeyS"
|
||||
],
|
||||
"label": "Backward"
|
||||
},
|
||||
{
|
||||
"action": "turn_left",
|
||||
"codes": [
|
||||
"ArrowLeft",
|
||||
"KeyA"
|
||||
],
|
||||
"label": "Turn left"
|
||||
},
|
||||
{
|
||||
"action": "turn_right",
|
||||
"codes": [
|
||||
"ArrowRight",
|
||||
"KeyD"
|
||||
],
|
||||
"label": "Turn right"
|
||||
},
|
||||
{
|
||||
"action": "reset",
|
||||
"codes": [
|
||||
"Space"
|
||||
],
|
||||
"label": "Reset"
|
||||
},
|
||||
{
|
||||
"action": "pause",
|
||||
"codes": [
|
||||
"Escape"
|
||||
],
|
||||
"label": "Pause / continue"
|
||||
},
|
||||
{
|
||||
"action": "toggle:head",
|
||||
"codes": [
|
||||
"KeyH"
|
||||
],
|
||||
"label": "Toggle head rotation"
|
||||
},
|
||||
{
|
||||
"action": "chaseToggle",
|
||||
"codes": ["KeyC"],
|
||||
"label": "Restore chase camera"
|
||||
}
|
||||
]
|
||||
},
|
||||
"render": {
|
||||
"source": "mjcf_visual",
|
||||
"groups": [
|
||||
2
|
||||
],
|
||||
"camera": {
|
||||
"distance": 0.8
|
||||
}
|
||||
},
|
||||
"presentation": {
|
||||
"theme": "comic"
|
||||
},
|
||||
"termination": {
|
||||
"tilt_z": -0.5,
|
||||
"min_height": 0.06,
|
||||
"on_fall": "hold"
|
||||
},
|
||||
"license": "See LICENSES/SOURCE-LICENSE.txt and SOURCE.md (file-specific notices apply)"
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import type { UtcDateTime } from './types';
|
||||
|
||||
export type ModelAssetType = 'whole-glb' | 'part-glb' | 'assembly-manifest' | 'parts-zip' | 'assembly-zip' | 'walking-zip';
|
||||
export type ExperienceKind = 'parts' | 'assembly' | 'walking';
|
||||
export type Vector3 = [number, number, number];
|
||||
export type Quaternion = [number, number, number, number];
|
||||
|
||||
export interface ModelAsset {
|
||||
assetId: string;
|
||||
type: ModelAssetType;
|
||||
relativePath: string;
|
||||
bytes: number;
|
||||
sha256: string;
|
||||
status: 'PROCESSING' | 'READY' | 'FAILED';
|
||||
downloadUrl: string | null;
|
||||
metadata?: {
|
||||
meshCount?: number;
|
||||
triangleCount?: number;
|
||||
robotId?: string;
|
||||
runtimeProfile?: string;
|
||||
manifestFiles?: { path: string; bytes: number; sha256: string }[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface ModelAssetPage {
|
||||
items: ModelAsset[];
|
||||
nextCursor: string | null;
|
||||
}
|
||||
|
||||
export interface ExperienceIssue {
|
||||
code: string;
|
||||
message: string;
|
||||
path?: string;
|
||||
partId?: string;
|
||||
stepId?: string;
|
||||
}
|
||||
|
||||
export interface ExperienceReport {
|
||||
status: 'PENDING' | 'PASSED' | 'FAILED';
|
||||
errors: ExperienceIssue[];
|
||||
warnings: ExperienceIssue[];
|
||||
/** 可选的行走逐项报告,必须绑定本次检查的不可变资源。旧报告不推断逐项通过。 */
|
||||
walking?: WalkingInspection;
|
||||
}
|
||||
|
||||
export type WalkingItemState = 'not_checked' | 'found_pending_validation' | 'missing' | 'checking' | 'passed' | 'mismatch' | 'runtime_failed';
|
||||
export type WalkingStageId = 'identify' | 'integrity' | 'compatibility' | 'contract' | 'runtime_support' | 'runtime' | 'review';
|
||||
export interface WalkingRequirement {
|
||||
key: string;
|
||||
label: string;
|
||||
path?: string;
|
||||
category: 'config' | 'model' | 'dependency' | 'policy' | 'render' | 'provenance' | 'adapter';
|
||||
required: boolean;
|
||||
help?: string;
|
||||
preparedBy?: string;
|
||||
/** 引用该文件的动作名称;同路径多个动作共享一份文件。 */
|
||||
skills?: string[];
|
||||
}
|
||||
export interface WalkingCapability {
|
||||
id: string;
|
||||
label: string;
|
||||
controller: string;
|
||||
policyPath?: string;
|
||||
supported?: boolean;
|
||||
message?: string;
|
||||
}
|
||||
export interface WalkingCheckItem {
|
||||
/** 单文件用包内完整路径;依赖组用 meshes/assets/provenance/rollers。 */
|
||||
key: string;
|
||||
path?: string;
|
||||
state: WalkingItemState;
|
||||
message?: string;
|
||||
suggestion?: string;
|
||||
}
|
||||
export interface WalkingInspection {
|
||||
sourceAssetId: string;
|
||||
robotId: string | null;
|
||||
runtimeProfile: string | null;
|
||||
format?: 'legacy-walking-v1' | 'robot-package' | 'walking-transport-v2' | 'unknown';
|
||||
entry?: string;
|
||||
adapter?: string;
|
||||
requirements?: WalkingRequirement[];
|
||||
capabilities?: WalkingCapability[];
|
||||
communityRuntime?: { status: 'supported' | 'pending' | 'unsupported'; message?: string };
|
||||
items: WalkingCheckItem[];
|
||||
stages: { id: WalkingStageId; state: WalkingItemState; message?: string }[];
|
||||
}
|
||||
|
||||
export interface AssemblyPart {
|
||||
id: string;
|
||||
name: string;
|
||||
assetId: string;
|
||||
parentId: string | null;
|
||||
position: Vector3;
|
||||
quaternion: Quaternion;
|
||||
scale: Vector3;
|
||||
installOffset: Vector3;
|
||||
}
|
||||
|
||||
export interface AssemblyStep {
|
||||
id: string;
|
||||
label: string;
|
||||
parts: string[];
|
||||
}
|
||||
|
||||
export interface ExperienceDraftContent {
|
||||
/** 新表单的依赖版本;随普通整机/装配保存原样携带,避免误清空新行走草稿。 */
|
||||
walkingEditorRevision?: number | null;
|
||||
wholeModel: { assetId: string; displayQuaternion: Quaternion } | null;
|
||||
assembly: {
|
||||
enabled: boolean;
|
||||
title: string;
|
||||
unit: 'meter';
|
||||
referenceAssetId: string | null;
|
||||
displayQuaternion: Quaternion;
|
||||
parts: AssemblyPart[];
|
||||
steps: AssemblyStep[];
|
||||
/** 编辑器分组,不写入公开 manifest;服务端保存后原样返回。 */
|
||||
editorGroups?: { id: string; name: string; parts: string[] }[];
|
||||
} | null;
|
||||
walking: {
|
||||
enabled: boolean;
|
||||
packageAssetId: string;
|
||||
robotId: string;
|
||||
runtimeProfile: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface ExperienceOutputs {
|
||||
glbMainUrl: string | null;
|
||||
glbConfig: { unit: 'meter'; displayQuaternion: Quaternion } | null;
|
||||
assemblyManifestUrl: string | null;
|
||||
walkingManifestUrl: string | null;
|
||||
}
|
||||
|
||||
export interface ExperienceBuild {
|
||||
buildId: string;
|
||||
draftRevision: number;
|
||||
status: 'READY' | 'FAILED';
|
||||
publishable: boolean;
|
||||
publicationMessage: string | null;
|
||||
report: ExperienceReport;
|
||||
outputs: ExperienceOutputs;
|
||||
previewUrls: { wholeModel: string | null; assembly: string | null; walking: string | null };
|
||||
}
|
||||
|
||||
export interface ExperiencePublished extends ExperienceOutputs {
|
||||
releaseId: string;
|
||||
commitSha: string;
|
||||
draftRevision: number;
|
||||
experienceBuildId: string | null;
|
||||
publishedAt: UtcDateTime;
|
||||
}
|
||||
|
||||
export interface ExperienceDraftView extends ExperienceDraftContent {
|
||||
projectCode: string;
|
||||
revision: number;
|
||||
report: ExperienceReport | null;
|
||||
latestBuild: ExperienceBuild | null;
|
||||
published: ExperiencePublished | null;
|
||||
}
|
||||
|
||||
export interface ExperienceResult {
|
||||
assets: ModelAsset[];
|
||||
draftCandidate: ExperienceDraftContent | null;
|
||||
build: ExperienceBuild | null;
|
||||
report: ExperienceReport | null;
|
||||
}
|
||||
|
||||
export interface ExperienceOperation extends ExperienceResult {
|
||||
jobId: string | null;
|
||||
}
|
||||
|
||||
export interface ExperienceJob {
|
||||
jobId: string;
|
||||
status: 'QUEUED' | 'RUNNING' | 'SUCCEEDED' | 'FAILED';
|
||||
phase: string;
|
||||
message: string | null;
|
||||
report: ExperienceReport | null;
|
||||
result: ExperienceResult | null;
|
||||
}
|
||||
|
||||
export interface ModelUploadSignature {
|
||||
batchCode: string;
|
||||
uploadUrl: string;
|
||||
expiresAt: UtcDateTime;
|
||||
files: { relativePath: string; objectKey: string; formFields: Record<string, string> }[];
|
||||
}
|
||||
|
||||
export interface ExperiencePublicationInput {
|
||||
experienceBuildId: string;
|
||||
expectedDraftRevision: number;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { queryString, requestAdmin } from './request';
|
||||
import type {
|
||||
ExperienceDraftContent, ExperienceDraftView, ExperienceJob, ExperienceKind,
|
||||
ExperienceOperation, ModelAssetPage, ModelAssetType, ModelUploadSignature,
|
||||
} from './experience-types';
|
||||
import type { SelectedFile } from './types';
|
||||
|
||||
const root = (code: string) => `/projects/${encodeURIComponent(code)}`;
|
||||
|
||||
export const getExperienceDraft = (code: string, signal?: AbortSignal) =>
|
||||
requestAdmin<ExperienceDraftView>(`${root(code)}/experience-draft`, { signal });
|
||||
|
||||
export const saveExperienceDraft = (code: string, expectedRevision: number, draft: ExperienceDraftContent) =>
|
||||
requestAdmin<ExperienceDraftView>(`${root(code)}/experience-draft`, {
|
||||
method: 'PUT', body: { expectedRevision, ...draft },
|
||||
});
|
||||
|
||||
export const listModelAssets = (code: string, query: { type?: ModelAssetType; cursor?: string } = {}, signal?: AbortSignal) =>
|
||||
requestAdmin<ModelAssetPage>(`${root(code)}/model-assets${queryString({ ...query })}`, { signal });
|
||||
|
||||
export const signModelAssets = (code: string, type: ModelAssetType, selected: SelectedFile[]) =>
|
||||
requestAdmin<ModelUploadSignature>(`${root(code)}/model-assets/signature`, {
|
||||
method: 'POST', body: {
|
||||
type, files: selected.map(({ file, relativePath }) => ({ relativePath, sizeBytes: file.size })),
|
||||
},
|
||||
});
|
||||
|
||||
export const completeModelAssets = (code: string, batchCode: string) =>
|
||||
requestAdmin<ExperienceOperation>(`${root(code)}/model-assets/complete`, {
|
||||
method: 'POST', body: { batchCode },
|
||||
});
|
||||
|
||||
export const importExperience = (code: string, input: {
|
||||
sourceAssetId: string;
|
||||
kind: ExperienceKind;
|
||||
expectedRevision: number;
|
||||
assetBindings?: { path: string; assetId: string }[];
|
||||
}) => requestAdmin<ExperienceOperation>(`${root(code)}/experience-imports`, { method: 'POST', body: input });
|
||||
|
||||
export const getExperienceJob = (code: string, jobId: string, signal?: AbortSignal) =>
|
||||
requestAdmin<ExperienceJob>(`${root(code)}/experience-jobs/${encodeURIComponent(jobId)}`, { signal });
|
||||
|
||||
export const buildExperience = (code: string, draftRevision: number) =>
|
||||
requestAdmin<ExperienceOperation>(`${root(code)}/experience-builds`, {
|
||||
method: 'POST', body: { draftRevision },
|
||||
});
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
import { downloadAdmin, queryString, requestAdmin, requestAdminUpload, setToken, uploadOssFile } from './request';
|
||||
import { compressCoverImage } from '@/utils/compressImage';
|
||||
import type { ExperiencePublicationInput } from './experience-types';
|
||||
import type {
|
||||
AdminView,
|
||||
CommitInput,
|
||||
@@ -112,10 +113,10 @@ export const updateProject = (code: string, project: ProjectUpdateInput) =>
|
||||
export const deleteProject = (code: string) =>
|
||||
requestAdmin<null>(`/projects/${enc(code)}`, { method: 'DELETE' });
|
||||
|
||||
export const publishProject = (code: string, commitSha: string) =>
|
||||
export const publishProject = (code: string, commitSha: string, experience?: ExperiencePublicationInput) =>
|
||||
requestAdmin<ProjectView>(`/projects/${enc(code)}/publication`, {
|
||||
method: 'PUT',
|
||||
body: { commitSha },
|
||||
body: { commitSha, ...experience },
|
||||
});
|
||||
export const unpublishProject = (code: string) =>
|
||||
requestAdmin<null>(`/projects/${enc(code)}/publication`, { method: 'DELETE' });
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { ProjectView, SelectedFile } from './types';
|
||||
import { requestAdmin } from './request';
|
||||
import { clearProjectResource, resourceProblems, uploadProjectResource, type ResourceBatch } from './project-resources';
|
||||
import { safeExperienceUrl } from '@/utils/modelAssets';
|
||||
|
||||
export type PartChange = { kind: 'upload'; selected: SelectedFile } | { kind: 'delete'; path: string };
|
||||
export interface PartChangeJob {
|
||||
project: ProjectView;
|
||||
change: PartChange;
|
||||
retained: Map<string, SelectedFile>;
|
||||
selected?: SelectedFile[];
|
||||
batch?: ResourceBatch;
|
||||
confirming?: boolean;
|
||||
}
|
||||
export class PartsChangedError extends Error {}
|
||||
const identity = (project: ProjectView) => JSON.stringify([
|
||||
project.modelPartsBaseUrl ?? null,
|
||||
[...(project.modelPartsFiles ?? [])].sort((a, b) => a.relativePath.localeCompare(b.relativePath)).map(f => [f.relativePath, f.sizeBytes, f.url]),
|
||||
]);
|
||||
const readProject = async (code: string, signal: AbortSignal) => (await requestAdmin<{ project: ProjectView }>(`/projects/${encodeURIComponent(code)}`, { signal })).project;
|
||||
|
||||
/** 当前协议是整批绑定:读取原文件并合并,不把仅一个新增文件误当完整清单提交。 */
|
||||
export async function changeProjectPart(job: PartChangeJob, signal: AbortSignal, progress: (text: string) => void): Promise<ProjectView> {
|
||||
const { project, change } = job, code = project.projectCode;
|
||||
const assertUnchanged = async () => {
|
||||
const latest = await readProject(code, signal);
|
||||
if (identity(latest) !== identity(project)) throw new PartsChangedError('零件列表已发生变化,请刷新资源绑定后重新操作。');
|
||||
};
|
||||
if (project.modelPartsBaseUrl && !project.modelPartsFiles?.length) throw new PartsChangedError('未取得完整零件清单,请刷新资源绑定后重试。');
|
||||
if (change.kind === 'upload') {
|
||||
const problems = resourceProblems('model-parts', [change.selected]);
|
||||
if (problems.length) throw new Error(problems.join(';'));
|
||||
} else if (!project.modelPartsFiles?.some(f => f.relativePath === change.path)) {
|
||||
throw new PartsChangedError('该零件已不在当前列表中,请刷新资源绑定。');
|
||||
}
|
||||
progress('正在核对当前零件列表…');
|
||||
await assertUnchanged();
|
||||
const target = change.kind === 'upload' ? change.selected.relativePath : change.path;
|
||||
const retained = (project.modelPartsFiles ?? []).filter(f => f.relativePath !== target);
|
||||
if (!retained.length && change.kind === 'delete') {
|
||||
job.confirming = true;
|
||||
await clearProjectResource(code, 'model-parts', signal);
|
||||
const updated = await readProject(code, signal);
|
||||
job.confirming = false;
|
||||
return updated;
|
||||
}
|
||||
if (!job.selected) {
|
||||
let cursor = 0, stopped = false;
|
||||
const pending = retained.filter(f => !job.retained.has(f.relativePath));
|
||||
progress(`正在保留其他零件 ${job.retained.size} / ${retained.length}…`);
|
||||
const results = await Promise.allSettled(Array.from({ length: Math.min(4, pending.length) }, async () => {
|
||||
while (!stopped && cursor < pending.length) {
|
||||
const item = pending[cursor++];
|
||||
try {
|
||||
const url = safeExperienceUrl(item.url);
|
||||
if (!url) throw new Error('下载地址无效');
|
||||
const response = await fetch(url, { signal, credentials: 'omit' });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const blob = await response.blob();
|
||||
if (blob.size !== item.sizeBytes) throw new Error('文件大小与绑定记录不一致');
|
||||
job.retained.set(item.relativePath, { relativePath: item.relativePath, file: new File([blob], item.relativePath.split('/').pop()!, { type: 'model/gltf-binary' }) });
|
||||
progress(`正在保留其他零件 ${job.retained.size} / ${retained.length}…`);
|
||||
} catch (cause) { stopped = true; throw new Error(`无法保留零件 ${item.relativePath}:${cause instanceof Error ? cause.message : String(cause)}。原绑定未修改。`); }
|
||||
}
|
||||
}));
|
||||
signal.throwIfAborted();
|
||||
const failed = results.find((r): r is PromiseRejectedResult => r.status === 'rejected');
|
||||
if (failed) throw failed.reason;
|
||||
job.selected = retained.map(f => job.retained.get(f.relativePath)!);
|
||||
if (change.kind === 'upload') job.selected.push(change.selected);
|
||||
}
|
||||
progress('正在保存零件列表…');
|
||||
const updated = await uploadProjectResource(code, 'model-parts', job.selected, job.batch, signal,
|
||||
batch => { job.batch = batch; },
|
||||
(done, total) => progress(`正在保存零件 ${done} / ${total},完成后更新列表`),
|
||||
async () => { await assertUnchanged(); job.confirming = true; });
|
||||
job.confirming = false;
|
||||
return updated;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { requestAdmin, uploadOssFile } from './request';
|
||||
import type { ProjectView, SelectedFile } from './types';
|
||||
import { validatePath } from '@/components/project/pickFiles';
|
||||
import { errorText, parseServerTime } from '@/utils/format';
|
||||
export type ResourceType = 'model-glb' | 'model-parts' | 'assembly-json' | 'walking-resources';
|
||||
export interface ResourceFileView { relativePath: string; sizeBytes: number; url: string }
|
||||
export interface ResourceSignature { batchCode: string; uploadUrl: string; expiresAt: string; files: { relativePath: string; objectKey: string; formFields: Record<string, string> }[] }
|
||||
export interface ResourceBatch { selected: SelectedFile[]; signature: ResourceSignature; uploaded: Set<string>; uncertain?: boolean }
|
||||
const endpoint = (code: string, type: ResourceType) => `/projects/${encodeURIComponent(code)}/resources/${type}`;
|
||||
export const clearProjectResource = (code: string, type: ResourceType, signal?: AbortSignal) => requestAdmin<null>(endpoint(code, type), { method: 'DELETE', signal });
|
||||
export function resourceProblems(type: ResourceType, selected: SelectedFile[]) {
|
||||
const errors: string[] = [];
|
||||
if (!selected.length) errors.push('请选择资源文件');
|
||||
if ((type === 'model-glb' || type === 'assembly-json') && selected.length !== 1) errors.push('此类资源只能选择一个文件');
|
||||
const paths = new Set<string>();
|
||||
for (const item of selected) {
|
||||
const problem = validatePath(item.relativePath); if (problem) errors.push(`${item.relativePath}:${problem}`);
|
||||
if (paths.has(item.relativePath)) errors.push(`重复路径:${item.relativePath}`); paths.add(item.relativePath);
|
||||
if ((type === 'model-glb' || type === 'model-parts') && !/\.glb$/i.test(item.relativePath)) errors.push('模型文件需要 .glb 扩展名');
|
||||
if (type === 'assembly-json' && !/\.json$/i.test(item.relativePath)) errors.push('步骤文件需要 .json 扩展名');
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
export async function uploadProjectResource(code: string, type: ResourceType, selected: SelectedFile[], previous: ResourceBatch | undefined, signal: AbortSignal, cache: (batch: ResourceBatch) => void, progress: (done: number, total: number) => void, beforeConfirm?: () => Promise<void>) {
|
||||
const problems = resourceProblems(type, selected); if (problems.length) throw new Error(problems.join(';'));
|
||||
const files = selected.map(({ file, relativePath }) => ({ relativePath, sizeBytes: file.size }));
|
||||
let batch = previous;
|
||||
if (!batch || batch.uncertain || batch.selected.length !== selected.length || batch.selected.some((s, i) => s.file !== selected[i].file || s.relativePath !== selected[i].relativePath) || parseServerTime(batch.signature.expiresAt).getTime() <= Date.now()) {
|
||||
const signature = await requestAdmin<ResourceSignature>(`${endpoint(code, type)}/signature`, { method: 'POST', body: { files }, signal }).catch(cause => { throw new Error(`获取上传签名失败:${errorText(cause)}`); });
|
||||
if (signature.files.length !== files.length || new Set(signature.files.map(f => f.relativePath)).size !== files.length || files.some(f => !signature.files.some(s => s.relativePath === f.relativePath))) throw new Error('签名文件清单与所选文件不一致,未开始上传');
|
||||
batch = { selected, signature, uploaded: new Set() }; cache(batch);
|
||||
}
|
||||
const current = batch, pending = current.signature.files.filter(f => !current.uploaded.has(f.relativePath));
|
||||
let cursor = 0, stopped = false;
|
||||
const outcomes = await Promise.allSettled(Array.from({ length: Math.min(4, pending.length) }, async () => {
|
||||
while (!stopped && cursor < pending.length) {
|
||||
const signed = pending[cursor++];
|
||||
try {
|
||||
await uploadOssFile(current.signature.uploadUrl, signed.formFields, selected.find(f => f.relativePath === signed.relativePath)!.file, signal);
|
||||
current.uploaded.add(signed.relativePath); progress(current.uploaded.size, files.length);
|
||||
} catch (error) { stopped = true; if (error instanceof TypeError || signal.aborted) current.uncertain = true; throw new Error(`OSS 上传失败(${signed.relativePath},${new URL(current.signature.uploadUrl).origin}):${error instanceof Error ? error.message : errorText(error)}`); }
|
||||
}
|
||||
}));
|
||||
signal.throwIfAborted();
|
||||
const failed = outcomes.find((r): r is PromiseRejectedResult => r.status === 'rejected'); if (failed) throw failed.reason;
|
||||
await beforeConfirm?.();
|
||||
signal.throwIfAborted();
|
||||
return requestAdmin<ProjectView>(endpoint(code, type), { method: 'PUT', body: { batchCode: current.signature.batchCode, files }, signal });
|
||||
}
|
||||
+2
-1
@@ -180,11 +180,12 @@ export async function uploadOssFile(
|
||||
uploadUrl: string,
|
||||
formFields: Record<string, string>,
|
||||
file: File,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const form = new FormData();
|
||||
for (const [key, value] of Object.entries(formFields)) form.append(key, value);
|
||||
form.append('file', file, file.name);
|
||||
const response = await fetch(uploadUrl, { method: 'POST', body: form });
|
||||
const response = await fetch(uploadUrl, { method: 'POST', body: form, signal });
|
||||
if (!response.ok) throw new Error(`OSS 上传失败(${response.status})`);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
/** 无时区后缀时为 Asia/Shanghai;兼容部分接口返回带 Z/偏移的 ISO 时间。 */
|
||||
export type ShanghaiDateTime = string;
|
||||
|
||||
/** 兼容资源模块沿用的时间类型名称;具体时区仍按接口返回值解析。 */
|
||||
export type UtcDateTime = ShanghaiDateTime;
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
code: string;
|
||||
message: string;
|
||||
@@ -68,6 +71,16 @@ export interface ProjectView {
|
||||
stepMainUrl?: string | null;
|
||||
stepFileName?: string | null;
|
||||
stepSizeBytes?: number | null;
|
||||
modelGlbUrl?: string | null;
|
||||
modelPartsBaseUrl?: string | null;
|
||||
modelPartsFiles?: import('./project-resources').ResourceFileView[];
|
||||
assemblyJsonUrl?: string | null;
|
||||
walkingResourcesBaseUrl?: string | null;
|
||||
walkingResourcesFiles?: import('./project-resources').ResourceFileView[];
|
||||
glbMainUrl?: string | null;
|
||||
glbConfig?: { unit: 'meter'; displayQuaternion: [number, number, number, number] } | null;
|
||||
assemblyManifestUrl?: string | null;
|
||||
walkingManifestUrl?: string | null;
|
||||
projectType: string;
|
||||
owner: { userCode: string | null; nickname: string };
|
||||
repoStatus: RepoStatus;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { ExperienceBuild, ExperienceDraftView } from './experience-types';
|
||||
|
||||
export type WalkingFeatureId = 'walk' | 'head' | 'sit_stand' | 'roll' | 'kick_left' | 'kick_right' | 'recovery' | 'ground_pick' | 'rollers' | 'roller_crouch' | 'visual_model';
|
||||
export type WalkingResourceKind = 'config' | 'mjcf' | 'dependency' | 'policy' | 'glb' | 'mapping' | 'extra' | 'archive';
|
||||
export interface WalkingResource {
|
||||
clientId?: string;
|
||||
resourceId: string;
|
||||
relativePath: string;
|
||||
originalPath: string;
|
||||
bytes: number;
|
||||
sha256: string;
|
||||
kind: WalkingResourceKind;
|
||||
status: 'PROCESSING' | 'READY' | 'FAILED';
|
||||
message?: string;
|
||||
}
|
||||
export interface WalkingFeatureBinding {
|
||||
enabled: boolean;
|
||||
skillIds: string[];
|
||||
configResource: string | null;
|
||||
policyResources: string[];
|
||||
modelResource: string | null;
|
||||
dependencyResources: string[];
|
||||
mappingResource: string | null;
|
||||
autoTrigger: boolean;
|
||||
}
|
||||
export interface WalkingPropBinding { presetId: string; version: string; visualResource: string | null }
|
||||
/** resource 字段在请求中只允许服务器 resourceId,客户端临时 key 不得提交。 */
|
||||
export interface WalkingFormDraft {
|
||||
enabled: boolean;
|
||||
entryResource: string | null;
|
||||
modelResource: string | null;
|
||||
dependencyResources: string[];
|
||||
walkPolicyResource: string | null;
|
||||
walkSkillId: string | null;
|
||||
features: Record<string, WalkingFeatureBinding>;
|
||||
football: WalkingPropBinding | null;
|
||||
pickupTarget: (WalkingPropBinding & { kind: 'football' | 'pickup_target' }) | null;
|
||||
/** 上传的所有草稿素材,包括未用于发布的文件。 */
|
||||
resourceIds: string[];
|
||||
}
|
||||
export interface WalkingPropPreset {
|
||||
id: string; version: string; label: string; kind: 'football' | 'pickup_target';
|
||||
parameters: Record<string, string | number | boolean>;
|
||||
}
|
||||
export interface WalkingSkill { id: string; kind: string; controller: string; policy?: string; owns?: string }
|
||||
export type WalkingCheckStatus = 'PENDING' | 'PASSED' | 'FAILED' | 'UNSUPPORTED' | 'NOT_RUN';
|
||||
export interface WalkingScopedCheck {
|
||||
capabilityId: string;
|
||||
status: WalkingCheckStatus;
|
||||
message: string;
|
||||
issues: { scope: 'base' | 'feature'; capabilityId: string; code: string; path?: string; message: string }[];
|
||||
}
|
||||
export interface WalkingFormCheck {
|
||||
checkId: string;
|
||||
draftRevision: number;
|
||||
sourceVersion: string;
|
||||
/** 通过必须代表实际运行器检查已完成,而非目录存在。 */
|
||||
base: WalkingScopedCheck;
|
||||
features: WalkingScopedCheck[];
|
||||
communityRuntime: 'supported' | 'pending' | 'unsupported';
|
||||
}
|
||||
export interface WalkingEditorBuild {
|
||||
draftRevision: number; sourceVersion: string; checkId: string; capabilityIds: WalkingFeatureId[];
|
||||
experienceBuild: ExperienceBuild;
|
||||
}
|
||||
export interface WalkingEditorView {
|
||||
apiVersion: 1;
|
||||
revision: number;
|
||||
experienceDraftRevision: number;
|
||||
sourceVersion: string;
|
||||
draft: WalkingFormDraft;
|
||||
resources: WalkingResource[];
|
||||
skills: WalkingSkill[];
|
||||
presets: WalkingPropPreset[];
|
||||
featureSupport: { capabilityId: WalkingFeatureId; supported: boolean; message: string }[];
|
||||
check: WalkingFormCheck | null;
|
||||
latestBuild: WalkingEditorBuild | null;
|
||||
/** 写草稿/构建后返回新的全项目草稿,以更新全项目的乐观锁。 */
|
||||
experienceDraft: ExperienceDraftView | null;
|
||||
}
|
||||
export interface WalkingEditorOperation {
|
||||
jobId: string | null;
|
||||
view: WalkingEditorView | null;
|
||||
/** ZIP 仅产生待确认候选,不直接覆盖草稿。 */
|
||||
importCandidate?: WalkingFormDraft | null;
|
||||
}
|
||||
export interface WalkingEditorJob extends WalkingEditorOperation {
|
||||
status: 'QUEUED' | 'RUNNING' | 'SUCCEEDED' | 'FAILED';
|
||||
message: string;
|
||||
}
|
||||
export interface WalkingUploadSignature {
|
||||
batchCode: string; uploadUrl: string; expiresAt: string;
|
||||
files: { clientId: string; relativePath: string; formFields: Record<string, string> }[];
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { requestAdmin } from './request';
|
||||
import type { WalkingEditorJob, WalkingEditorOperation, WalkingEditorView, WalkingFeatureId, WalkingFormDraft, WalkingResource, WalkingResourceKind, WalkingUploadSignature } from './walking-editor-types';
|
||||
const root = (code: string) => `/projects/${encodeURIComponent(code)}/walking-editor`;
|
||||
export const getWalkingEditor = (code: string, signal?: AbortSignal) => requestAdmin<WalkingEditorView>(root(code), { signal });
|
||||
export const saveWalkingEditor = (code: string, revision: number, experienceRevision: number, draft: WalkingFormDraft, signal?: AbortSignal) => requestAdmin<WalkingEditorView>(root(code), { method: 'PUT', body: { expectedRevision: revision, expectedExperienceDraftRevision: experienceRevision, draft }, signal });
|
||||
export const signWalkingResources = (code: string, files: { clientId: string; relativePath: string; originalPath: string; sizeBytes: number; kind: WalkingResourceKind }[], signal?: AbortSignal) => requestAdmin<WalkingUploadSignature>(`${root(code)}/resource-signatures`, { method: 'POST', body: { files }, signal });
|
||||
export const completeWalkingResources = (code: string, batchCode: string, signal?: AbortSignal) => requestAdmin<{ resources: WalkingResource[] }>(`${root(code)}/resource-completions`, { method: 'POST', body: { batchCode }, signal });
|
||||
export const checkWalkingEditor = (code: string, revision: number, experienceRevision: number, signal?: AbortSignal) => requestAdmin<WalkingEditorOperation>(`${root(code)}/checks`, { method: 'POST', body: { expectedRevision: revision, expectedExperienceDraftRevision: experienceRevision }, signal });
|
||||
export const buildWalkingEditor = (code: string, revision: number, experienceRevision: number, checkId: string, capabilityIds: WalkingFeatureId[], signal?: AbortSignal) => requestAdmin<WalkingEditorOperation>(`${root(code)}/builds`, { method: 'POST', body: { expectedRevision: revision, expectedExperienceDraftRevision: experienceRevision, checkId, capabilityIds }, signal });
|
||||
export const importWalkingResources = (code: string, revision: number, resourceId: string, signal?: AbortSignal) => requestAdmin<WalkingEditorOperation>(`${root(code)}/imports`, { method: 'POST', body: { expectedRevision: revision, sourceResourceId: resourceId }, signal });
|
||||
export const getWalkingEditorJob = (code: string, jobId: string, signal?: AbortSignal) => requestAdmin<WalkingEditorJob>(`${root(code)}/jobs/${encodeURIComponent(jobId)}`, { signal });
|
||||
@@ -1,23 +1,26 @@
|
||||
import { Form, Input, Select } from 'antd';
|
||||
import type { ReactNode } from 'react';
|
||||
import type { TypeView } from '@/api/types';
|
||||
import CoverUpload from './CoverUpload';
|
||||
|
||||
/** 项目基础信息字段(name/description/projectType/coverUrl),嵌在外层 Form 中 */
|
||||
export default function ProjectFields({ types }: { types: TypeView[] }) {
|
||||
return (
|
||||
export default function ProjectFields({ types, compact = false, extraFields }: { types: TypeView[]; compact?: boolean; extraFields?: ReactNode }) {
|
||||
const fields = (
|
||||
<>
|
||||
<Form.Item name="name" label="项目名称" rules={[{ required: true, whitespace: true, message: '请输入项目名称' }, { max: 100 }]}>
|
||||
<Form.Item className="project-field-name" name="name" label="项目名称" rules={[{ required: true, whitespace: true, message: '请输入项目名称' }, { max: 100 }]}>
|
||||
<Input maxLength={100} showCount />
|
||||
</Form.Item>
|
||||
<Form.Item name="description" label="项目描述" rules={[{ max: 2000 }]}>
|
||||
<Input.TextArea rows={4} maxLength={2000} showCount />
|
||||
<Form.Item className="project-field-description" name="description" label="项目描述" rules={[{ max: 2000 }]}>
|
||||
<Input.TextArea rows={compact ? 3 : 4} maxLength={2000} showCount />
|
||||
</Form.Item>
|
||||
<Form.Item name="projectType" label="项目类型" rules={[{ required: true, message: '请选择项目类型' }]}>
|
||||
<Select placeholder="请选择" options={types.map((t) => ({ value: t.code, label: t.name }))} style={{ maxWidth: 320 }} />
|
||||
<Form.Item className="project-field-type" name="projectType" label="项目类型" rules={[{ required: true, message: '请选择项目类型' }]}>
|
||||
<Select placeholder="请选择" options={types.map((t) => ({ value: t.code, label: t.name }))} style={{ maxWidth: compact ? undefined : 320 }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="coverUrl" label="封面" extra="JPG / PNG / WEBP,原图最大 5 MiB,上传后自动优化">
|
||||
<Form.Item className="project-field-cover" name="coverUrl" label="封面" extra="JPG / PNG / WEBP,原图最大 5 MiB,上传后自动优化">
|
||||
<CoverUpload />
|
||||
</Form.Item>
|
||||
{extraFields && <div className="project-field-owner">{extraFields}</div>}
|
||||
</>
|
||||
);
|
||||
return compact ? <div className="project-fields-compact">{fields}</div> : fields;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
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 { errorText } from '@/utils/format';
|
||||
import AssemblyViewport from './AssemblyViewport';
|
||||
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 = '保存后自动生成步骤数据。上传、检查并发布后,前台才会更新。' }: {
|
||||
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 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 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 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 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();
|
||||
};
|
||||
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 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 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);
|
||||
} 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>)}
|
||||
</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>
|
||||
</Modal>
|
||||
</Modal>;
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
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 { OrbitControls } from 'three/addons/controls/OrbitControls.js';
|
||||
import { TransformControls } from 'three/addons/controls/TransformControls.js';
|
||||
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
|
||||
import { clone } from 'three/addons/utils/SkeletonUtils.js';
|
||||
import type { AssemblyPart } from '@/api/experience-types';
|
||||
import type { Assembly, AssemblySource } from '@/utils/assemblyEditor';
|
||||
import { safeExperienceUrl } from '@/utils/modelAssets';
|
||||
import { errorText } from '@/utils/format';
|
||||
|
||||
interface Props {
|
||||
assembly: Assembly; sources: AssemblySource[]; reference?: AssemblySource; selected: string[];
|
||||
preview: number | null; replay: number; referenceVisible: boolean; tool: 'select' | 'translate' | 'rotate'; fit: number;
|
||||
onPick: (id: string, additive: boolean) => void;
|
||||
onTransform: (id: string, position: AssemblyPart['position'], quaternion: AssemblyPart['quaternion']) => void;
|
||||
}
|
||||
interface SceneApi {
|
||||
update: (props: Props) => void; fit: () => void;
|
||||
}
|
||||
function disposeObjects(objects: THREE.Object3D[]) {
|
||||
const geometries = new Set<THREE.BufferGeometry>(), materials = new Set<THREE.Material>(), textures = new Set<THREE.Texture>();
|
||||
objects.forEach((o) => o.traverse((child) => {
|
||||
const mesh = child as THREE.Mesh;
|
||||
if (mesh.geometry) geometries.add(mesh.geometry);
|
||||
if (mesh.material) (Array.isArray(mesh.material) ? mesh.material : [mesh.material]).forEach((m) => materials.add(m));
|
||||
}));
|
||||
materials.forEach((m) => Object.values(m).forEach((v) => { if (v instanceof THREE.Texture) textures.add(v); }));
|
||||
textures.forEach((t) => { (t.source?.data as ImageBitmap | undefined)?.close?.(); t.dispose(); });
|
||||
materials.forEach((m) => m.dispose()); geometries.forEach((g) => g.dispose());
|
||||
}
|
||||
|
||||
export default function AssemblyViewport(props: Props) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const latest = useRef(props); latest.current = props;
|
||||
const api = useRef<SceneApi>();
|
||||
const [loading, setLoading] = useState(true), [problem, setProblem] = useState('');
|
||||
const topology = JSON.stringify(props.assembly.parts.map((p) => [p.id, p.assetId, p.parentId]));
|
||||
|
||||
useEffect(() => {
|
||||
const host = container.current!;
|
||||
const abort = new AbortController();
|
||||
let disposed = false, frame = 0, needsRender = true, dragging = false, animating = false, animationStart = 0;
|
||||
let renderer: THREE.WebGLRenderer;
|
||||
setLoading(true); setProblem('');
|
||||
try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false }); }
|
||||
catch { setLoading(false); setProblem('当前浏览器无法开启 3D 预览。请开启硬件加速后重试;零件列表仍可编辑。'); return; }
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||||
renderer.toneMappingExposure = 1.15;
|
||||
renderer.domElement.setAttribute('aria-label', '装配模型三维预览');
|
||||
host.appendChild(renderer.domElement);
|
||||
const scene = new THREE.Scene(); scene.background = new THREE.Color('#f1f4fa');
|
||||
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);
|
||||
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 axes = new THREE.AxesHelper(1); scene.add(axes); axes.visible = false;
|
||||
let axesSize = 0.1;
|
||||
const templates: THREE.Object3D[] = [];
|
||||
const boxes: THREE.BoxHelper[] = [];
|
||||
const transform = new TransformControls(camera, renderer.domElement);
|
||||
const transformHelper = transform.getHelper(); scene.add(transformHelper);
|
||||
transform.addEventListener('change', () => { needsRender = true; });
|
||||
transform.addEventListener('dragging-changed', (event) => { dragging = !!event.value; controls.enabled = !dragging; });
|
||||
transform.addEventListener('mouseUp', () => {
|
||||
const object = transform.object;
|
||||
if (object?.userData.partId) latest.current.onTransform(object.userData.partId, object.position.toArray() as AssemblyPart['position'], object.quaternion.toArray() as AssemblyPart['quaternion']);
|
||||
});
|
||||
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;
|
||||
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));
|
||||
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);
|
||||
}
|
||||
clearBoxes();
|
||||
scene.updateMatrixWorld(true);
|
||||
const active = next.selected.length === 1 ? groups.get(next.selected[0]) : null;
|
||||
axes.visible = !!active && next.preview === null;
|
||||
if (active) {
|
||||
axes.position.copy(active.getWorldPosition(new THREE.Vector3()));
|
||||
axes.quaternion.copy((active.parent ?? display).getWorldQuaternion(new THREE.Quaternion()));
|
||||
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;
|
||||
(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;
|
||||
};
|
||||
const fit = () => {
|
||||
// 使用最终位姿取包围盒;只移动相机,绝不归中、缩放或重写零件的原始变换。
|
||||
const next = latest.current;
|
||||
const preview = next.preview;
|
||||
update({ ...next, preview: null });
|
||||
scene.updateMatrixWorld(true);
|
||||
const box = new THREE.Box3().setFromObject(models);
|
||||
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;
|
||||
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));
|
||||
controls.target.copy(center); camera.updateProjectionMatrix(); controls.update();
|
||||
}
|
||||
update({ ...next, preview });
|
||||
};
|
||||
const resize = () => { const { width, height } = host.getBoundingClientRect(); if (!width || !height) return; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); needsRender = true; };
|
||||
const observer = new ResizeObserver(resize); observer.observe(host); resize();
|
||||
let down: { x: number; y: number; onGizmo: boolean } | null = null;
|
||||
const pointerDown = (e: PointerEvent) => { down = { x: e.clientX, y: e.clientY, onGizmo: transform.axis !== null }; };
|
||||
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();
|
||||
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)) {
|
||||
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; }
|
||||
}
|
||||
};
|
||||
renderer.domElement.addEventListener('pointerdown', pointerDown); renderer.domElement.addEventListener('pointerup', pointerUp);
|
||||
const draw = (time: number) => {
|
||||
frame = requestAnimationFrame(draw);
|
||||
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 ?? []);
|
||||
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);
|
||||
});
|
||||
animating = t < 1; needsRender = true;
|
||||
}
|
||||
if (needsRender) { boxes.forEach((b) => b.update()); renderer.render(scene, camera); needsRender = false; }
|
||||
};
|
||||
frame = requestAnimationFrame(draw);
|
||||
api.current = { update, 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 fetchModel = async (source: AssemblySource) => {
|
||||
let buffer: ArrayBuffer;
|
||||
if (source.file) buffer = await source.file.arrayBuffer();
|
||||
else {
|
||||
const url = safeExperienceUrl(source.asset.downloadUrl); if (!url) throw new Error(`${source.asset.relativePath} 尚无预览地址,请刷新或重新选择原 GLB`);
|
||||
const response = await fetch(url, { signal: abort.signal, credentials: 'omit' });
|
||||
if (!response.ok) throw new Error(`${source.asset.relativePath} 下载失败(${response.status})`);
|
||||
buffer = await response.arrayBuffer();
|
||||
}
|
||||
abort.signal.throwIfAborted();
|
||||
const gltf = await loader.parseAsync(buffer, '');
|
||||
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);
|
||||
});
|
||||
// 层级预先由编辑器校验;额外防止损坏的草稿产生场景环。
|
||||
next.assembly.parts.forEach((p) => {
|
||||
const seen = new Set([p.id]); let parentId = p.parentId, valid = true;
|
||||
while (parentId) { if (seen.has(parentId)) { valid = false; break; } seen.add(parentId); parentId = next.assembly.parts.find((item) => item.id === parentId)?.parentId ?? null; }
|
||||
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(';'));
|
||||
};
|
||||
loadModels().catch((cause) => { if (!disposed) { setLoading(false); setProblem(errorText(cause)); } });
|
||||
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();
|
||||
};
|
||||
}, [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]);
|
||||
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>;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, Modal, Select, Space, Table, Typography } from 'antd';
|
||||
import type { ModelAsset } from '@/api/experience-types';
|
||||
import { formatSize } from '@/utils/format';
|
||||
|
||||
export default function AssetImportDialog({ source, assets, busy, error, onClose, onImport }: {
|
||||
source: ModelAsset | null;
|
||||
assets: ModelAsset[];
|
||||
busy: boolean;
|
||||
error?: string;
|
||||
onClose: () => void;
|
||||
onImport: (source: ModelAsset, bindings?: { path: string; assetId: string }[]) => Promise<void>;
|
||||
}) {
|
||||
const [bindings, setBindings] = useState<Record<string, string>>({});
|
||||
useEffect(() => {
|
||||
const automatic: Record<string, string> = {};
|
||||
for (const file of source?.metadata?.manifestFiles ?? []) {
|
||||
const matches = assets.filter((asset) => asset.status === 'READY' && asset.relativePath === file.path
|
||||
&& asset.bytes === file.bytes && asset.sha256 === file.sha256 && asset.type === 'part-glb');
|
||||
if (matches.length === 1) automatic[file.path] = matches[0].assetId;
|
||||
}
|
||||
setBindings(automatic);
|
||||
}, [source, assets]);
|
||||
const isJson = source?.type === 'assembly-manifest';
|
||||
const files = source?.metadata?.manifestFiles ?? [];
|
||||
const missing = !!isJson && (!files.length || files.some((file) => !bindings[file.path]));
|
||||
return <Modal
|
||||
title="核对步骤文件中的零件" width={840} open={!!source} confirmLoading={busy}
|
||||
okText="确认并读取" cancelText="取消" okButtonProps={{ disabled: missing }}
|
||||
cancelButtonProps={{ disabled: busy }} closable={!busy} maskClosable={!busy}
|
||||
onCancel={() => { if (!busy) onClose(); }}
|
||||
onOk={async () => { if (source) await onImport(source, isJson ? files.map((file) => ({ path: file.path, assetId: bindings[file.path] })) : undefined); }}
|
||||
>
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<Typography.Text>{source?.relativePath}</Typography.Text>
|
||||
<Alert type="info" showIcon message="有些步骤还未找到对应的零件文件,请逐项选择。读取完成后会显示步骤供你确认,不会直接发布。" />
|
||||
{error && <Alert type="error" showIcon message={error} />}
|
||||
{isJson && <>
|
||||
<Typography.Text>步骤文件中的路径需要对应到“零件模型”已上传的 GLB;文件夹不同的同名零件会分开核对。</Typography.Text>
|
||||
{!files.length && <Alert type="warning" showIcon message="暂未读到步骤文件引用的零件清单,请刷新状态后重试。" />}
|
||||
<Table
|
||||
size="small" rowKey="path" dataSource={files} pagination={{ pageSize: 8, showSizeChanger: false }}
|
||||
columns={[
|
||||
{ title: '清单路径', dataIndex: 'path' },
|
||||
{ title: '对应 GLB', render: (_, file) => <Select
|
||||
aria-label={`映射 ${file.path}`} style={{ width: 330 }} placeholder="选择已上传资源" value={bindings[file.path]} disabled={busy}
|
||||
showSearch optionFilterProp="label"
|
||||
options={assets.filter((asset) => asset.status === 'READY' && asset.type === 'part-glb')
|
||||
.map((asset) => ({ value: asset.assetId, label: `${asset.relativePath} · ${formatSize(asset.bytes)} · ${asset.sha256.slice(0, 8)}` }))}
|
||||
onChange={(assetId) => setBindings((previous) => ({ ...previous, [file.path]: assetId }))}
|
||||
/> },
|
||||
]}
|
||||
/>
|
||||
<Typography.Text type="secondary">找不到零件时,先关闭此窗口,在“零件模型”区域选择文件夹补传,再重新读取步骤。整机模型不会作为零件候选。</Typography.Text>
|
||||
</>}
|
||||
</Space>
|
||||
</Modal>;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Button, Collapse, Descriptions, Input, Popconfirm, Select, Space, Switch, Table, Tag, Typography } from 'antd';
|
||||
import type { ExperienceFileSection } from '@/utils/experienceFiles';
|
||||
import type { ExperienceDraftContent, ModelAsset, Quaternion } from '@/api/experience-types';
|
||||
|
||||
const half = Math.SQRT1_2;
|
||||
const rotations: { label: string; value: string; quaternion: Quaternion }[] = [
|
||||
{ label: '保持模型原始方向', value: 'identity', quaternion: [0, 0, 0, 1] },
|
||||
{ label: '绕 X 轴 +90°', value: 'x90', quaternion: [half, 0, 0, half] },
|
||||
{ label: '绕 X 轴 −90°', value: 'x-90', quaternion: [-half, 0, 0, half] },
|
||||
{ label: '绕 Y 轴 +90°', value: 'y90', quaternion: [0, half, 0, half] },
|
||||
{ label: '绕 Y 轴 −90°', value: 'y-90', quaternion: [0, -half, 0, half] },
|
||||
{ label: '绕 Z 轴 +90°', value: 'z90', quaternion: [0, 0, half, half] },
|
||||
{ label: '绕 Z 轴 −90°', value: 'z-90', quaternion: [0, 0, -half, half] },
|
||||
];
|
||||
|
||||
function RotationSelect({ value, disabled, onChange }: { value: Quaternion; disabled: boolean; onChange: (value: Quaternion) => void }) {
|
||||
const selected = rotations.find((rotation) => rotation.quaternion.every((item, index) => Math.abs(item - value[index]) < 1e-8));
|
||||
return <Select
|
||||
aria-label="整机展示方向" style={{ width: 230 }} disabled={disabled} value={selected?.value ?? 'imported'}
|
||||
options={[...rotations.map(({ label, value }) => ({ label, value })), ...(!selected ? [{ label: '保留导入的展示方向', value: 'imported' }] : [])]}
|
||||
onChange={(key) => { const rotation = rotations.find((item) => item.value === key); if (rotation) onChange([...rotation.quaternion]); }}
|
||||
/>;
|
||||
}
|
||||
|
||||
export default function ExperienceDraftForm({ section, value, assets, disabled, onChange }: {
|
||||
section: ExperienceFileSection;
|
||||
value: ExperienceDraftContent;
|
||||
assets: ModelAsset[];
|
||||
disabled: boolean;
|
||||
onChange: (value: ExperienceDraftContent) => void;
|
||||
}) {
|
||||
const current = value.wholeModel;
|
||||
if (section === 'whole') return current ? <Space direction="vertical" className="experience-current" style={{ width: '100%' }}>
|
||||
<Space wrap><Tag color="green">已选用整机</Tag><Typography.Text strong>{assets.find((asset) => asset.assetId === current.assetId)?.relativePath ?? '已上传的整机模型'}</Typography.Text></Space>
|
||||
<Space wrap><span>展示方向</span><RotationSelect value={current.displayQuaternion} disabled={disabled} onChange={(displayQuaternion) => onChange({ ...value, wholeModel: { ...current, displayQuaternion } })} /></Space>
|
||||
<Popconfirm title="移除整机模型?保存并发布后,前台将不再展示这个模型。" onConfirm={() => onChange({ ...value, wholeModel: null })}>
|
||||
<Button danger size="small" disabled={disabled}>移除整机模型</Button>
|
||||
</Popconfirm>
|
||||
</Space> : null;
|
||||
if (section === 'parts') {
|
||||
const parts = assets.filter((asset) => asset.type === 'part-glb');
|
||||
return parts.length ? <div className="experience-current">
|
||||
<Typography.Text strong>已上传零件(当前显示 {parts.length} 个)</Typography.Text>
|
||||
<Table size="small" rowKey="assetId" dataSource={parts} pagination={parts.length > 5 ? { pageSize: 5, showSizeChanger: false } : false}
|
||||
columns={[{ title: '零件文件', dataIndex: 'relativePath' }, { title: '状态', dataIndex: 'status', render: (status) => status === 'READY' ? '可使用' : status === 'FAILED' ? '检查失败' : '检查中' }]} />
|
||||
</div> : null;
|
||||
}
|
||||
if (section === 'assembly') return value.assembly ? <Space direction="vertical" className="experience-current" style={{ width: '100%' }}>
|
||||
<Space wrap><Tag color="green">已添加拼装步骤</Tag><span>{value.assembly.parts.length} 个零件实例 · {value.assembly.steps.length} 步</span></Space>
|
||||
<Space wrap><span>在前台显示 AI 装配</span><Switch aria-label="启用装配入口" disabled={disabled} checked={value.assembly.enabled} onChange={(enabled) => onChange({ ...value, assembly: { ...value.assembly!, enabled } })} /></Space>
|
||||
<Input aria-label="装配标题" addonBefore="演示名称" disabled={disabled} value={value.assembly.title} onChange={(event) => onChange({ ...value, assembly: { ...value.assembly!, title: event.target.value } })} />
|
||||
<Collapse size="small" style={{ width: '100%' }} items={[{ key: 'steps', label: '查看拼装步骤', children: <Table
|
||||
size="small" rowKey="id" dataSource={value.assembly.steps} pagination={{ pageSize: 8, showSizeChanger: false }}
|
||||
locale={{ emptyText: '此文件只展示完整模型,不包含分步动画' }}
|
||||
columns={[
|
||||
{ title: '顺序', width: 60, render: (_, step) => value.assembly!.steps.findIndex((item) => item.id === step.id) + 1 },
|
||||
{ title: '安装说明', dataIndex: 'label' },
|
||||
{ title: '包含零件', dataIndex: 'parts', render: (parts: string[]) => parts.map((id) => value.assembly!.parts.find((part) => part.id === id)?.name || id).join('、') },
|
||||
]}
|
||||
/> }]} />
|
||||
<Popconfirm title="移除拼装步骤?保存并发布后,前台将隐藏 AI 装配入口。" onConfirm={() => onChange({ ...value, assembly: null })}><Button danger size="small" disabled={disabled}>移除拼装步骤</Button></Popconfirm>
|
||||
</Space> : null;
|
||||
return value.walking ? <Space direction="vertical" className="experience-current" style={{ width: '100%' }}>
|
||||
<Space><Tag color="green">已添加行走包</Tag><span>在前台显示行走演示</span><Switch aria-label="启用行走入口" disabled={disabled} checked={value.walking.enabled} onChange={(enabled) => onChange({ ...value, walking: { ...value.walking!, enabled } })} /></Space>
|
||||
<Collapse size="small" style={{ width: '100%' }} items={[{ key: 'walking', label: '查看行走包识别信息', children: <Descriptions column={1} size="small">
|
||||
<Descriptions.Item label="机器人">{value.walking.robotId}</Descriptions.Item>
|
||||
<Descriptions.Item label="运行器">{value.walking.runtimeProfile}</Descriptions.Item>
|
||||
</Descriptions> }]} />
|
||||
<Popconfirm title="移除行走演示?保存并发布后,前台将隐藏行走入口。" onConfirm={() => onChange({ ...value, walking: null })}><Button danger size="small" disabled={disabled}>移除行走演示</Button></Popconfirm>
|
||||
</Space> : null;
|
||||
}
|
||||
@@ -0,0 +1,599 @@
|
||||
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Card, Collapse, Descriptions, Modal, Popconfirm, Space, Steps, Table, Tag, Typography } from 'antd';
|
||||
import * as api from '@/api/experiences';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import type {
|
||||
ExperienceBuild, ExperienceDraftContent, ExperienceDraftView, ExperienceJob, ExperienceOperation,
|
||||
ExperienceReport as Report, ExperienceResult, ModelAsset, ModelAssetType,
|
||||
} from '@/api/experience-types';
|
||||
import { errorText, formatSize, formatTime, isAbort } from '@/utils/format';
|
||||
import { emptyExperienceDraft, modelAssetLabels, safeExperienceUrl, uploadModelFiles, type ModelUploadBatch } from '@/utils/modelAssets';
|
||||
import ModelAssetUpload from './ModelAssetUpload';
|
||||
import ExperienceDraftForm from './ExperienceDraftForm';
|
||||
import ExperienceReport from './ExperienceReport';
|
||||
import AssetImportDialog from './AssetImportDialog';
|
||||
import { emptyExperienceFiles, experienceFileSections, peekExperienceFiles, releaseExperienceFiles, type ExperienceFileSection } from '@/utils/experienceFiles';
|
||||
import { bindAssemblySession, peekAssemblySession, pendingAssemblyFiles, prepareAssemblySession, releaseAssemblySession, stageAssemblyFiles, type AssemblySession } from '@/utils/assemblyEditor';
|
||||
import WalkingWorkbench from './WalkingWorkbench';
|
||||
|
||||
const AssemblyEditor = lazy(() => import('./AssemblyEditor'));
|
||||
|
||||
type ResultIntent = { operation: 'upload'; type: ModelAssetType; section: ExperienceFileSection }
|
||||
| { operation: 'import'; section: 'assembly' | 'walking' } | { operation: 'build' };
|
||||
|
||||
const content = ({ wholeModel, assembly, walking, walkingEditorRevision }: ExperienceDraftContent): ExperienceDraftContent => ({ wholeModel, assembly, walking, ...(walkingEditorRevision !== undefined ? { walkingEditorRevision } : {}) });
|
||||
const running = (job: ExperienceJob | null) => job?.status === 'QUEUED' || job?.status === 'RUNNING';
|
||||
const wait = (signal: AbortSignal) => new Promise<void>((resolve, reject) => {
|
||||
if (signal.aborted) return reject(new DOMException('Aborted', 'AbortError'));
|
||||
const timer = setTimeout(() => { signal.removeEventListener('abort', abort); resolve(); }, 3000);
|
||||
const abort = () => { clearTimeout(timer); reject(new DOMException('Aborted', 'AbortError')); };
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
});
|
||||
|
||||
function ResourceLink({ url, children }: { url: string | null | undefined; children: React.ReactNode }) {
|
||||
const href = safeExperienceUrl(url);
|
||||
return href ? <a href={href} target="_blank" rel="noreferrer">{children}</a> : <Typography.Text type="secondary">未配置</Typography.Text>;
|
||||
}
|
||||
|
||||
export default function ExperiencePanel({ projectCode, canPublish, disabled = false, refreshKey = 0, onPublish, onProjectRefresh }: {
|
||||
projectCode: string;
|
||||
canPublish: boolean;
|
||||
disabled?: boolean;
|
||||
refreshKey?: number;
|
||||
onPublish: (build: ExperienceBuild) => void;
|
||||
onProjectRefresh?: () => void;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [server, setServer] = useState<ExperienceDraftView | null>(null);
|
||||
const [draft, setDraft] = useState<ExperienceDraftContent>(() => ({ ...emptyExperienceDraft(), assembly: peekAssemblySession(projectCode)?.assembly ?? null }));
|
||||
const [assets, setAssets] = useState<ModelAsset[]>([]);
|
||||
const [cursor, setCursor] = useState<string | null>(null);
|
||||
const [build, setBuild] = useState<ExperienceBuild | null>(null);
|
||||
const [report, setReport] = useState<Report | null>(null);
|
||||
const [dirty, setDirty] = useState(() => !!peekAssemblySession(projectCode));
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [walkingFormPending, setWalkingFormPending] = useState(false), [walkingFormBusy, setWalkingFormBusy] = useState(false);
|
||||
const [unavailable, setUnavailable] = useState(false);
|
||||
const [conflict, setConflict] = useState(false);
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [phase, setPhase] = useState('');
|
||||
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
|
||||
const [job, setJob] = useState<ExperienceJob | null>(null);
|
||||
const [source, setSource] = useState<ModelAsset | null>(null);
|
||||
const [candidate, setCandidate] = useState<{ draft: ExperienceDraftContent; report: Report | null; section: 'assembly' | 'walking' } | null>(null);
|
||||
const [walkingSourceId, setWalkingSourceId] = useState<string | null>(null);
|
||||
const [walkingInspection, setWalkingInspection] = useState<{ sourceAssetId: string; report: Report; file?: File } | null>(null);
|
||||
const walkingSourceRef = useRef<string | null>(null);
|
||||
const uploadedWalkingRef = useRef<{ assetId: string; selected: typeof files.walking.selected } | null>(null);
|
||||
const [files, setFiles] = useState(() => peekExperienceFiles(projectCode) ?? emptyExperienceFiles());
|
||||
const [fromCreate] = useState(() => !!peekExperienceFiles(projectCode));
|
||||
const [editor, setEditor] = useState<AssemblySession | null>(null);
|
||||
const [openingEditor, setOpeningEditor] = useState(false);
|
||||
const [editorPlan, setEditorPlan] = useState<AssemblySession | null>(() => peekAssemblySession(projectCode) ?? null);
|
||||
const editorPlanRef = useRef(editorPlan);
|
||||
const queuedPlanRef = useRef(editorPlan);
|
||||
const busyRef = useRef(false);
|
||||
const mounted = useRef(false);
|
||||
const operationController = useRef<AbortController>();
|
||||
const loadController = useRef<AbortController>();
|
||||
const batches = useRef<Partial<Record<ModelAssetType, ModelUploadBatch>>>({});
|
||||
const jobRef = useRef<ExperienceJob | null>(null);
|
||||
const intentRef = useRef<ResultIntent>({ operation: 'build' });
|
||||
const serverRef = useRef<ExperienceDraftView | null>(null);
|
||||
const assetsRef = useRef<ModelAsset[]>([]);
|
||||
const cursorRef = useRef<string | null>(null);
|
||||
const awaitingInput = useRef(false);
|
||||
|
||||
useEffect(() => { releaseExperienceFiles(projectCode); releaseAssemblySession(projectCode); }, [projectCode]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
loadController.current?.abort();
|
||||
const controller = new AbortController();
|
||||
loadController.current = controller;
|
||||
setLoading(true);
|
||||
try {
|
||||
const view = await api.getExperienceDraft(projectCode, controller.signal);
|
||||
const page = await api.listModelAssets(projectCode, {}, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
serverRef.current = view;
|
||||
assetsRef.current = page.items;
|
||||
cursorRef.current = page.nextCursor;
|
||||
setServer(view);
|
||||
const plan = queuedPlanRef.current;
|
||||
const retained = plan ? bindAssemblySession(plan, page.items) : null;
|
||||
queuedPlanRef.current = null;
|
||||
editorPlanRef.current = retained; setEditorPlan(retained);
|
||||
setDraft(retained ? { ...content(view), assembly: retained.assembly } : content(view));
|
||||
setAssets(page.items);
|
||||
setCursor(page.nextCursor);
|
||||
setBuild(view.latestBuild);
|
||||
setReport(view.report);
|
||||
walkingSourceRef.current = view.walking?.packageAssetId ?? null;
|
||||
setWalkingSourceId(walkingSourceRef.current);
|
||||
const walkingReport = view.report?.walking ? view.report : view.latestBuild?.draftRevision === view.revision && view.latestBuild.report.walking ? view.latestBuild.report : view.report;
|
||||
setWalkingInspection(walkingReport && walkingSourceRef.current ? { sourceAssetId: walkingSourceRef.current, report: walkingReport } : null);
|
||||
setDirty(!!retained);
|
||||
setUnavailable(false);
|
||||
setConflict(false);
|
||||
setUncertain(false);
|
||||
setError('');
|
||||
} catch (cause) {
|
||||
if (controller.signal.aborted || isAbort(cause)) return;
|
||||
const unsupported = cause instanceof AdminApiError && [404, 405, 501].includes(cause.status);
|
||||
setUnavailable(unsupported);
|
||||
setError(unsupported ? '模型上传服务尚未接入。可以先分别选好整机、零件和演示文件,服务接入后再点击上传。' : errorText(cause));
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}
|
||||
}, [projectCode]);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
load();
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
operationController.current?.abort();
|
||||
loadController.current?.abort();
|
||||
};
|
||||
}, [load, refreshKey]);
|
||||
|
||||
const refreshAssets = async (signal: AbortSignal, nextCursor?: string) => {
|
||||
const page = await api.listModelAssets(projectCode, { cursor: nextCursor }, signal);
|
||||
signal.throwIfAborted();
|
||||
const next = nextCursor ? [...new Map([...assetsRef.current, ...page.items].map((asset) => [asset.assetId, asset])).values()] : page.items;
|
||||
assetsRef.current = next;
|
||||
setAssets(next);
|
||||
setCursor(page.nextCursor);
|
||||
cursorRef.current = page.nextCursor;
|
||||
if (editorPlanRef.current) {
|
||||
const plan = bindAssemblySession(editorPlanRef.current, next);
|
||||
editorPlanRef.current = plan;
|
||||
setEditorPlan(plan);
|
||||
setDraft((previous) => previous.assembly ? { ...previous, assembly: { ...previous.assembly, parts: plan.assembly.parts } } : previous);
|
||||
}
|
||||
};
|
||||
|
||||
const readUploadedPackage = async (asset: ModelAsset, signal: AbortSignal) => {
|
||||
if (!['walking-zip', 'assembly-manifest'].includes(asset.type)) throw new Error('装配步骤仅支持 JSON,请先通过零件文件夹上传模型。');
|
||||
const section = asset.type === 'walking-zip' ? 'walking' : 'assembly';
|
||||
if (section === 'walking') {
|
||||
walkingSourceRef.current = asset.assetId; setWalkingSourceId(asset.assetId); setWalkingInspection(null);
|
||||
}
|
||||
let bindings: { path: string; assetId: string }[] | undefined;
|
||||
if (asset.type === 'assembly-manifest') {
|
||||
const manifestFiles = asset.metadata?.manifestFiles ?? [];
|
||||
const hasAllFiles = () => manifestFiles.every((file) => assetsRef.current.some((item) => item.status === 'READY'
|
||||
&& item.type === 'part-glb' && item.relativePath === file.path && item.bytes === file.bytes && item.sha256 === file.sha256));
|
||||
const visited = new Set<string>();
|
||||
while (!hasAllFiles() && cursorRef.current) {
|
||||
const next = cursorRef.current;
|
||||
if (visited.has(next)) throw new Error('文件列表分页重复,请刷新状态后重试');
|
||||
visited.add(next);
|
||||
setPhase('正在核对已上传的零件文件');
|
||||
await refreshAssets(signal, next);
|
||||
}
|
||||
bindings = manifestFiles.map((file) => {
|
||||
const matches = assetsRef.current.filter((item) => item.status === 'READY' && item.type === 'part-glb'
|
||||
&& item.relativePath === file.path && item.bytes === file.bytes && item.sha256 === file.sha256);
|
||||
return { path: file.path, assetId: matches.length === 1 ? matches[0].assetId : '' };
|
||||
});
|
||||
if (!manifestFiles.length || bindings.some((binding) => !binding.assetId)) {
|
||||
awaitingInput.current = true;
|
||||
setSource(asset);
|
||||
setPhase('请核对步骤文件引用的零件');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!serverRef.current) throw new Error('请先刷新项目状态');
|
||||
setPhase(section === 'walking' ? '正在读取行走演示包' : '正在读取拼装步骤');
|
||||
const operation = await api.importExperience(projectCode, {
|
||||
sourceAssetId: asset.assetId, kind: section, expectedRevision: serverRef.current.revision,
|
||||
...(bindings ? { assetBindings: bindings } : {}),
|
||||
});
|
||||
await processOperation(operation, signal, { operation: 'import', section });
|
||||
};
|
||||
|
||||
const applyResult = async (result: ExperienceResult, signal: AbortSignal, intent: ResultIntent) => {
|
||||
signal.throwIfAborted();
|
||||
setReport(result.report ?? result.build?.report ?? null);
|
||||
if (intent.operation === 'upload' && intent.type === 'walking-zip') {
|
||||
const asset = result.assets.find((item) => item.type === 'walking-zip');
|
||||
if (asset) {
|
||||
walkingSourceRef.current = asset.assetId; setWalkingSourceId(asset.assetId);
|
||||
const selected = batches.current['walking-zip']?.selected;
|
||||
if (selected) uploadedWalkingRef.current = { assetId: asset.assetId, selected };
|
||||
}
|
||||
}
|
||||
const incomingReport = result.report ?? result.build?.report;
|
||||
const reportSource = intent.operation === 'import' && intent.section === 'walking' || intent.operation === 'upload' && intent.type === 'walking-zip'
|
||||
? walkingSourceRef.current : intent.operation === 'build' ? serverRef.current?.walking?.packageAssetId : null;
|
||||
if (incomingReport && reportSource) setWalkingInspection({ sourceAssetId: reportSource, report: incomingReport,
|
||||
file: uploadedWalkingRef.current?.assetId === reportSource ? uploadedWalkingRef.current.selected[0]?.file : undefined });
|
||||
if (result.assets.length) {
|
||||
if (intent.operation === 'upload' && intent.type === 'part-glb' && editorPlanRef.current) {
|
||||
const plan = bindAssemblySession(editorPlanRef.current, result.assets);
|
||||
editorPlanRef.current = plan; setEditorPlan(plan);
|
||||
setDraft((previous) => previous.assembly ? { ...previous, assembly: { ...previous.assembly, parts: plan.assembly.parts } } : previous);
|
||||
}
|
||||
assetsRef.current = [...new Map([...assetsRef.current, ...result.assets].map((asset) => [asset.assetId, asset])).values()];
|
||||
setAssets(assetsRef.current);
|
||||
await refreshAssets(signal);
|
||||
}
|
||||
if (result.build) setBuild(result.build);
|
||||
if (result.report?.status === 'FAILED') throw new Error('资源校验未通过,请查看具体文件、零件或步骤的错误说明');
|
||||
if (intent.operation === 'upload' && intent.type !== 'walking-zip') {
|
||||
const confirmed = batches.current[intent.type]?.selected;
|
||||
if (confirmed) setFiles((previous) => previous[intent.section].selected === confirmed
|
||||
? { ...previous, [intent.section]: emptyExperienceFiles()[intent.section] } : previous);
|
||||
}
|
||||
if (intent.operation === 'upload' && intent.type === 'whole-glb') {
|
||||
const whole = result.assets.find((asset) => asset.type === 'whole-glb' && asset.status === 'READY');
|
||||
if (!whole) throw new Error('整机文件仍在检查中,请刷新状态后再使用');
|
||||
setDraft((previous) => ({ ...previous, wholeModel: { assetId: whole.assetId, displayQuaternion: [0, 0, 0, 1] } }));
|
||||
setDirty(true);
|
||||
setBuild(null);
|
||||
setPhase('整机模型已上传并选用,检查预览后即可发布');
|
||||
return;
|
||||
}
|
||||
if (intent.operation === 'upload' && ['assembly-manifest', 'walking-zip'].includes(intent.type)) {
|
||||
const sourceAsset = result.assets.find((asset) => asset.type === intent.type && asset.status === 'READY');
|
||||
if (!sourceAsset) throw new Error('文件仍在检查中,请刷新状态后再读取');
|
||||
await readUploadedPackage(sourceAsset, signal);
|
||||
return;
|
||||
}
|
||||
if (result.draftCandidate) {
|
||||
awaitingInput.current = true;
|
||||
setCandidate({ draft: result.draftCandidate, report: result.report, section: intent.operation === 'import' ? intent.section : 'assembly' });
|
||||
if (intent.operation === 'import' && intent.section === 'walking' && result.report?.status === 'PASSED') {
|
||||
const uploaded = uploadedWalkingRef.current;
|
||||
if (uploaded && uploaded.assetId === walkingSourceRef.current) setFiles((previous) => previous.walking.selected === uploaded.selected ? { ...previous, walking: emptyExperienceFiles().walking } : previous);
|
||||
}
|
||||
}
|
||||
setPhase(result.draftCandidate ? '文件已读取,请确认使用这份演示内容' : result.build ? '检查完成,请预览后发布到前台'
|
||||
: result.assets.length ? '零件已上传,可以继续添加拼装步骤' : '文件处理完成,请查看检查结果');
|
||||
};
|
||||
|
||||
const watchJob = async (jobId: string, signal: AbortSignal) => {
|
||||
for (;;) {
|
||||
const current = await api.getExperienceJob(projectCode, jobId, signal);
|
||||
signal.throwIfAborted();
|
||||
jobRef.current = current;
|
||||
setJob(current);
|
||||
setPhase(current.message || current.phase);
|
||||
if (current.report) {
|
||||
setReport(current.report);
|
||||
if ((intentRef.current.operation === 'import' && intentRef.current.section === 'walking' || intentRef.current.operation === 'upload' && intentRef.current.type === 'walking-zip') && walkingSourceRef.current) setWalkingInspection({ sourceAssetId: walkingSourceRef.current, report: current.report,
|
||||
file: uploadedWalkingRef.current?.assetId === walkingSourceRef.current ? uploadedWalkingRef.current.selected[0]?.file : undefined });
|
||||
else if (intentRef.current.operation === 'build' && serverRef.current?.walking) setWalkingInspection({ sourceAssetId: serverRef.current.walking.packageAssetId, report: current.report });
|
||||
}
|
||||
if (current.status === 'FAILED') throw new Error(current.message || '服务端处理失败,请检查校验报告');
|
||||
if (current.status === 'SUCCEEDED') {
|
||||
if (!current.result) throw new Error('任务完成但未返回处理结果,请刷新核对');
|
||||
await applyResult(current.result, signal, intentRef.current);
|
||||
return;
|
||||
}
|
||||
await wait(signal);
|
||||
}
|
||||
};
|
||||
|
||||
const processOperation = async (operation: ExperienceOperation, signal: AbortSignal, intent: ResultIntent = { operation: 'build' }) => {
|
||||
signal.throwIfAborted();
|
||||
intentRef.current = intent;
|
||||
if (operation.jobId) {
|
||||
const current: ExperienceJob = { jobId: operation.jobId, status: 'QUEUED', phase: 'QUEUED', message: null, report: null, result: null };
|
||||
jobRef.current = current;
|
||||
setJob(current);
|
||||
await watchJob(operation.jobId, signal);
|
||||
} else {
|
||||
jobRef.current = null;
|
||||
setJob(null);
|
||||
await applyResult(operation, signal, intent);
|
||||
}
|
||||
};
|
||||
|
||||
const perform = async (action: (signal: AbortSignal) => Promise<void>, readOnly = false) => {
|
||||
if (busyRef.current) return false;
|
||||
busyRef.current = true;
|
||||
const controller = new AbortController();
|
||||
operationController.current = controller;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setProgress(null);
|
||||
try {
|
||||
await action(controller.signal);
|
||||
return !controller.signal.aborted;
|
||||
} catch (cause) {
|
||||
if (!mounted.current || controller.signal.aborted || isAbort(cause)) return false;
|
||||
const text = errorText(cause);
|
||||
if (cause instanceof AdminApiError) {
|
||||
const detail = cause.details as { errors?: Report['errors']; warnings?: Report['warnings']; walking?: Report['walking'] } | null;
|
||||
if (detail && Array.isArray(detail.errors)) {
|
||||
const report: Report = { status: 'FAILED', errors: detail.errors, warnings: Array.isArray(detail.warnings) ? detail.warnings : [], ...(detail.walking ? { walking: detail.walking } : {}) };
|
||||
setReport(report);
|
||||
if (detail.walking?.sourceAssetId && detail.walking.sourceAssetId === walkingSourceRef.current) setWalkingInspection({ sourceAssetId: detail.walking.sourceAssetId, report,
|
||||
file: uploadedWalkingRef.current?.assetId === walkingSourceRef.current ? uploadedWalkingRef.current.selected[0]?.file : undefined });
|
||||
}
|
||||
if (cause.status === 409) {
|
||||
setConflict(true);
|
||||
setError(`${text}。本地修改已保留,请核对最新草稿版本后再操作。`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (running(jobRef.current)) {
|
||||
setError(`获取处理状态失败:${text}。可恢复查询,不会重新发起上传或解析。`);
|
||||
} else if (!readOnly && (cause instanceof TypeError || cause instanceof AdminApiError && (cause.status >= 500 || cause.code === 'REMOTE_RESULT_UNKNOWN'))) {
|
||||
setUncertain(true);
|
||||
setError(`${text}。操作结果待核对,请刷新草稿和资源库确认,不会自动重发。`);
|
||||
} else setError(text);
|
||||
return false;
|
||||
} finally {
|
||||
busyRef.current = false;
|
||||
if (mounted.current) setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const changeDraft = (value: ExperienceDraftContent) => {
|
||||
if (editorPlanRef.current) {
|
||||
const plan = value.assembly ? { ...editorPlanRef.current, assembly: value.assembly } : null;
|
||||
editorPlanRef.current = plan; setEditorPlan(plan);
|
||||
}
|
||||
setDraft(value);
|
||||
setDirty(true);
|
||||
setBuild(null);
|
||||
setReport(null);
|
||||
};
|
||||
|
||||
const save = () => perform(async (signal) => {
|
||||
if (!server) return;
|
||||
setPhase('保存草稿');
|
||||
const view = await api.saveExperienceDraft(projectCode, server.revision, draft);
|
||||
signal.throwIfAborted();
|
||||
setServer(view);
|
||||
serverRef.current = view;
|
||||
setDraft(content(view));
|
||||
setBuild(view.latestBuild);
|
||||
setReport(view.report);
|
||||
setDirty(false);
|
||||
setPhase('展示设置已保存,发布后才会更新前台');
|
||||
message.success('展示设置已保存');
|
||||
});
|
||||
|
||||
const uploadSection = (section: ExperienceFileSection) => perform(async (signal) => {
|
||||
const selection = files[section];
|
||||
if (!selection.selected.length || selection.checking || selection.problems.length) return;
|
||||
setPhase(`正在上传${section === 'whole' ? '整机模型' : section === 'parts' ? '零件模型' : section === 'assembly' ? '拼装步骤' : '行走演示'}`);
|
||||
setProgress({ done: 0, total: selection.selected.length });
|
||||
const operation = await uploadModelFiles(projectCode, selection.type, selection.selected, batches.current[selection.type] ?? null, signal,
|
||||
(batch) => { batches.current[selection.type] = batch; }, (done, total) => { if (!signal.aborted) setProgress({ done, total }); });
|
||||
signal.throwIfAborted();
|
||||
setProgress(null);
|
||||
await processOperation(operation, signal, { operation: 'upload', type: selection.type, section });
|
||||
delete batches.current[selection.type];
|
||||
});
|
||||
|
||||
const checkAndPreview = () => perform(async (signal) => {
|
||||
if (editorPlanRef.current && pendingAssemblyFiles(editorPlanRef.current)) throw new Error('请先上传制作流程时选用的零件 GLB,系统会自动关联文件。');
|
||||
if (!serverRef.current) return;
|
||||
let revision = serverRef.current.revision;
|
||||
if (dirty) {
|
||||
setPhase('正在保存展示设置');
|
||||
const view = await api.saveExperienceDraft(projectCode, revision, draft);
|
||||
signal.throwIfAborted();
|
||||
serverRef.current = view;
|
||||
setServer(view);
|
||||
setDraft(content(view));
|
||||
setDirty(false);
|
||||
revision = view.revision;
|
||||
}
|
||||
setPhase('正在检查模型和演示文件');
|
||||
await processOperation(await api.buildExperience(projectCode, revision), signal);
|
||||
if (!signal.aborted) onProjectRefresh?.();
|
||||
});
|
||||
|
||||
const locked = disabled || busy || walkingFormBusy || loading || !server || unavailable || uncertain || conflict || running(job) || awaitingInput.current;
|
||||
const currentBuild = build && server && build.draftRevision === server.revision && !dirty;
|
||||
const publicOutputs = server?.published;
|
||||
const pendingSections = experienceFileSections.filter((section) => files[section].selected.length);
|
||||
const refresh = async () => { await load(); if (mounted.current) onProjectRefresh?.(); };
|
||||
|
||||
const useWhole = (asset: ModelAsset) => changeDraft({ ...draft, wholeModel: { assetId: asset.assetId, displayQuaternion: [0, 0, 0, 1] } });
|
||||
const reusable = (types: ModelAssetType[]) => assets.find((asset) => asset.status === 'READY' && types.includes(asset.type));
|
||||
const previewLink = (section: ExperienceFileSection) => section === 'whole' ? build?.previewUrls.wholeModel : section === 'assembly' ? build?.previewUrls.assembly : section === 'walking' ? build?.previewUrls.walking : null;
|
||||
const walkingAssetId = walkingSourceId ?? draft.walking?.packageAssetId ?? null;
|
||||
const walkingRuntimePending = !!(draft.walking?.enabled && build?.report.walking && ['robot-package', 'walking-transport-v2'].includes(build.report.walking.format ?? '') && build.report.walking.communityRuntime?.status !== 'supported');
|
||||
const identifiedWalking = candidate?.section === 'walking' ? candidate.draft.walking : draft.walking;
|
||||
const pendingParts = !!editorPlan && pendingAssemblyFiles(editorPlan);
|
||||
const openAssemblyEditor = async () => {
|
||||
if (openingEditor || busy) return;
|
||||
setOpeningEditor(true);
|
||||
try {
|
||||
// 加载完整资源列表,避免分页导致原有零件被误判丢失。
|
||||
const visited = new Set<string>();
|
||||
while (cursorRef.current) {
|
||||
const next = cursorRef.current;
|
||||
if (visited.has(next)) throw new Error('资源分页重复,请刷新后重试');
|
||||
visited.add(next);
|
||||
const controller = new AbortController(); loadController.current = controller;
|
||||
await refreshAssets(controller.signal, next);
|
||||
}
|
||||
const session = await prepareAssemblySession(editorPlanRef.current, draft.assembly, assetsRef.current, files, draft.wholeModel?.assetId);
|
||||
if (!session.assembly.parts.length && !session.sources.some((source) => source.asset.type === 'part-glb')) throw new Error('请先在上方“零件模型”选择零件文件夹,再制作装配流程。');
|
||||
if (mounted.current) setEditor(session);
|
||||
} catch (cause) { message.error(errorText(cause)); }
|
||||
finally { if (mounted.current) setOpeningEditor(false); }
|
||||
};
|
||||
|
||||
return <Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
<div className="experience-workspace-heading">
|
||||
<div><h4>上传项目装配与仿真</h4><Typography.Text type="secondary">整机和零件分别添加,装配流程可在模型上直接制作。未配置的内容不会显示在前台。</Typography.Text></div>
|
||||
{dirty ? <Popconfirm title="刷新会丢弃尚未保存的展示设置,确定刷新?" onConfirm={refresh}><Button disabled={busy || walkingFormBusy || loading}>刷新状态</Button></Popconfirm>
|
||||
: <Button loading={loading} disabled={busy || walkingFormBusy} onClick={refresh}>刷新状态</Button>}
|
||||
</div>
|
||||
<Steps size="small" current={build && currentBuild ? 2 : dirty || assets.length ? 1 : 0} items={[{ title: '上传模型文件' }, { title: '检查展示效果' }, { title: '发布到前台' }]} />
|
||||
{error && <Alert type={unavailable ? 'info' : 'error'} showIcon message={error} />}
|
||||
{fromCreate && !!pendingSections.length && <Alert type="info" showIcon message="已保留新建项目时选好的文件。点击下方对应区域上传,也可以一次上传全部已选文件。" />}
|
||||
{!!pendingSections.length && <Space wrap>
|
||||
<Button type="primary" disabled={!!locked || pendingSections.some((section) => files[section].checking || files[section].problems.length > 0)} onClick={async () => {
|
||||
for (const section of pendingSections) {
|
||||
if (!await uploadSection(section)) break;
|
||||
setFiles((previous) => ({ ...previous, [section]: emptyExperienceFiles()[section] }));
|
||||
if (awaitingInput.current) break;
|
||||
}
|
||||
}}>上传全部已选文件</Button>
|
||||
<Typography.Text type="secondary">四个区域独立保存选择,不会因为选择零件而清掉整机文件。文件大小由上传服务检查。</Typography.Text>
|
||||
</Space>}
|
||||
{(phase || progress) && <Alert type="info" showIcon message={<Space wrap><span>{phase}</span>{progress && <span>文件传输 {progress.done} / {progress.total}</span>}{busy && <Tag color="processing">处理中</Tag>}</Space>} />}
|
||||
{running(job) && !busy && <Button onClick={() => perform((signal) => watchJob(job!.jobId, signal), true)}>继续查看处理结果</Button>}
|
||||
{report && (report.status !== 'PASSED' || report.errors.length > 0 || report.warnings.length > 0) && <ExperienceReport report={report} />}
|
||||
|
||||
<ModelAssetUpload
|
||||
value={files} onChange={setFiles} disabled={!!locked || walkingFormBusy} busy={busy || running(job) || openingEditor || walkingFormBusy} onUpload={uploadSection}
|
||||
renderWalking={(legacy) => <WalkingWorkbench projectCode={projectCode} disabled={disabled || busy || loading || conflict || uncertain} legacy={legacy}
|
||||
legacyInitiallyOpen={!!(draft.walking && draft.walkingEditorRevision == null || reusable(['walking-zip']))} onPendingChange={setWalkingFormPending} onBusyChange={setWalkingFormBusy}
|
||||
experienceRevision={() => serverRef.current?.revision ?? 0} canPublish={canPublish && !dirty && !pendingSections.length && !pendingParts}
|
||||
onPublish={onPublish} onSnapshot={(snapshot, built) => {
|
||||
serverRef.current = snapshot; setServer(snapshot);
|
||||
setDraft((previous) => ({ ...previous, walking: snapshot.walking, ...(snapshot.walkingEditorRevision !== undefined ? { walkingEditorRevision: snapshot.walkingEditorRevision } : {}) }));
|
||||
setBuild(built ?? snapshot.latestBuild ?? null); setReport(snapshot.report);
|
||||
}} beforeBuild={async () => {
|
||||
if (pendingSections.length || pendingParts) throw new Error('请先完成上方整机、零件和装配文件的上传。');
|
||||
if (!serverRef.current) throw new Error('项目资源草稿接口尚未接入。');
|
||||
if (dirty) {
|
||||
const current = await api.saveExperienceDraft(projectCode, serverRef.current.revision, draft);
|
||||
serverRef.current = current; setServer(current); setDraft(content(current)); setDirty(false);
|
||||
}
|
||||
return serverRef.current.revision;
|
||||
}} />}
|
||||
hasMoreAssets={!!cursor}
|
||||
onEditAssembly={disabled || loading || conflict || uncertain ? undefined : openAssemblyEditor}
|
||||
walking={{ asset: assets.find((asset) => asset.assetId === walkingAssetId), sourceAssetId: walkingAssetId,
|
||||
report: walkingInspection?.sourceAssetId === walkingAssetId ? walkingInspection.report : null,
|
||||
inspectedFile: walkingInspection?.sourceAssetId === walkingAssetId ? walkingInspection.file : undefined,
|
||||
identity: identifiedWalking ? { sourceAssetId: identifiedWalking.packageAssetId, robotId: identifiedWalking.robotId, runtimeProfile: identifiedWalking.runtimeProfile } : null,
|
||||
serviceUnavailable: unavailable, processing: busy || running(job) }}
|
||||
configured={{ whole: !!draft.wholeModel, parts: assets.some((asset) => asset.type === 'part-glb' && asset.status === 'READY'), assembly: !!draft.assembly, walking: !!draft.walking }}
|
||||
renderCurrent={(section) => <>
|
||||
<ExperienceDraftForm section={section} value={draft} assets={assets} disabled={!!locked} onChange={changeDraft} />
|
||||
{section === 'whole' && !draft.wholeModel && reusable(['whole-glb']) && <Space direction="vertical" className="experience-current">
|
||||
<Typography.Text>{reusable(['whole-glb'])!.relativePath}</Typography.Text>
|
||||
<Button disabled={!!locked} onClick={() => useWhole(reusable(['whole-glb'])!)}>使用已上传的整机</Button>
|
||||
</Space>}
|
||||
{section === 'assembly' && !draft.assembly && reusable(['assembly-manifest']) && <Space direction="vertical" className="experience-current">
|
||||
<Typography.Text>{reusable(['assembly-manifest'])!.relativePath}</Typography.Text>
|
||||
<Button disabled={!!locked} onClick={() => perform((signal) => readUploadedPackage(reusable(['assembly-manifest'])!, signal))}>读取已上传的拼装步骤</Button>
|
||||
</Space>}
|
||||
{section === 'walking' && !draft.walking && reusable(['walking-zip']) && <Space direction="vertical" className="experience-current">
|
||||
<Typography.Text>{reusable(['walking-zip'])!.relativePath}</Typography.Text>
|
||||
<Button disabled={!!locked} onClick={() => perform((signal) => readUploadedPackage(reusable(['walking-zip'])!, signal))}>读取已上传的行走包</Button>
|
||||
</Space>}
|
||||
{currentBuild && previewLink(section) && (section !== 'walking' || !walkingRuntimePending && !files.walking.selected.length && walkingAssetId === draft.walking?.packageAssetId) && <ResourceLink url={previewLink(section)}>预览{section === 'whole' ? '整机模型' : section === 'assembly' ? '拼装过程' : '行走演示'}</ResourceLink>}
|
||||
</>}
|
||||
/>
|
||||
|
||||
<Card size="small" title="检查后发布">
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<Typography.Text type="secondary">文件上传完成后,点击“检查并预览”会自动保存展示设置。预览确认后,再将本项目的装配与仿真发布到前台。</Typography.Text>
|
||||
<div className="experience-publish-actions">
|
||||
<Space wrap>
|
||||
<Button type="primary" disabled={!!locked || walkingFormBusy || walkingFormPending || pendingSections.length > 0 || pendingParts} onClick={checkAndPreview}>检查并预览</Button>
|
||||
<Button disabled={!!locked || !dirty || pendingParts} onClick={save}>保存设置</Button>
|
||||
{build && <Button type="primary" disabled={!!locked || walkingFormBusy || walkingFormPending || walkingRuntimePending || pendingSections.length > 0 || !currentBuild || !canPublish || build.status !== 'READY' || !build.publishable || build.report.status !== 'PASSED' || !!(draft.walking?.enabled && build.report.walking && build.report.walking.sourceAssetId !== draft.walking.packageAssetId)} onClick={() => onPublish(build)}>发布到前台</Button>}
|
||||
</Space>
|
||||
<Tag color={dirty ? 'orange' : build && currentBuild ? 'green' : 'default'}>{dirty ? '有尚未保存的展示设置' : build && currentBuild ? '文件检查完成,尚未发布' : server ? '上传和保存不会立即改变前台' : '等待上传服务接入'}</Tag>
|
||||
</div>
|
||||
{!!pendingSections.length && <Typography.Text type="secondary">还有已选文件尚未上传,请先点击对应区域的上传按钮或“上传全部已选文件”。</Typography.Text>}
|
||||
{pendingParts && <Alert type="info" showIcon message="装配流程已在本页保留。请上传所选零件 GLB,系统会自动关联后再保存;刷新页面前请先上传或导出 JSON。" />}
|
||||
{build?.publicationMessage && <Alert type="warning" showIcon message={build.publicationMessage} />}
|
||||
{build && currentBuild && !Object.values(build.previewUrls).some(Boolean) && <Typography.Text type="secondary">预览链接尚未返回,请接入后确认实际展示效果。</Typography.Text>}
|
||||
{!canPublish && <Typography.Text type="secondary">当前项目暂不能发布,可以先上传并保存模型文件。</Typography.Text>}
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Card size="small" title="前台当前展示状态">
|
||||
<Space size="large" wrap>
|
||||
<span>整机模型 <Tag color={publicOutputs?.glbMainUrl ? 'green' : 'default'}>{publicOutputs?.glbMainUrl ? '已发布' : '未配置'}</Tag></span>
|
||||
<span>AI 装配 <Tag color={publicOutputs?.assemblyManifestUrl ? 'green' : 'default'}>{publicOutputs?.assemblyManifestUrl ? '已发布' : '未配置'}</Tag></span>
|
||||
<span>行走演示 <Tag color={publicOutputs?.walkingManifestUrl ? 'green' : 'default'}>{publicOutputs?.walkingManifestUrl ? '已发布' : '未配置'}</Tag></span>
|
||||
{publicOutputs?.publishedAt && <Typography.Text type="secondary">发布于 {formatTime(publicOutputs.publishedAt)}</Typography.Text>}
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Collapse items={[{ key: 'files', label: `已上传文件与历史版本(当前加载 ${assets.length} 个)`, children: <Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Table<ModelAsset> size="small" rowKey="assetId" dataSource={assets} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 900 }}
|
||||
columns={[
|
||||
{ title: '文件', dataIndex: 'relativePath' },
|
||||
{ title: '用途', dataIndex: 'type', render: (type: ModelAssetType) => modelAssetLabels[type] ?? type },
|
||||
{ title: '大小', dataIndex: 'bytes', render: formatSize },
|
||||
{ title: '检查结果', dataIndex: 'status', render: (status) => status === 'READY' ? '可使用' : status === 'FAILED' ? '检查失败' : '检查中' },
|
||||
{ title: '文件校验值', dataIndex: 'sha256', render: (value: string) => value ? <Typography.Text className="mono" copyable={{ text: value }}>{value.slice(0, 12)}…</Typography.Text> : '—' },
|
||||
{ title: '操作', render: (_, asset) => <Space wrap>
|
||||
{asset.downloadUrl && <ResourceLink url={asset.downloadUrl}>下载原文件</ResourceLink>}
|
||||
{asset.type === 'whole-glb' && <Button type="link" size="small" disabled={!!locked || asset.status !== 'READY'} onClick={() => useWhole(asset)}>使用此整机</Button>}
|
||||
{['assembly-manifest', 'walking-zip'].includes(asset.type) && <Button type="link" size="small" disabled={!!locked || asset.status !== 'READY'} onClick={() => perform((signal) => readUploadedPackage(asset, signal))}>读取此文件</Button>}
|
||||
</Space> },
|
||||
]}
|
||||
/>
|
||||
{cursor && <Button disabled={busy || loading} onClick={() => perform((signal) => refreshAssets(signal, cursor), true)}>加载更多文件</Button>}
|
||||
</Space> }, { key: 'details', label: '查看发布记录和清单(高级)', children: <Descriptions column={1} bordered size="small">
|
||||
<Descriptions.Item label="内部设置版本">{server?.revision ?? '—'}</Descriptions.Item>
|
||||
<Descriptions.Item label="检查版本">{build?.buildId ?? '—'}</Descriptions.Item>
|
||||
<Descriptions.Item label="已发布整机"><ResourceLink url={publicOutputs?.glbMainUrl}>下载已发布整机 GLB</ResourceLink></Descriptions.Item>
|
||||
<Descriptions.Item label="已发布装配清单"><ResourceLink url={publicOutputs?.assemblyManifestUrl}>查看已发布装配清单</ResourceLink></Descriptions.Item>
|
||||
<Descriptions.Item label="已发布行走清单"><ResourceLink url={publicOutputs?.walkingManifestUrl}>查看已发布行走清单</ResourceLink></Descriptions.Item>
|
||||
</Descriptions> }]} />
|
||||
|
||||
<AssetImportDialog source={source} assets={assets} busy={busy} error={error}
|
||||
onClose={() => { awaitingInput.current = false; setSource(null); }} onImport={async (asset, assetBindings) => {
|
||||
await perform(async (signal) => {
|
||||
if (!serverRef.current) return;
|
||||
const section = asset.type === 'walking-zip' ? 'walking' : 'assembly';
|
||||
const operation = await api.importExperience(projectCode, {
|
||||
sourceAssetId: asset.assetId, kind: section, expectedRevision: serverRef.current.revision,
|
||||
...(assetBindings ? { assetBindings } : {}),
|
||||
});
|
||||
signal.throwIfAborted();
|
||||
awaitingInput.current = false;
|
||||
setSource(null);
|
||||
await processOperation(operation, signal, { operation: 'import', section });
|
||||
});
|
||||
}} />
|
||||
|
||||
<Modal title={candidate?.section === 'walking' ? '确认使用行走演示' : '确认使用拼装步骤'} open={!!candidate}
|
||||
okText="确认使用" cancelText="取消" onCancel={() => { awaitingInput.current = false; setCandidate(null); }}
|
||||
okButtonProps={{ disabled: candidate?.report?.status !== 'PASSED' || busy }}
|
||||
onOk={() => {
|
||||
if (!candidate) return;
|
||||
const section = candidate.section;
|
||||
if (section !== 'walking') { editorPlanRef.current = null; setEditorPlan(null); }
|
||||
setDraft((previous) => section === 'walking' ? { ...previous, walking: candidate.draft.walking } : { ...previous, assembly: candidate.draft.assembly });
|
||||
setDirty(true); setBuild(null); setReport(null);
|
||||
awaitingInput.current = false;
|
||||
setCandidate(null);
|
||||
}}
|
||||
>
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Typography.Paragraph>确认后会使用下方内容,并保留已选整机模型和其他演示。检查并发布后才会更新前台。</Typography.Paragraph>
|
||||
<Descriptions column={1} size="small">
|
||||
{candidate?.section === 'walking' ? <>
|
||||
<Descriptions.Item label="机器人">{candidate.draft.walking?.robotId ?? '未识别'}</Descriptions.Item>
|
||||
<Descriptions.Item label="演示配置">{candidate.draft.walking?.runtimeProfile ?? '未识别'}</Descriptions.Item>
|
||||
</> : <>
|
||||
<Descriptions.Item label="零件实例">{candidate?.draft.assembly?.parts.length ?? 0}</Descriptions.Item>
|
||||
<Descriptions.Item label="拼装步骤">{candidate?.draft.assembly?.steps.length ?? 0}</Descriptions.Item>
|
||||
</>}
|
||||
</Descriptions>
|
||||
<ExperienceReport report={candidate?.report} />
|
||||
</Space>
|
||||
</Modal>
|
||||
{editor && <Suspense fallback={<Alert type="info" message="正在打开装配编辑器…" />}><AssemblyEditor initial={editor} onClose={() => setEditor(null)} onSave={(session) => {
|
||||
const plan = bindAssemblySession(session, assetsRef.current);
|
||||
setFiles(stageAssemblyFiles(plan, files));
|
||||
editorPlanRef.current = plan; setEditorPlan(plan);
|
||||
changeDraft({ ...draft, assembly: plan.assembly });
|
||||
setEditor(null);
|
||||
message.success('装配流程已生成,请上传所需文件后检查并发布');
|
||||
}} /></Suspense>}
|
||||
</Space>;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Alert, List, Space, Tag } from 'antd';
|
||||
import type { ExperienceReport as Report } from '@/api/experience-types';
|
||||
|
||||
export default function ExperienceReport({ report }: { report: Report | null | undefined }) {
|
||||
if (!report) return null;
|
||||
const issues = [...(report.errors ?? []).map((item) => ({ ...item, severity: 'error' })),
|
||||
...(report.warnings ?? []).map((item) => ({ ...item, severity: 'warning' }))];
|
||||
return (
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Alert
|
||||
showIcon
|
||||
type={report.status === 'PASSED' ? 'success' : report.status === 'FAILED' ? 'error' : 'info'}
|
||||
message={report.status === 'PASSED' ? '服务端校验通过' : report.status === 'FAILED' ? '服务端校验未通过' : '等待服务端校验'}
|
||||
/>
|
||||
{!!issues.length && <List
|
||||
bordered size="small" dataSource={issues}
|
||||
renderItem={(issue) => <List.Item>
|
||||
<Space wrap>
|
||||
<Tag color={issue.severity === 'error' ? 'red' : 'orange'}>{issue.code}</Tag>
|
||||
<span>{issue.message}</span>
|
||||
{issue.path && <span className="mono">文件:{issue.path}</span>}
|
||||
{issue.partId && <span>零件:{issue.partId}</span>}
|
||||
{issue.stepId && <span>步骤:{issue.stepId}</span>}
|
||||
</Space>
|
||||
</List.Item>}
|
||||
/>}
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useRef, type Dispatch, type ReactNode, type SetStateAction } from 'react';
|
||||
import { Alert, Button, Card, Collapse, Space, Table, Tag, Typography } from 'antd';
|
||||
import { AppstoreOutlined, BuildOutlined, FolderOpenOutlined, PlayCircleOutlined, RobotOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import type { ModelAssetType } from '@/api/experience-types';
|
||||
import type { SelectedFile } from '@/api/types';
|
||||
import { formatSize } from '@/utils/format';
|
||||
import { inspectModelFiles } from '@/utils/modelAssets';
|
||||
import { emptyExperienceFiles, experienceFileSections, type ExperienceFileSection, type ExperienceFileSelections } from '@/utils/experienceFiles';
|
||||
import { pickFiles, toSelected } from '../pickFiles';
|
||||
import './experiences.css';
|
||||
import WalkingUploadGuide, { type WalkingUploadContext } from './WalkingUploadGuide';
|
||||
import { resourceProblems } from '@/api/project-resources';
|
||||
import { walkingProfiles } from '@/utils/walkingUpload';
|
||||
|
||||
const sections = {
|
||||
whole: {
|
||||
title: '整机模型', icon: <RobotOutlined />, number: '01',
|
||||
description: '上传一个完整机器人的 GLB 文件,用来展示整机外观。',
|
||||
hint: '这里放完整模型,下面的“零件模型”放拆分后的文件,两者可以同时上传。',
|
||||
uploadLabel: '上传整机模型',
|
||||
},
|
||||
parts: {
|
||||
title: '零件模型', icon: <AppstoreOutlined />, number: '02',
|
||||
description: '选择存放零件 GLB 的文件夹,统一上传其中的零件模型。',
|
||||
hint: '保留子文件夹路径,仅上传 GLB 文件。下方“制作装配流程”直接使用这里的零件。',
|
||||
uploadLabel: '上传零件文件夹',
|
||||
},
|
||||
assembly: {
|
||||
title: '拼装步骤', icon: <BuildOutlined />, number: '03',
|
||||
description: '在模型上选择零件、设置安装方向和顺序,直接制作可播放的装配流程。',
|
||||
hint: '先在上方“零件模型”选择文件夹,再点击“制作装配流程”。直接选择其中的零件,步骤 JSON 由系统生成。',
|
||||
uploadLabel: '上传并读取拼装步骤',
|
||||
},
|
||||
walking: {
|
||||
title: '机器人运动演示', icon: <PlayCircleOutlined />, number: '04',
|
||||
description: walkingProfiles.defaultDescription,
|
||||
hint: '每个项目使用自己的文件。没有上传行走演示时,前台不显示这个入口。',
|
||||
uploadLabel: '上传并读取行走包',
|
||||
},
|
||||
};
|
||||
|
||||
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 = {} }: {
|
||||
resourceProtocol?: boolean;
|
||||
autoUpload?: boolean;
|
||||
retrySections?: Partial<Record<ExperienceFileSection, boolean>>;
|
||||
value: ExperienceFileSelections;
|
||||
onChange: Dispatch<SetStateAction<ExperienceFileSelections>>;
|
||||
disabled?: boolean;
|
||||
busy?: boolean;
|
||||
onUpload?: (section: ExperienceFileSection) => Promise<boolean>;
|
||||
onEditAssembly?: () => void;
|
||||
renderCurrent?: (section: ExperienceFileSection) => ReactNode;
|
||||
configured?: Partial<Record<ExperienceFileSection, boolean>>;
|
||||
mode?: 'create' | 'manage';
|
||||
walking?: WalkingUploadContext;
|
||||
hasMoreAssets?: boolean;
|
||||
renderWalking?: (legacy: ReactNode) => ReactNode;
|
||||
}) {
|
||||
const requests = useRef<Record<ExperienceFileSection, number>>({ whole: 0, parts: 0, assembly: 0, walking: 0 });
|
||||
const hasParts = hasMoreAssets || !!configured.parts || !!configured.assembly || value.parts.type === 'part-glb' && value.parts.selected.length > 0 && !value.parts.checking && !value.parts.problems.length;
|
||||
|
||||
const choose = async (section: ExperienceFileSection, type: ModelAssetType, directory = false) => {
|
||||
const files = await pickFiles({ directory, multiple: type === 'part-glb', accept: type.includes('glb') ? '.glb' : type.endsWith('zip') ? '.zip' : '.json' });
|
||||
if (!files.length) return;
|
||||
const request = ++requests.current[section];
|
||||
const usable = section === 'parts' ? files.filter((file) => /\.glb$/i.test(file.name) && !file.name.startsWith('._')) : files;
|
||||
const selected = toSelected(usable, false);
|
||||
const ignoredCount = files.length - usable.length;
|
||||
if (!selected.length) {
|
||||
onChange((previous) => ({ ...previous, [section]: { type, selected: [], problems: ['该文件夹中没有可用的 GLB 零件文件,请重新选择零件文件夹。'], checking: false, ignoredCount } }));
|
||||
return;
|
||||
}
|
||||
onChange((previous) => ({ ...previous, [section]: { type, selected, problems: [], checking: true, ignoredCount } }));
|
||||
const result = resourceProtocol ? { problems: resourceProblems(section === 'whole' ? 'model-glb' : section === 'parts' ? 'model-parts' : 'assembly-json', selected) } : await inspectModelFiles(type, selected);
|
||||
if (request === requests.current[section]) onChange((previous) => ({ ...previous, [section]: { type, selected, problems: result.problems, checking: false, ignoredCount } }));
|
||||
};
|
||||
|
||||
const clear = (section: ExperienceFileSection) => {
|
||||
requests.current[section]++;
|
||||
onChange((previous) => ({ ...previous, [section]: emptyExperienceFiles()[section] }));
|
||||
};
|
||||
|
||||
const picker = (section: ExperienceFileSection, type: ModelAssetType, label: string, directory = false) => <Button
|
||||
aria-label={label} icon={directory ? <FolderOpenOutlined /> : <UploadOutlined />}
|
||||
disabled={busy || value[section].checking} onClick={() => choose(section, type, directory)}
|
||||
>{label}</Button>;
|
||||
|
||||
return <div className="experience-upload-grid">
|
||||
{experienceFileSections.map((section) => {
|
||||
const info = sections[section];
|
||||
const selection = value[section];
|
||||
const selectionContent = (!!selection.selected.length || !!selection.problems.length) && <Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
{!!selection.selected.length && <Table<SelectedFile>
|
||||
size="small" rowKey="relativePath" loading={selection.checking} dataSource={selection.selected}
|
||||
pagination={selection.selected.length > 5 ? { pageSize: 5, showSizeChanger: false } : false}
|
||||
columns={[{ title: '已选文件', dataIndex: 'relativePath' }, { title: '大小', width: 100, render: (_, item) => formatSize(item.file.size) }]}
|
||||
/>}
|
||||
{section === 'parts' && !!selection.ignoredCount && <Typography.Text type="secondary">已忽略 {selection.ignoredCount} 个非零件文件,仅使用文件夹中的 GLB。</Typography.Text>}
|
||||
{selection.problems.map((problem) => <Alert key={problem} type="error" showIcon message={problem} />)}
|
||||
<Space wrap>
|
||||
{mode === 'manage' && !!selection.selected.length && (!autoUpload || retrySections[section]) && <Button type="primary" loading={busy || selection.checking}
|
||||
disabled={disabled || selection.checking || !!selection.problems.length}
|
||||
onClick={async () => { if (await onUpload?.(section)) clear(section); }}
|
||||
>{autoUpload ? '重试' : ''}{resourceProtocol && section === 'assembly' ? '上传拼装步骤 JSON' : info.uploadLabel}</Button>}
|
||||
<Button disabled={busy || selection.checking} onClick={() => clear(section)}>清除已选{info.title}文件</Button>
|
||||
</Space>
|
||||
</Space>;
|
||||
|
||||
return <Card key={section} className={`experience-upload-card experience-upload-${section}`} size="small"
|
||||
title={<span className="experience-section-title"><span className="experience-section-icon">{info.icon}</span><span>{info.title}</span><span className="experience-section-number">{info.number}</span></span>}
|
||||
extra={<Tag color={selection.selected.length ? 'blue' : configured[section] ? 'green' : 'default'}>{selection.selected.length ? `已选择 ${selection.selected.length} 个文件` : configured[section] ? '已添加' : '选填'}</Tag>}
|
||||
>
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<Typography.Paragraph className="experience-section-description">{resourceProtocol && section === 'parts' && mode === 'manage' ? '支持文件夹上传,也可在下方搜索、添加或删除单个零件。' : resourceProtocol && section === 'walking' ? '上传当前项目的完整行走资源文件夹,保留全部文件与目录。' : info.description}</Typography.Paragraph>
|
||||
<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>}
|
||||
</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' && <Collapse size="small" items={[{ key: 'import', label: '高级导入(JSON)', children: <Space direction="vertical">
|
||||
<Typography.Text type="secondary">仅导入装配步骤 JSON。引用的零件需先在上方“零件模型”通过文件夹上传。</Typography.Text>
|
||||
{picker(section, 'assembly-manifest', '选择拼装步骤 JSON')}
|
||||
</Space> }]} />}
|
||||
{section !== 'walking' && selectionContent}
|
||||
{(section !== 'walking' || !renderWalking) && renderCurrent?.(section)}
|
||||
</Space>
|
||||
</Card>;
|
||||
})}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useState } from 'react';
|
||||
import { App, AutoComplete, Button, Input, Popconfirm, Space, Table, Typography } from 'antd';
|
||||
import { SearchOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
import type { ResourceFileView } from '@/api/project-resources';
|
||||
import { resourceProblems } from '@/api/project-resources';
|
||||
import type { PartChange } from '@/api/part-resources';
|
||||
import { pickFiles } from '../pickFiles';
|
||||
import { safeExperienceUrl } from '@/utils/modelAssets';
|
||||
import { formatSize } from '@/utils/format';
|
||||
|
||||
export default function PartsResourceList({ files, disabled, onChange }: { files: ResourceFileView[]; disabled?: boolean; onChange: (change: PartChange) => Promise<void> }) {
|
||||
const { modal, message } = App.useApp();
|
||||
const [search, setSearch] = useState(''), [directory, setDirectory] = useState('');
|
||||
const [page, setPage] = useState(1), [pageSize, setPageSize] = useState(5);
|
||||
const [picking, setPicking] = useState(false);
|
||||
const filtered = files.filter(f => f.relativePath.toLocaleLowerCase().includes(search.trim().toLocaleLowerCase()));
|
||||
const directories = [...new Set(files.flatMap(f => f.relativePath.includes('/') ? [f.relativePath.slice(0, f.relativePath.lastIndexOf('/'))] : []))];
|
||||
const choose = async () => {
|
||||
setPicking(true);
|
||||
try {
|
||||
const [file] = await pickFiles({ multiple: false, accept: '.glb' });
|
||||
if (!file) return;
|
||||
const folder = directory.trim().replace(/\/$/, '');
|
||||
const selected = { file, relativePath: folder ? `${folder}/${file.name}` : file.name };
|
||||
const problems = resourceProblems('model-parts', [selected]);
|
||||
if (problems.length) { message.error(problems.join(';')); return; }
|
||||
if (files.some(f => f.relativePath === selected.relativePath)) {
|
||||
modal.confirm({ title: '替换同路径零件?', content: `${selected.relativePath} 已存在,替换后其他零件保持不变。`, okText: '替换并上传', cancelText: '取消', onOk: () => onChange({ kind: 'upload', selected }) });
|
||||
} else await onChange({ kind: 'upload', selected });
|
||||
} finally { setPicking(false); }
|
||||
};
|
||||
return <Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Space wrap>
|
||||
<AutoComplete aria-label="单个零件上传目录" value={directory} onChange={setDirectory} disabled={disabled || picking} options={directories.map(value => ({ value }))} placeholder="上传目录(留空为根目录)" style={{ width: 240, maxWidth: '100%' }} filterOption={(input, option) => String(option?.value).toLowerCase().includes(input.toLowerCase())} />
|
||||
<Button aria-label="上传单个零件" icon={<UploadOutlined />} disabled={disabled || picking} onClick={() => { void choose(); }}>上传单个零件</Button>
|
||||
</Space>
|
||||
<Typography.Text type="secondary">选择 GLB 后自动添加,保留其他零件。同路径文件需确认替换。</Typography.Text>
|
||||
<Input aria-label="搜索零件" placeholder="搜索零件名称或目录" prefix={<SearchOutlined />} allowClear value={search} onChange={event => { setSearch(event.target.value); setPage(1); }} />
|
||||
<Typography.Text type="secondary">{search.trim() ? `匹配 ${filtered.length} / 共 ${files.length} 个零件` : `共 ${files.length} 个零件`}</Typography.Text>
|
||||
<Table<ResourceFileView> size="small" rowKey="relativePath" dataSource={filtered}
|
||||
locale={{ emptyText: search.trim() ? '没有匹配的零件' : '尚未上传零件' }}
|
||||
pagination={{ current: Math.min(page, Math.max(1, Math.ceil(filtered.length / pageSize))), pageSize, onChange: (next, size) => { setPage(size === pageSize ? next : 1); setPageSize(size); } }}
|
||||
columns={[
|
||||
{ title: '当前文件', render: (_, row) => safeExperienceUrl(row.url) ? <a style={{ overflowWrap: 'anywhere' }} href={row.url} target="_blank" rel="noreferrer">{row.relativePath}</a> : row.relativePath },
|
||||
{ title: '大小', width: 90, render: (_, row) => formatSize(row.sizeBytes) },
|
||||
{ title: '操作', width: 64, render: (_, row) => <Popconfirm title="删除这个零件?" description={<>仅从当前零件列表移除“{row.relativePath}”,其他零件保留。若装配步骤引用了它,请同步调整步骤。</>} okText="删除零件" cancelText="取消" onConfirm={() => onChange({ kind: 'delete', path: row.relativePath })}><Button type="link" danger size="small" aria-label={`删除零件 ${row.relativePath}`} disabled={disabled || picking}>删除</Button></Popconfirm> },
|
||||
]} />
|
||||
</Space>;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Popconfirm, Space, Table, Typography } from 'antd';
|
||||
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 { peekWalkingSession, releaseWalkingSession } from '@/utils/walkingForm';
|
||||
import { safeExperienceUrl } from '@/utils/modelAssets';
|
||||
import { errorText, formatSize, isAbort } from '@/utils/format';
|
||||
import ModelAssetUpload from './ModelAssetUpload';
|
||||
import WalkingFolderUpload from './WalkingFolderUpload';
|
||||
import PartsResourceList from './PartsResourceList';
|
||||
import { changeProjectPart, PartsChangedError, type PartChange, type PartChangeJob } from '@/api/part-resources';
|
||||
const AssemblyEditor = lazy(() => import('./AssemblyEditor'));
|
||||
const resourceTypes: Record<ExperienceFileSection, ResourceType> = { whole: 'model-glb', parts: 'model-parts', assembly: 'assembly-json', walking: 'walking-resources' };
|
||||
const binding = (project: ProjectView, section: ExperienceFileSection) => section === 'whole' ? project.modelGlbUrl : section === 'parts' ? project.modelPartsBaseUrl : section === 'assembly' ? project.assemblyJsonUrl : project.walkingResourcesBaseUrl;
|
||||
export default function ProjectResourcesPanel({ project, disabled, onUpdate }: { project: ProjectView; disabled?: boolean; onUpdate: (project: ProjectView) => void }) {
|
||||
const code = project.projectCode;
|
||||
const { message } = App.useApp();
|
||||
const [files, setFiles] = useState(() => {
|
||||
const pending = peekExperienceFiles(code) ?? emptyExperienceFiles();
|
||||
const walking = peekWalkingSession(code)?.resources.filter(r => r.file).map(r => ({ file: r.file!, relativePath: r.relativePath }));
|
||||
return walking?.length ? { ...pending, walking: { ...pending.walking, selected: walking, problems: [] } } : pending;
|
||||
});
|
||||
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 [busy, setBusy] = useState(false), [error, setError] = useState(''), [progress, setProgress] = useState('');
|
||||
const [uncertain, setUncertain] = useState(false);
|
||||
const partJob = useRef<PartChangeJob>();
|
||||
const [partRetry, setPartRetry] = useState(false);
|
||||
const attempted = useRef<Partial<Record<ExperienceFileSection, SelectedFile[]>>>({});
|
||||
const [failedSections, setFailedSections] = useState<Partial<Record<ExperienceFileSection, boolean>>>({});
|
||||
const batches = useRef<Partial<Record<ResourceType, ResourceBatch>>>({});
|
||||
const controller = useRef<AbortController>(), running = useRef(false);
|
||||
useEffect(() => { releaseExperienceFiles(code); releaseAssemblySession(code); releaseWalkingSession(code); return () => controller.current?.abort(); }, [code]);
|
||||
const perform = async (fn: (signal: AbortSignal) => Promise<void>) => {
|
||||
if (running.current) return false;
|
||||
running.current = true; setBusy(true); setError(''); const abort = new AbortController(); controller.current = abort;
|
||||
try { await fn(abort.signal); return true; }
|
||||
catch (cause) { if (!abort.signal.aborted && !isAbort(cause)) setError(errorText(cause)); return false; }
|
||||
finally { if (!abort.signal.aborted) { setBusy(false); setProgress(''); } running.current = false; }
|
||||
};
|
||||
const upload = async (section: ExperienceFileSection) => {
|
||||
const selected = files[section].selected;
|
||||
attempted.current[section] = selected;
|
||||
setFailedSections(old => ({ ...old, [section]: false }));
|
||||
const success = await perform(async signal => {
|
||||
const type = resourceTypes[section];
|
||||
setProgress(`正在准备上传 ${selected.length} 个文件…`);
|
||||
try {
|
||||
const updated = await uploadProjectResource(code, type, selected, batches.current[type], signal, b => { batches.current[type] = b; }, (done, total) => setProgress(`已上传 ${done} / ${total},全部成功后确认绑定`));
|
||||
signal.throwIfAborted(); onUpdate(updated); delete batches.current[type];
|
||||
if (section === 'assembly' && selected[0]?.file !== generatedAssembly.current) setPlan(null);
|
||||
if (section === 'parts' && plan && selected.some(item => !plan.sources.some(source => source.file === item.file))) setPlan(null);
|
||||
message.success('上传并绑定成功,社区详情使用新资源,无需重新发布');
|
||||
} catch (cause) {
|
||||
// 确认请求可能已到达后端;无论错误类型,都先让用户核对当前绑定。
|
||||
const batch = batches.current[type];
|
||||
if (batch && batch.uploaded.size === batch.selected.length) setUncertain(true);
|
||||
throw cause;
|
||||
}
|
||||
});
|
||||
if (success) setFiles(old => old[section].selected === selected ? { ...old, [section]: { ...old[section], selected: [] } } : old);
|
||||
else if (!controller.current?.signal.aborted) setFailedSections(old => ({ ...old, [section]: true }));
|
||||
return success;
|
||||
};
|
||||
useEffect(() => {
|
||||
if (busy || running.current || uncertain || partRetry || disabled || project.repoStatus !== 'READY') return;
|
||||
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 changePart = async (change?: PartChange) => {
|
||||
if (running.current || disabled || uncertain || project.repoStatus !== 'READY') return;
|
||||
if (change) partJob.current = { project, change, retained: new Map() };
|
||||
const job = partJob.current;
|
||||
if (!job) return;
|
||||
setPartRetry(false);
|
||||
const success = await perform(async signal => {
|
||||
try {
|
||||
const updated = await changeProjectPart(job, signal, setProgress);
|
||||
signal.throwIfAborted(); onUpdate(updated); setPlan(null); delete batches.current['model-parts'];
|
||||
message.success(job.change.kind === 'delete' ? '零件已删除,其他零件已保留' : '零件已上传,其他零件已保留');
|
||||
} catch (cause) {
|
||||
if (job.confirming || cause instanceof PartsChangedError) setUncertain(true);
|
||||
throw cause;
|
||||
}
|
||||
});
|
||||
if (success) partJob.current = undefined;
|
||||
else if (!controller.current?.signal.aborted) setPartRetry(true);
|
||||
};
|
||||
const remove = (section: ExperienceFileSection) => perform(async signal => {
|
||||
try {
|
||||
await clearProjectResource(code, resourceTypes[section], signal);
|
||||
const next = await getProject(code); signal.throwIfAborted(); onUpdate(next.project);
|
||||
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 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>}
|
||||
<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>}
|
||||
{section !== 'parts' && !!list?.length && <Table size="small" rowKey="relativePath" dataSource={list} pagination={{ pageSize: 5, showTotal: total => `共 ${total} 个文件` }} columns={[{ title: '当前文件', render: (_, row) => safeExperienceUrl(row.url) ? <a href={row.url} target="_blank" rel="noreferrer">{row.relativePath}</a> : row.relativePath }, { title: '大小', render: (_, row) => formatSize(row.sizeBytes) }]} />}
|
||||
<Popconfirm title="清除后社区详情将立即停用这类资源,确认清除?" onConfirm={() => remove(section)}><Button danger disabled={busy || uncertain || partRetry || disabled}>清除当前绑定</Button></Popconfirm></>}
|
||||
</Space>;
|
||||
};
|
||||
return <Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
<Alert showIcon type="info" message="选择文件后自动上传并绑定,成功后立即更新社区详情,无需重新发布。" description="替换整类资源时请提供完整文件清单。上传失败保留原绑定,清除绑定不删除 OSS 文件。" />
|
||||
{project.repoStatus !== 'READY' && <Alert type="warning" message="仓库尚未 READY,可先选择文件;仓库就绪后刷新,将自动上传。" />}
|
||||
{error && <Alert type="error" showIcon message={error} />}{progress && <Alert type="info" message={progress} />}
|
||||
{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}
|
||||
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 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,正在自动上传');
|
||||
}} /></Suspense>}
|
||||
</Space>;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useState } from 'react';
|
||||
import { Alert, Button, Empty, Modal, Space, Tag, Typography } from 'antd';
|
||||
import type { WalkingItemState, WalkingRequirement } from '@/api/experience-types';
|
||||
import type { ExperienceFileSelection } from '@/utils/experienceFiles';
|
||||
import { formatSize } from '@/utils/format';
|
||||
import { legacyWalkingSpec, missingWalkingHelp, resolveWalkingResource, walkingFileCheck, walkingStateLabels, type WalkingResourceContext } from '@/utils/walkingUpload';
|
||||
import ExperienceReport from './ExperienceReport';
|
||||
|
||||
const stateInfo = (state: WalkingItemState | undefined) => walkingStateLabels[state ?? 'not_checked'] ?? walkingStateLabels.not_checked;
|
||||
const genericStages = [{ id: 'identify', label: '文件与配置识别' }, { id: 'integrity', label: '引用完整性' }, { id: 'contract', label: '控制契约' }, { id: 'runtime_support', label: '运行器支持' }, { id: 'runtime', label: '实际试运行' }, { id: 'review', label: '预览确认' }];
|
||||
export default function WalkingChecklist({ selection, serviceUnavailable = false, processing = false, mode = 'manage', ...context }: WalkingResourceContext & {
|
||||
selection: ExperienceFileSelection; serviceUnavailable?: boolean; processing?: boolean; mode?: 'create' | 'manage';
|
||||
}) {
|
||||
const [details, setDetails] = useState(false);
|
||||
const local = selection.selected[0];
|
||||
const { newFile, scopedReport, inspection, robotId, profile, legacy, formatLabel, requirements } = resolveWalkingResource(context, local?.file);
|
||||
const policies = requirements.filter((r) => r.category === 'policy');
|
||||
const dependencies = requirements.filter((r) => r.category === 'dependency');
|
||||
const compactDependencies = dependencies.length > 4;
|
||||
const policyStates = policies.map((file) => walkingFileCheck(scopedReport, context.sourceAssetId, file.key, file.path)?.state);
|
||||
const foundPolicies = policyStates.filter((state) => state === 'passed' || state === 'found_pending_validation').length;
|
||||
const missingPolicies = policyStates.filter((state) => state === 'missing').length;
|
||||
const requiredKeys = new Set(requirements.flatMap((r) => [r.key, ...(r.path ? [r.path] : [])]));
|
||||
const failures = inspection?.items?.filter((item) => ['missing', 'mismatch', 'runtime_failed'].includes(item.state) && requiredKeys.has(item.path ?? item.key)
|
||||
&& (!legacy || item.key !== 'rollers' && !legacyWalkingSpec.optionalExtension.paths.includes(item.path ?? item.key)))
|
||||
?? requirements.map((file) => walkingFileCheck(scopedReport, context.sourceAssetId, file.key, file.path)).filter((item): item is NonNullable<typeof item> => !!item);
|
||||
const errors = scopedReport?.errors ?? [];
|
||||
const errorPaths = new Set(failures.map((item) => item.path ?? item.key));
|
||||
const repairHints = [
|
||||
...failures.map((item) => ({ key: item.key, path: item.path ?? item.key, message: item.message, suggestion: item.suggestion })),
|
||||
...errors.filter((issue) => issue.path && !errorPaths.has(issue.path)).map((issue) => ({ key: issue.path!, path: issue.path!, message: issue.message, suggestion: undefined })),
|
||||
];
|
||||
const phase = (id: string) => inspection?.stages?.find((stage) => stage.id === id);
|
||||
const runtime = inspection?.communityRuntime;
|
||||
const packagePending = !legacy && ['robot-package', 'walking-transport-v2'].includes(inspection?.format ?? '') && runtime?.status !== 'supported';
|
||||
const capabilities = inspection?.capabilities ?? [];
|
||||
const stageList = legacy ? legacyWalkingSpec.validationStages : genericStages;
|
||||
const itemRow = (file: WalkingRequirement) => {
|
||||
const check = walkingFileCheck(scopedReport, context.sourceAssetId, file.key, file.path), state = stateInfo(check?.state);
|
||||
return <div key={file.path ?? file.key} className="walking-check-row" data-check-key={file.key}>
|
||||
<div><strong>{file.label}</strong>{file.path && <Typography.Text className="walking-path" copyable>{file.path}</Typography.Text>}
|
||||
{file.skills?.length ? <div className="walking-check-help">引用动作:{file.skills.join('、')}</div> : null}
|
||||
{check?.message && <div className="walking-check-message">{check.message}</div>}{check?.suggestion && <div className="walking-check-help">{check.suggestion}</div>}
|
||||
</div><Tag color={state.color}>{state.label}</Tag>
|
||||
</div>;
|
||||
};
|
||||
return <section className="walking-checklist" aria-label="行走资源检查结果">
|
||||
<div className="walking-block-heading"><strong>当前包的识别与检查</strong><Tag>按实际报告更新</Tag></div>
|
||||
{!local && !context.sourceAssetId ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="选择资源 ZIP 并上传后,按本包配置显示动作、依赖和检查结果。" /> : <>
|
||||
<div className="walking-package-name"><strong>{local?.relativePath ?? context.asset?.relativePath ?? '已上传的运动资源包'}</strong>{(local || context.asset) && <Typography.Text type="secondary">{formatSize(local?.file.size ?? context.asset!.bytes)}</Typography.Text>}</div>
|
||||
<Typography.Paragraph type="secondary" className="walking-robot">识别机器人:{robotId ?? '尚未识别'}{profile ? ` · ${profile}` : ''}<br />格式:{formatLabel}{inspection?.adapter ? ` · adapter:${inspection.adapter}` : ''}{inspection?.entry ? ` · 入口:${inspection.entry}` : ''}</Typography.Paragraph>
|
||||
{legacy && <Alert type="warning" showIcon message="当前识别的是旧版 Microduck 演示包,下面的七策略要求只适用于这个格式。" />}
|
||||
{newFile && <Alert type="info" showIcon message={mode === 'create' ? '已选择文件,创建项目并上传后检查。尚未检查资源内容。' : serviceUnavailable ? '已选择文件,等待上传服务接入,尚未检查资源内容。' : selection.checking ? '正在检查文件格式,尚未检查包内内容。' : selection.problems.length ? '文件格式检查未通过,请重新选择有效 ZIP。' : '文件格式检查通过,尚未检查包内内容。'} />}
|
||||
{!newFile && !inspection && <Alert type="info" showIcon message={processing ? '资源包处理中,等待服务端返回配置与逐项结果。' : '尚未返回当前包的解析与逐项检查报告,不预设动作或文件要求。'} />}
|
||||
<div className="walking-stage-list">
|
||||
<div className="walking-stage"><span>资源上传</span><Tag color={newFile ? undefined : 'blue'}>{newFile ? '待上传' : '已接收资源'}</Tag></div>
|
||||
{stageList.map((stage) => {
|
||||
const check = phase(stage.id), state = stateInfo(check?.state);
|
||||
const label = !check || check.state === 'not_checked' ? ['runtime', 'review'].includes(stage.id) ? '未执行' : '未检查' : state.label;
|
||||
return <div key={stage.id} className="walking-stage"><span>{stage.label}</span><Tag color={state.color}>{label}</Tag>{check?.message && <small>{check.message}</small>}</div>;
|
||||
})}
|
||||
<div className="walking-stage"><span>社区播放器接入</span><Tag color={runtime?.status === 'supported' ? 'blue' : runtime?.status ? 'orange' : undefined}>{runtime?.status === 'supported' ? '已接入,仍需试运行' : runtime?.status === 'unsupported' ? '需要运行器适配' : packagePending || runtime?.status === 'pending' ? '待接入' : '未确认'}</Tag>{runtime?.message && <small>{runtime.message}</small>}</div>
|
||||
</div>
|
||||
{packagePending && <Alert type="warning" showIcon message="社区播放器尚未接入此包格式,当前可作为待适配资源。" description="文件可上传保存,不代表旧社区已经能够播放。需完成对应包入口与运行器接入后,再进行浏览器试运行和发布验收。" />}
|
||||
{!!capabilities.length && <section className="walking-capabilities" aria-label="本包声明动作"><strong>本包声明动作</strong>{capabilities.map((capability) => <div key={capability.id} className="walking-capability"><Space wrap><span>{capability.label}</span>
|
||||
<Tag color={capability.supported === false ? 'orange' : 'default'}>{capability.supported === false ? '需要运行器适配' : capability.controller === 'oscillator' ? '内置控制器,无需策略文件' : capability.controller === 'onnx' ? '使用声明的 ONNX 策略' : `控制器:${capability.controller}`}</Tag></Space>
|
||||
{capability.policyPath && <Typography.Text className="walking-path" copyable>{capability.policyPath}</Typography.Text>}{capability.message && <small>{capability.message}</small>}
|
||||
</div>)}</section>}
|
||||
{policies.length > 0 && <div className="walking-policy-summary">{legacy ? '旧版 Microduck 专用策略' : '本包声明的策略'}:{policies.length} 个文件,{foundPolicies} 个已确认找到{missingPolicies ? `,${missingPolicies} 项缺失` : ''};未返回结果的仍为未检查。</div>}
|
||||
{requirements.length ? <div className="walking-check-items">{requirements.filter((r) => !compactDependencies || r.category !== 'dependency').map(itemRow)}
|
||||
{compactDependencies && <details className="walking-dependency-details"><summary>模型依赖检查 · {dependencies.length} 项(展开查看逐项结果)</summary>{dependencies.map(itemRow)}</details>}
|
||||
</div> : <Typography.Paragraph type="secondary">等待解析本包配置;不预填其他机器人的策略或依赖。</Typography.Paragraph>}
|
||||
{repairHints.map((item) => {
|
||||
const requirement = requirements.find((r) => r.path === item.path || r.key === item.key);
|
||||
const code = errors.find((error) => error.path === item.path)?.code;
|
||||
return <Alert key={item.key} type="error" showIcon message={item.message || `${item.path}:资源检查未通过`}
|
||||
description={item.suggestion || missingWalkingHelp(item.path, requirement, legacy, code)} />;
|
||||
})}
|
||||
{scopedReport && <Button onClick={() => setDetails(true)}>查看完整检查报告</Button>}
|
||||
</>}
|
||||
<Typography.Paragraph className="walking-check-note" type="secondary">动作声明不等于已经可运行。需检查对应运行器,并实际验证加载、站立、走停、重置及本包声明的动作。</Typography.Paragraph>
|
||||
<Modal title="行走资源完整检查报告" open={details} onCancel={() => setDetails(false)} footer={<Button onClick={() => setDetails(false)}>关闭报告</Button>} width={800}>
|
||||
<ExperienceReport report={scopedReport} />
|
||||
{inspection && <Space direction="vertical" style={{ width: '100%', marginTop: 16 }}>{(inspection.items ?? []).map((item) => <div className="walking-check-row" key={item.key}>
|
||||
<div><Typography.Text className="walking-path" copyable>{item.path ?? item.key}</Typography.Text>{item.message && <p>{item.message}</p>}{item.suggestion && <p>{item.suggestion}</p>}</div><Tag color={stateInfo(item.state).color}>{stateInfo(item.state).label}</Tag>
|
||||
</div>)}</Space>}
|
||||
</Modal>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Alert, Button, Checkbox, Collapse, Input, Select, Space, Switch, Tag, Typography } from 'antd';
|
||||
import type { WalkingFeatureId, WalkingPropPreset, WalkingResourceKind, WalkingSkill } from '@/api/walking-editor-types';
|
||||
import { walkingFeatures, type WalkingLocalSession } from '@/utils/walkingForm';
|
||||
import WalkingFileField from './WalkingFileField';
|
||||
export default function WalkingFeatureForm({ session, presets, skills, support, disabled, onChange, onPick }: {
|
||||
session: WalkingLocalSession; presets: WalkingPropPreset[]; skills: WalkingSkill[]; support: { capabilityId: WalkingFeatureId; supported: boolean; message: string }[]; disabled: boolean;
|
||||
onChange: (update: (session: WalkingLocalSession) => void) => void;
|
||||
onPick: (target: string, kind: WalkingResourceKind, directory?: boolean, feature?: string) => void;
|
||||
}) {
|
||||
const d = session.draft, kicks = d.features.kick_left.enabled || d.features.kick_right.enabled;
|
||||
const updateFeature = (id: string, key: string, value: unknown) => onChange((s) => { Object.assign(s.draft.features[id], { [key]: value }); });
|
||||
const presetPicker = (kind: 'football' | 'pickup_target') => {
|
||||
const current = kind === 'football' ? d.football : d.pickupTarget;
|
||||
const choices = presets.filter((p) => p.kind === kind);
|
||||
return <div className="walking-prop-preset"><strong>{kind === 'football' ? '共享足球物理预设' : '拾取道具物理预设'} · 必选</strong><Typography.Paragraph type="secondary">平台提供标准外观,预设必须与训练场景兼容。需经对应运行器验证;不会因上传外观模型而启用动作。</Typography.Paragraph>
|
||||
<Select aria-label={kind === 'football' ? '足球物理预设' : '拾取物理预设'} disabled={disabled || !choices.length} value={current ? `${current.presetId}@${current.version}` : undefined} placeholder={choices.length ? '选择已提供的固定版本预设' : '等待后端提供已验证预设'} style={{ width: '100%' }} options={choices.map((p) => ({ value: `${p.id}@${p.version}`, label: `${p.label} · ${p.version}` }))} onChange={(key) => {
|
||||
const p = choices.find((p) => `${p.id}@${p.version}` === key)!;
|
||||
onChange((s) => { if (kind === 'football') s.draft.football = { presetId: p.id, version: p.version, visualResource: s.draft.football?.visualResource ?? null }; else s.draft.pickupTarget = { kind: 'pickup_target', presetId: p.id, version: p.version, visualResource: s.draft.pickupTarget?.visualResource ?? null }; });
|
||||
}} />
|
||||
{current && <Collapse size="small" items={[{ key: 'parameters', label: '查看物理预设参数', children: <pre className="walking-file-tree">{JSON.stringify(choices.find((p) => p.id === current.presetId && p.version === current.version)?.parameters ?? { message: '预设参数待服务端返回' }, null, 2)}</pre> }]} />}
|
||||
</div>;
|
||||
};
|
||||
return <>
|
||||
<div className="walking-form-heading"><strong>额外功能 · 选填</strong><Typography.Text type="secondary">默认关闭,选哪项才要求配齐哪项;取消后保留草稿文件。</Typography.Text></div>
|
||||
<div className="walking-feature-grid">{walkingFeatures.map((def) => {
|
||||
const f = d.features[def.id], supported = support.find((s) => s.capabilityId === def.id);
|
||||
const availableSkills = [...skills, ...(session.resources.find((r) => r.key === f.configResource)?.config?.skills ?? [])];
|
||||
const uniqueSkills = [...new Map(availableSkills.map((s) => [s.id, s])).values()];
|
||||
const fileField = (field: string, label: string, kind: WalkingResourceKind, multiple = false, required = false) => <WalkingFileField label={`${def.label}:${label}`} value={f[field as keyof typeof f] as string | string[] | null} resources={session.resources} kinds={[kind, ...(kind === 'policy' ? ['extra' as const] : [])]} multiple={multiple} required={required} help={kind === 'policy' ? '可选择新文件或复用资源;策略路径以实际技能配置为准。' : '由同一演示工程提供,保留模型与控制引用关系。'} disabled={disabled} onPick={(directory) => onPick(field, kind, directory, def.id)} onChange={(v) => updateFeature(def.id, field, v)} />;
|
||||
return <section className={`walking-feature-card ${f.enabled ? 'selected' : ''}`} key={def.id} data-capability-id={def.id}>
|
||||
<Checkbox aria-label={`启用${def.label}`} checked={f.enabled} disabled={disabled} onChange={(event) => onChange((s) => { s.draft.enabled = true; s.draft.features[def.id].enabled = event.target.checked; })}><strong>{def.label}</strong></Checkbox>
|
||||
<Tag>{f.enabled ? '已选择,待验证' : '未启用,无需上传'}</Tag>
|
||||
{f.enabled && <Space direction="vertical" size="middle" style={{ width: '100%', marginTop: 12 }}>
|
||||
<Alert type="info" showIcon message={supported?.supported === false ? '需要播放器适配,可先保留草稿。' : '所选功能需单独检查,未验证前不会增加前台展示。'} description={supported?.message ?? def.requirementWhenSelected} />
|
||||
<Typography.Text type="secondary">{def.requires.join(';')}</Typography.Text>
|
||||
{def.skillBinding && <>
|
||||
<label>绑定实际技能 · 必填</label><Select aria-label={`${def.label}技能绑定`} mode="tags" disabled={disabled} value={f.skillIds} options={uniqueSkills.map((s) => ({ value: s.id, label: `${s.id} · ${s.controller} · ${s.kind}` }))} style={{ width: '100%' }} placeholder="选择配置中的技能;独立配置可填写其技能 ID" onChange={(v) => updateFeature(def.id, 'skillIds', v)} />
|
||||
<Typography.Text type="secondary">只绑定技能编号不会生成控制逻辑;控制器、触发/退出和恢复行走规则由配套配置提供。</Typography.Text>
|
||||
{fileField('configResource', '配套控制配置', 'config')}
|
||||
{fileField('policyResources', '引用策略', 'policy', true)}
|
||||
{f.skillIds.some((id) => uniqueSkills.some((s) => s.id === id && s.controller === 'oscillator')) && <Tag color="blue">已绑定参数控制器,无需为它额外提供 ONNX</Tag>}
|
||||
</>}
|
||||
{def.id === 'rollers' && fileField('modelResource', '滚轮物理模型', 'mjcf', false, true)}
|
||||
{def.id === 'visual_model' && <>{fileField('modelResource', '显示 GLB', 'glb', false, true)}{fileField('mappingResource', '节点/关节映射', 'mapping', false, true)}</>}
|
||||
{fileField('dependencyResources', '配套依赖文件', 'dependency', true)}
|
||||
{def.id === 'roller_crouch' && !d.features.rollers.enabled && <Alert type="warning" message="请先启用并配置滚轮行驶。" />}
|
||||
{def.id === 'recovery' && <Space><span>配置自动触发</span><Switch aria-label="起身自动触发" checked={f.autoTrigger} disabled={disabled} onChange={(v) => updateFeature(def.id, 'autoTrigger', v)} /><Typography.Text type="secondary">默认关闭;启用后仍需验证触发规则。</Typography.Text></Space>}
|
||||
<Typography.Paragraph type="secondary">前台通过验证并发布后增加:{def.controls.length ? def.controls.join('、') : '高精度模型显示'}{(def.props as string[]).includes('football') ? ',以及一个共享足球' : ''}。</Typography.Paragraph>
|
||||
</Space>}
|
||||
</section>;
|
||||
})}</div>
|
||||
{kicks && <section className="walking-shared-prop">{presetPicker('football')}
|
||||
<Alert type="info" showIcon message={`前台计划:一个足球${d.features.kick_left.enabled ? '+左脚踢球' : ''}${d.features.kick_right.enabled ? '+右脚踢球' : ''}。`} description="左右脚共享同一个有版本的物理预设,避免冲突。未启用的另一侧不要求策略,也不会出现按钮。" />
|
||||
<WalkingFileField label="自定义足球外观 GLB" value={d.football?.visualResource ?? null} resources={session.resources} kinds={['glb']} help="选填。平台提供标准足球;上传自定义外观不改变物理参数,也不启用踢球。" disabled={disabled || !d.football} onPick={() => onPick('footballVisual', 'glb')} onChange={(key) => onChange((s) => { if (s.draft.football) s.draft.football.visualResource = key as string | null; })} />
|
||||
</section>}
|
||||
{d.features.ground_pick.enabled && <section className="walking-shared-prop">{presetPicker('pickup_target')}{d.football && <Button disabled={disabled} onClick={() => onChange((s) => { s.draft.pickupTarget = { ...s.draft.football!, kind: 'football' }; })}>明确复用已选足球预设作为拾取对象</Button>}</section>}
|
||||
{!kicks && !d.features.ground_pick.enabled && <Alert type="info" showIcon message="当前没有球类/拾取功能,不会配置或显示足球及相关操作。" />}
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Button, Select, Space, Tag, Typography } from 'antd';
|
||||
import { UploadOutlined } from '@ant-design/icons';
|
||||
import type { WalkingLocalResource } from '@/utils/walkingForm';
|
||||
import type { WalkingResourceKind } from '@/api/walking-editor-types';
|
||||
export default function WalkingFileField({ label, value, resources, kinds, required, help, disabled, onPick, onChange, multiple = false }: {
|
||||
label: string; value: string | string[] | null; resources: WalkingLocalResource[]; kinds?: WalkingResourceKind[]; required?: boolean | 'referenced'; help: string; disabled?: boolean; multiple?: boolean;
|
||||
onPick: (directory?: boolean) => void; onChange: (value: string | string[] | null) => void;
|
||||
}) {
|
||||
const keys = Array.isArray(value) ? value : value ? [value] : [];
|
||||
const chosen = keys.map((key) => resources.find((r) => r.key === key)).filter((r): r is WalkingLocalResource => !!r);
|
||||
const options = resources.filter((r) => r.kind !== 'archive' && (!kinds || kinds.includes(r.kind))).map((r) => ({ value: r.key, label: `${r.relativePath}${r.remote ? ' · 已上传' : ' · 本地已选'}` }));
|
||||
return <div className="walking-form-field" data-walking-slot={label}>
|
||||
<div className="walking-form-field-title"><strong>{label}</strong><Tag color={required === true ? 'purple' : required === 'referenced' ? 'gold' : undefined}>{required === true ? '必传' : required === 'referenced' ? '有引用必传' : '选填'}</Tag><Tag color={chosen.some((r) => r.problem || r.remote?.status === 'FAILED') ? 'red' : chosen.length ? 'blue' : undefined}>{!chosen.length ? '未提供' : chosen.some((r) => r.problem || r.remote?.status === 'FAILED') ? '需要处理' : chosen.some((r) => r.remote?.status === 'PROCESSING') ? '处理中' : chosen.every((r) => r.remote) ? '已上传,待校验' : '已选择,尚未上传'}</Tag></div>
|
||||
<Typography.Paragraph type="secondary">{help}</Typography.Paragraph>
|
||||
<Space wrap><Button aria-label={`选择${label}`} icon={<UploadOutlined />} disabled={disabled} onClick={() => onPick()}>选择文件{multiple ? '(可多选)' : ''}</Button>{multiple && <Button aria-label={`选择${label.replace(/文件$/, '')}文件夹`} disabled={disabled} onClick={() => onPick(true)}>选择文件夹</Button>}</Space>
|
||||
{options.length > 0 && <Select aria-label={`绑定${label}`} mode={multiple ? 'multiple' : undefined} value={value ?? undefined} disabled={disabled} allowClear showSearch optionFilterProp="label" options={options} placeholder="可复用已选择或已上传资源" style={{ width: '100%', marginTop: 8 }} onChange={(v) => onChange(v ?? (multiple ? [] : null))} />}
|
||||
{chosen.map((r) => <div className="walking-field-file" key={r.key}><Typography.Text className="walking-path" copyable>{r.relativePath}</Typography.Text>{r.problem && <Typography.Text type="danger">{r.problem}</Typography.Text>}</div>)}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Alert, Button, Space, Table, Typography } from 'antd';
|
||||
import type { SelectedFile } from '@/api/types';
|
||||
import { pickFiles, toSelected } from '../pickFiles';
|
||||
import { formatSize } from '@/utils/format';
|
||||
export default function WalkingFolderUpload({ selected, onChange, busy, disabled, onUpload, autoUpload = false, retry = false }: { autoUpload?: boolean; retry?: boolean; selected: SelectedFile[]; onChange: (files: SelectedFile[]) => void; busy?: boolean; disabled?: boolean; onUpload?: () => void }) {
|
||||
return <Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Typography.Paragraph>直接选择行走演示工程文件夹,全部文件和子目录原样上传,无需压缩,也不要求特定配置文件名。</Typography.Paragraph>
|
||||
<Button disabled={busy} onClick={async () => { const files = await pickFiles({ directory: true }); if (files.length) onChange(toSelected(files, false)); }}>选择行走资源文件夹</Button>
|
||||
{!!selected.length && <><Table size="small" rowKey="relativePath" dataSource={selected} pagination={{ pageSize: 5 }} columns={[{ title: '文件路径', dataIndex: 'relativePath' }, { title: '大小', render: (_, row) => formatSize(row.file.size) }]} /><Space>{onUpload && (!autoUpload || retry) && <Button type="primary" disabled={disabled || busy} onClick={onUpload}>{autoUpload ? '重试上传行走资源文件夹' : '上传行走资源文件夹'}</Button>}<Button disabled={busy} onClick={() => onChange([])}>清除所选行走文件</Button></Space></>}
|
||||
<Alert type="info" message="上传保存资源文件;是否能展示、支持哪些动作,由前台读取内容决定。上传成功不代表仿真已验证通过。" />
|
||||
</Space>;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { Alert, Button, Drawer, Select, Space, Tag, Typography } from 'antd';
|
||||
import { FileTextOutlined } from '@ant-design/icons';
|
||||
import type { ExperienceFileSelection } from '@/utils/experienceFiles';
|
||||
import { legacyWalkingSpec, legacyWalkingRequirements, microbanConfigUrl, resolveWalkingResource, walkingExampleUrl, walkingGeneralRequirements, walkingProfiles, walkingRequirementsText, type WalkingResourceContext } from '@/utils/walkingUpload';
|
||||
import WalkingChecklist from './WalkingChecklist';
|
||||
import './walking-upload.css';
|
||||
|
||||
export interface WalkingUploadContext extends WalkingResourceContext {
|
||||
serviceUnavailable?: boolean;
|
||||
processing?: boolean;
|
||||
}
|
||||
const genericTree = `资源 ZIP(结构示意,路径以当前配置为准)
|
||||
├── robot.json 机器人配置入口
|
||||
├── <model 声明的 MJCF 路径> 物理模型
|
||||
├── <assets 声明的资源> 网格、贴图与引用依赖
|
||||
├── <ONNX controller.policy> 仅配置实际使用的策略
|
||||
└── 来源与许可说明
|
||||
|
||||
内置参数控制器不额外要求 ONNX。
|
||||
GLB、运动映射和单独控制文件由渲染方式与适配器决定。`;
|
||||
|
||||
export default function WalkingUploadGuide({ picker, selection, actions, mode = 'manage', ...context }: WalkingUploadContext & {
|
||||
picker: ReactNode; actions?: ReactNode; selection: ExperienceFileSelection; mode?: 'create' | 'manage';
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [example, setExample] = useState<'general' | 'microban-reference' | 'legacy-microduck'>('general');
|
||||
const model = resolveWalkingResource(context, selection.selected[0]?.file);
|
||||
const groupedDependencies = model.requirements.filter((file) => file.category === 'dependency');
|
||||
const compactDependencies = groupedDependencies.length > 4;
|
||||
const requirementRow = (file: typeof model.requirements[number]) => <div className="walking-requirement" key={file.path ?? file.key}>
|
||||
<div className="walking-requirement-name"><strong>{file.label}</strong><Tag color={file.required ? 'purple' : 'default'}>{file.required ? '本包必备' : '按引用/保留'}</Tag></div>
|
||||
<div>{file.path && <Typography.Text className="walking-path" copyable>{file.path}</Typography.Text>}{file.skills?.length ? <small>引用动作:{file.skills.join('、')}</small> : null}<small>{file.help}</small>{file.preparedBy && <small>准备:{file.preparedBy}</small>}</div>
|
||||
</div>;
|
||||
const downloadRequirements = () => {
|
||||
const url = URL.createObjectURL(new Blob([walkingRequirementsText(model.requirements, model.legacy)], { type: 'text/plain;charset=utf-8' }));
|
||||
const a = document.createElement('a'); a.href = url; a.download = '机器人运动演示文件要求.txt'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
};
|
||||
return <div className="walking-upload-guide">
|
||||
<div className="walking-template-heading"><Tag color={model.legacy ? 'gold' : 'blue'}>{model.legacy ? '旧版 Microduck 演示包专用清单' : '按当前资源包配置识别'}</Tag><Typography.Text type="secondary">选填,未配置时前台隐藏入口</Typography.Text></div>
|
||||
<Space wrap className="walking-upload-actions">{picker}<Button aria-label="查看准备说明" onClick={() => { setExample('general'); setOpen(true); }} icon={<FileTextOutlined />}>查看准备说明</Button>
|
||||
<Button onClick={() => { setExample('general'); setOpen(true); }}>查看示例模板</Button>
|
||||
</Space>
|
||||
{context.serviceUnavailable && mode === 'manage' && <Alert type="info" showIcon message="可以先查看通用准备说明与示例。上传服务尚未接入,暂不能读取包配置、检查或发布演示。" />}
|
||||
{actions && <div className="walking-selection-actions">{actions}</div>}
|
||||
<div className="walking-upload-columns">
|
||||
<section className="walking-requirements" aria-label="行走上传文件要求">
|
||||
<div className="walking-block-heading"><strong>{model.requirements.length ? '当前包的文件要求' : '通常需要准备'}</strong><span>{model.requirements.length ? model.formatLabel : '实际要求以本包声明为准'}</span></div>
|
||||
{model.requirements.length ? <>
|
||||
{model.legacy && <Alert type="warning" message="以下要求仅适用于旧版 Microduck 包,不适用于其他机器人。" />}
|
||||
{model.requirements.filter((file) => !compactDependencies || file.category !== 'dependency').map(requirementRow)}
|
||||
{compactDependencies && <details className="walking-dependency-details"><summary>模型依赖 · 本包引用 {groupedDependencies.length} 个(展开查看路径)</summary>{groupedDependencies.map(requirementRow)}</details>}
|
||||
</> : <>
|
||||
{walkingGeneralRequirements.map((requirement) => <div className="walking-requirement" key={requirement.label}>
|
||||
<div className="walking-requirement-name"><strong>{requirement.label}</strong></div><div><span>{requirement.rule}</span><small>准备:{requirement.source}</small></div>
|
||||
</div>)}
|
||||
<Alert type="info" showIcon message="只准备当前机器人声明的动作与文件。" description="未识别前不会套用其他机器人的策略清单。踢球、翻滚、起身不是所有机器人的必需动作。" />
|
||||
</>}
|
||||
<Button type="link" onClick={downloadRequirements}>下载文件要求说明,交给准备人员</Button>
|
||||
</section>
|
||||
<WalkingChecklist selection={selection} mode={mode} {...context} />
|
||||
</div>
|
||||
<Typography.Paragraph className="walking-template-note" type="secondary">示例仅供准备参考,不会替换上传内容。声明的动作、运行器支持与实际试运行分别检查;文件大小与数量由上传服务校验。</Typography.Paragraph>
|
||||
<Drawer aria-label="机器人运动演示:准备说明与示例" title="机器人运动演示:准备说明与示例" open={open} width="min(960px, 100vw)" onClose={() => setOpen(false)}>
|
||||
<Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||
<Alert type="info" showIcon message="不同机器人的动作和文件要求不同。" description="以当前包的配置与适配器依赖为准。ONNX 动作需要声明的策略文件,内置参数控制器无需另传策略。不能通过换一个模型文件就自动获得其他机器人的动作。" />
|
||||
<Space wrap><Button onClick={downloadRequirements}>下载文件要求说明</Button><Typography.Text copyable={{ text: walkingRequirementsText(model.requirements, model.legacy) }}>复制文件要求</Typography.Text></Space>
|
||||
<pre className="walking-file-tree">{genericTree}</pre>
|
||||
<section className="walking-file-details"><h4>通常需要准备</h4>{walkingGeneralRequirements.map((requirement) => <div className="walking-file-detail" key={requirement.label}><strong>{requirement.label}</strong><p>{requirement.rule}</p><Typography.Text type="secondary">准备:{requirement.source}</Typography.Text></div>)}</section>
|
||||
<section className="walking-file-details" aria-label="示例模板参考">
|
||||
<h4>示例模板 · 仅供参考,不决定当前包要求</h4>
|
||||
<Select aria-label="示例模板" showSearch={false} value={example} style={{ width: '100%' }} onChange={setExample} options={[
|
||||
{ value: 'general', label: '请选择参考示例' },
|
||||
{ value: 'microban-reference', label: 'Microban Robot Package:配置参考,不含完整模型' },
|
||||
{ value: 'legacy-microduck', label: '旧版 Microduck v1:专用兼容示例' },
|
||||
]} />
|
||||
{example === 'microban-reference' && <div className="walking-template-example">
|
||||
<Tag>Robot Package 配置参考</Tag><p>此参考声明 1 个行走 ONNX 和 1 个内置转头控制器,使用 MJCF 显示几何,不要求额外 GLB、运动映射或单独控制配置。</p>
|
||||
<Alert type="warning" showIcon message="这里只提供配置参考,不是可运行资源包。" description="当前下载工程的策略与网格包含 Git LFS 占位文件,需要取得真实大文件并完成校验、运行器接入和试运行。" />
|
||||
<Button href={microbanConfigUrl} download="microban.robot.json">下载 Microban 配置参考 JSON</Button>
|
||||
</div>}
|
||||
{example === 'legacy-microduck' && <div className="walking-template-example" aria-label="旧版 Microduck 专用示例">
|
||||
<Alert type="warning" showIcon message="仅适用于旧版 Microduck v1,不能作为所有机器人的上传要求。" description="下列七策略是这个旧版播放器的启动依赖。其他机器人不需要照着补踢球、翻滚或起身文件。新版 Microduck Robot Package 也需按声明与专用适配器完整依赖另行检查。" />
|
||||
<Space wrap><Button href={walkingExampleUrl} download={legacyWalkingSpec.example.fileName}>下载旧版 Microduck 示例 ZIP</Button><Typography.Text copyable={{ text: walkingRequirementsText(legacyWalkingRequirements, true) }}>复制旧版专用清单</Typography.Text></Space>
|
||||
{legacyWalkingSpec.requiredFiles.map((file) => <div className="walking-file-detail" key={file.id}><Space wrap><strong>{file.label}</strong><Tag color="gold">仅旧版示例必需</Tag></Space><Typography.Text className="walking-path" copyable>{file.path}</Typography.Text><p>{file.help}</p></div>)}
|
||||
<h4>旧版示例的滚轮扩展</h4><p>{legacyWalkingSpec.optionalExtension.help}</p>{legacyWalkingSpec.optionalExtension.paths.map((path) => <Typography.Paragraph key={path} className="walking-path" copyable>{path}</Typography.Paragraph>)}
|
||||
</div>}
|
||||
</section>
|
||||
<Alert type="warning" showIcon message="上传完成、文件齐全与可以播放是不同状态。" description="Robot Package 还需社区接入对应格式与运行器;尚未接入时只能作为待适配资源。控制契约、引用闭包、真实文件内容和浏览器试运行均需检查,不能仅凭配置或扩展名标为可运行。" />
|
||||
</Space>
|
||||
</Drawer>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Collapse, Descriptions, Input, Modal, Popconfirm, Select, Space, Switch, Table, Tag, Typography } from 'antd';
|
||||
import type { ExperienceBuild, ExperienceDraftView } from '@/api/experience-types';
|
||||
import type { WalkingEditorOperation, WalkingEditorView, WalkingFeatureId, WalkingResourceKind } from '@/api/walking-editor-types';
|
||||
import * as api from '@/api/walking-editor';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import { activeResourceKeys, emptyWalkingSession, enabledCapabilityIds, inspectWalkingFile, peekWalkingSession, publicationSummary, readRobotConfig, readWalkingFolder, readyCapabilities, releaseWalkingSession, serializeWalkingDraft, sessionFromView, walkingFeatures, walkingFormProblems, type WalkingLocalResource, type WalkingLocalSession } from '@/utils/walkingForm';
|
||||
import { uploadWalkingRows, type WalkingUploadBatch } from '@/utils/walkingResourceUpload';
|
||||
import { experiencePathProblem, safeExperienceUrl } from '@/utils/modelAssets';
|
||||
import { errorText, formatSize, isAbort } from '@/utils/format';
|
||||
import { pickFiles } from '../pickFiles';
|
||||
import WalkingFileField from './WalkingFileField';
|
||||
import WalkingFeatureForm from './WalkingFeatureForm';
|
||||
import './walking-form.css';
|
||||
|
||||
type Props = {
|
||||
projectCode?: string; disabled?: boolean; mode?: 'create' | 'manage'; legacy?: ReactNode; legacyInitiallyOpen?: boolean;
|
||||
onSessionChange?: (session: WalkingLocalSession) => void; onPendingChange?: (pending: boolean) => void; onBusyChange?: (busy: boolean) => void;
|
||||
experienceRevision?: () => number; beforeBuild?: () => Promise<number>;
|
||||
onSnapshot?: (snapshot: ExperienceDraftView, build?: ExperienceBuild) => void;
|
||||
canPublish?: boolean; onPublish?: (build: ExperienceBuild) => void;
|
||||
};
|
||||
const labelFor = (id: string) => id === 'walk' ? '基础行走' : walkingFeatures.find((f) => f.id === id)?.label ?? id;
|
||||
const waitForJob = (signal: AbortSignal) => new Promise<void>((resolve, reject) => {
|
||||
const abort = () => { clearTimeout(timer); reject(new DOMException('Aborted', 'AbortError')); };
|
||||
const timer = setTimeout(() => { signal.removeEventListener('abort', abort); resolve(); }, 2000);
|
||||
signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort();
|
||||
});
|
||||
export default function WalkingWorkbench(props: Props) {
|
||||
const { projectCode, mode = 'manage', disabled = false } = props;
|
||||
const { message, modal } = App.useApp();
|
||||
const [session, setSession] = useState<WalkingLocalSession>(() => projectCode ? peekWalkingSession(projectCode) ?? emptyWalkingSession() : emptyWalkingSession());
|
||||
const sessionRef = useRef(session); sessionRef.current = session;
|
||||
const [view, setView] = useState<WalkingEditorView | null>(null), viewRef = useRef<WalkingEditorView | null>(null);
|
||||
const [available, setAvailable] = useState(false), [loading, setLoading] = useState(!!projectCode), [dirty, setDirty] = useState(() => !!(projectCode && peekWalkingSession(projectCode)));
|
||||
const dirtyRef = useRef(dirty); dirtyRef.current = dirty;
|
||||
const [busy, setBusy] = useState(false), busyRef = useRef(false), [picking, setPicking] = useState(false);
|
||||
const [error, setError] = useState(''), [phase, setPhase] = useState(''), [uncertain, setUncertain] = useState(false), [conflict, setConflict] = useState(false);
|
||||
const [progress, setProgress] = useState(''), [jobId, setJobId] = useState<string | null>(null);
|
||||
const [confirmCapabilities, setConfirmCapabilities] = useState<WalkingFeatureId[] | null>(null), [importCandidate, setImportCandidate] = useState<WalkingEditorOperation['importCandidate']>(null);
|
||||
const [openSections, setOpenSections] = useState<string[]>(props.legacyInitiallyOpen ? ['legacy'] : []);
|
||||
const mounted = useRef(false), controller = useRef<AbortController>(), loadController = useRef<AbortController>(), batch = useRef<WalkingUploadBatch | null>(null);
|
||||
const latestProps = useRef(props); latestProps.current = props;
|
||||
const locked = disabled || busy || picking || loading || uncertain || conflict || !!jobId;
|
||||
const local = session.resources.filter((r) => r.file && !r.remote);
|
||||
const used = activeResourceKeys(session);
|
||||
const basicProblems = walkingFormProblems(session);
|
||||
const currentCheck = !dirty && view?.check?.draftRevision === view?.revision && view?.check?.sourceVersion === view?.sourceVersion ? view?.check : null;
|
||||
const build = !dirty && view && view.latestBuild && view.latestBuild.draftRevision === view.revision && view.latestBuild.sourceVersion === view.sourceVersion ? view.latestBuild : null;
|
||||
const revision = () => latestProps.current.experienceRevision?.() ?? viewRef.current?.experienceDraftRevision ?? 0;
|
||||
const edit = (update: (s: WalkingLocalSession) => void) => {
|
||||
setSession((previous) => { const next = { ...previous, draft: structuredClone(previous.draft), resources: [...previous.resources] }; update(next); sessionRef.current = next; return next; });
|
||||
setDirty(true); setError('');
|
||||
};
|
||||
const applyView = (next: WalkingEditorView, replace = false) => {
|
||||
if (next.apiVersion !== 1 || !Number.isInteger(next.revision) || !Number.isInteger(next.experienceDraftRevision) || !next.draft?.features || !Array.isArray(next.resources) || !Array.isArray(next.skills) || !Array.isArray(next.presets) || !Array.isArray(next.featureSupport) || next.check && (!next.check.base || !Array.isArray(next.check.features))) throw new Error('行走表单接口结构不匹配,请核对 apiVersion、revision、draft、resources、skills、presets 与分组报告。');
|
||||
viewRef.current = next; setView(next); setAvailable(true);
|
||||
setSession((old) => {
|
||||
if (replace) { const value = sessionFromView(next); sessionRef.current = value; return value; }
|
||||
const merged = old.resources.map((r) => {
|
||||
const remote = next.resources.find((a) => a.resourceId === r.remote?.resourceId || a.clientId === r.key && a.relativePath === r.relativePath && a.bytes === r.file?.size);
|
||||
return remote ? { ...r, remote } : r;
|
||||
});
|
||||
for (const remote of next.resources) if (!merged.some((r) => r.remote?.resourceId === remote.resourceId)) merged.push({ key: remote.resourceId, relativePath: remote.relativePath, originalPath: remote.originalPath, kind: remote.kind, remote });
|
||||
const value = { ...old, resources: merged }; sessionRef.current = value; return value;
|
||||
});
|
||||
if (next.experienceDraft) latestProps.current.onSnapshot?.(next.experienceDraft, next.latestBuild?.experienceBuild);
|
||||
};
|
||||
const load = async (replace = false) => {
|
||||
if (!projectCode) return;
|
||||
loadController.current?.abort(); const abort = new AbortController(); loadController.current = abort;
|
||||
setLoading(true);
|
||||
try {
|
||||
const next = await api.getWalkingEditor(projectCode, abort.signal); abort.signal.throwIfAborted();
|
||||
applyView(next, replace || !dirtyRef.current); if (replace || !dirtyRef.current) setDirty(false);
|
||||
setUncertain(false); setConflict(false); setError('');
|
||||
} catch (cause) {
|
||||
if (abort.signal.aborted || isAbort(cause)) return;
|
||||
if (cause instanceof AdminApiError && [404, 405, 501].includes(cause.status)) setAvailable(false);
|
||||
else setError(errorText(cause));
|
||||
} finally { if (!abort.signal.aborted) setLoading(false); }
|
||||
};
|
||||
useEffect(() => {
|
||||
mounted.current = true; if (projectCode) { releaseWalkingSession(projectCode); load(); }
|
||||
return () => { mounted.current = false; controller.current?.abort(); loadController.current?.abort(); };
|
||||
}, [projectCode]);
|
||||
useEffect(() => { props.onSessionChange?.(session); }, [session, props.onSessionChange]);
|
||||
useEffect(() => { props.onPendingChange?.(dirty || !!jobId); }, [dirty, jobId, props.onPendingChange]);
|
||||
useEffect(() => { props.onBusyChange?.(busy || picking); }, [busy, picking, props.onBusyChange]);
|
||||
useEffect(() => { if (props.legacyInitiallyOpen) setOpenSections((old) => old.includes('legacy') ? old : [...old, 'legacy']); }, [props.legacyInitiallyOpen]);
|
||||
|
||||
const perform = async (action: (signal: AbortSignal) => Promise<void>, readOnly = false) => {
|
||||
if (busyRef.current) return;
|
||||
busyRef.current = true; setBusy(true); setError(''); const abort = new AbortController(); controller.current = abort;
|
||||
try { await action(abort.signal); }
|
||||
catch (cause) {
|
||||
if (abort.signal.aborted || isAbort(cause) || !mounted.current) return;
|
||||
if (cause instanceof AdminApiError && cause.status === 409) { setConflict(true); setError(`${errorText(cause)}。本地表单保留,请刷新核对版本后再操作。`); }
|
||||
else if (!readOnly && (cause instanceof TypeError || cause instanceof AdminApiError && cause.status >= 500)) { setUncertain(true); setError(`${errorText(cause)}。服务端结果待核对,请刷新状态,不会自动重发。`); }
|
||||
else setError(errorText(cause));
|
||||
} finally { busyRef.current = false; if (mounted.current) setBusy(false); }
|
||||
};
|
||||
const runOperation = async (operation: WalkingEditorOperation, signal: AbortSignal) => {
|
||||
let next = operation;
|
||||
if (next.jobId) {
|
||||
const id = next.jobId; setJobId(id);
|
||||
for (;;) {
|
||||
const job = await api.getWalkingEditorJob(projectCode!, id, signal); signal.throwIfAborted(); setPhase(job.message);
|
||||
if (job.status === 'FAILED') { if (job.view) applyView(job.view); setJobId(null); throw new Error(job.message || '处理失败,原草稿及发布版本已保留。'); }
|
||||
if (job.status === 'SUCCEEDED') { next = job; setJobId(null); break; }
|
||||
await waitForJob(signal);
|
||||
}
|
||||
}
|
||||
if (next.view) { applyView(next.view); setUncertain(false); }
|
||||
if (next.importCandidate) setImportCandidate(next.importCandidate);
|
||||
if (!next.view && !next.importCandidate) throw new Error('处理完成但没有返回版本或候选,请刷新核对。');
|
||||
};
|
||||
const save = async (signal: AbortSignal) => {
|
||||
if (!projectCode || !viewRef.current) throw new Error('上传服务尚未接入。');
|
||||
const draft = serializeWalkingDraft(sessionRef.current);
|
||||
const next = await api.saveWalkingEditor(projectCode, viewRef.current.revision, revision(), draft, signal); signal.throwIfAborted();
|
||||
applyView(next); setDirty(false); dirtyRef.current = false; setPhase('已保存已上传的资源和功能设置,前台尚未更新。');
|
||||
message.success(sessionRef.current.resources.some((r) => r.file && !r.remote) ? '服务器草稿已保存,仍有本地素材尚未上传' : '行走草稿已保存');
|
||||
return next;
|
||||
};
|
||||
const choose = async (target: string, kind: WalkingResourceKind, directory = false, feature?: string) => {
|
||||
const multiple = directory || ['dependencyResources', 'policyResources', 'extra'].includes(target);
|
||||
const accept = kind === 'config' || kind === 'mapping' ? '.json' : kind === 'policy' ? '.onnx' : kind === 'mjcf' ? '.xml' : kind === 'glb' ? '.glb' : kind === 'archive' ? '.zip' : undefined;
|
||||
const files = await pickFiles({ directory, multiple, accept }); if (!files.length || !mounted.current) return;
|
||||
setPicking(true);
|
||||
try {
|
||||
const current = sessionRef.current, rows: WalkingLocalResource[] = [];
|
||||
let robot = target === 'entryResource' ? null : current.robot;
|
||||
for (const file of files) {
|
||||
const originalPath = file.webkitRelativePath || file.name;
|
||||
let relativePath = originalPath;
|
||||
if (directory && robot?.assets.length) {
|
||||
const trimmed = originalPath.split('/').slice(1).join('/');
|
||||
if (robot.assets.includes(trimmed) && !robot.assets.includes(originalPath)) relativePath = trimmed;
|
||||
}
|
||||
if (target === 'entryResource') relativePath = 'robot.json';
|
||||
if (target === 'modelResource' && !feature && robot) relativePath = robot.model;
|
||||
if (target === 'walkPolicyResource') relativePath = robot?.skills.find((s) => s.id === current.draft.walkSkillId)?.policy ?? file.name;
|
||||
const row: WalkingLocalResource = { key: `local-${crypto.randomUUID()}`, file, relativePath, originalPath, kind };
|
||||
row.problem = experiencePathProblem(relativePath) ?? await inspectWalkingFile(file, kind);
|
||||
if (kind === 'config' && !row.problem) {
|
||||
try { row.config = readRobotConfig(JSON.parse((await file.text()).replace(/^\uFEFF/, ''))); if (target === 'entryResource') robot = row.config; }
|
||||
catch (cause) { row.problem = errorText(cause); }
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
if (!mounted.current) return;
|
||||
edit((s) => {
|
||||
s.draft.enabled = true; s.resources.push(...rows);
|
||||
if (target === 'extra' || target === 'archive') return;
|
||||
const holder = feature ? s.draft.features[feature] : s.draft;
|
||||
const old = (holder as unknown as Record<string, unknown>)[target];
|
||||
if (target === 'footballVisual') { if (s.draft.football) s.draft.football.visualResource = rows[0].key; }
|
||||
else (holder as unknown as Record<string, unknown>)[target] = multiple ? [...new Set([...(Array.isArray(old) ? old : []), ...rows.map((r) => r.key)])] : rows[0].key;
|
||||
if (target === 'entryResource') { s.robot = null; s.draft.walkSkillId = null; }
|
||||
if (target === 'entryResource' && robot && !rows[0].problem) {
|
||||
s.robot = robot; const primary = robot.skills.filter((skill) => skill.kind === 'primary' && skill.controller === 'onnx');
|
||||
s.draft.walkSkillId = primary.length === 1 ? primary[0].id : null;
|
||||
}
|
||||
const referenced = activeResourceKeys(s);
|
||||
if (!multiple && typeof old === 'string' && !referenced.has(old)) s.resources = s.resources.filter((r) => r.key !== old || !!r.remote);
|
||||
});
|
||||
} finally { if (mounted.current) setPicking(false); }
|
||||
};
|
||||
const chooseFolder = async () => {
|
||||
const files = await pickFiles({ directory: true });
|
||||
if (!files.length || !mounted.current) return;
|
||||
setPicking(true);
|
||||
try {
|
||||
const folder = await readWalkingFolder(files);
|
||||
if (!mounted.current) return;
|
||||
edit((s) => {
|
||||
s.resources.push(...folder.resources); s.draft.enabled = true;
|
||||
if (!s.draft.entryResource && folder.draft.entryResource) {
|
||||
s.robot = folder.robot;
|
||||
s.draft.entryResource = folder.draft.entryResource;
|
||||
s.draft.modelResource = folder.draft.modelResource;
|
||||
s.draft.walkPolicyResource = folder.draft.walkPolicyResource;
|
||||
s.draft.walkSkillId = folder.draft.walkSkillId;
|
||||
}
|
||||
});
|
||||
setPhase(folder.robot ? '文件夹已读取,基础资源已识别;请核对表单并按需勾选附加功能,再上传文件。已有基础配置会保留。' : '文件夹已读取;请提供根目录的 robot.json,或在下方选择机器人控制配置。');
|
||||
} catch (cause) { setError(errorText(cause)); }
|
||||
finally { if (mounted.current) setPicking(false); }
|
||||
};
|
||||
const upload = () => perform(async (signal) => {
|
||||
const rows = sessionRef.current.resources.filter((r) => r.file && !r.remote && !r.problem);
|
||||
const remote = await uploadWalkingRows(projectCode!, rows, batch.current, signal, (b) => { batch.current = b; }, (done, total) => setProgress(`${done} / ${total}`)); signal.throwIfAborted();
|
||||
setSession((s) => { const next = { ...s, resources: s.resources.map((r) => { const match = remote.find((a) => a.clientId === r.key); return match ? { ...r, remote: match } : r; }) }; sessionRef.current = next; return next; });
|
||||
batch.current = null; setProgress(''); setPhase('资源已上传,尚未校验控制契约或运行效果。');
|
||||
});
|
||||
const field = (target: string, label: string, kind: WalkingResourceKind, required: boolean | 'referenced', help: string, multiple = false) => <WalkingFileField label={label} value={session.draft[target as keyof typeof session.draft] as string | string[] | null} resources={session.resources} kinds={[kind, 'extra']} required={required} help={help} multiple={multiple} disabled={locked} onPick={(directory) => choose(target, kind, directory)} onChange={(value) => edit((s) => { (s.draft as unknown as Record<string, unknown>)[target] = value; })} />;
|
||||
const skillOptions = session.robot?.skills ?? view?.skills ?? [];
|
||||
const ready = view && !dirty ? readyCapabilities(view) : [];
|
||||
const validBuild = !!(build && currentCheck && build.checkId === currentCheck.checkId && build.capabilityIds.includes('walk') && build.capabilityIds.every((id) => ready.includes(id) && (walkingFeatures.find((f) => f.id === id)?.dependsOn ?? []).every((dependency) => build.capabilityIds.includes(dependency as WalkingFeatureId))) && build.experienceBuild.publishable && build.experienceBuild.report.status === 'PASSED' && currentCheck.communityRuntime === 'supported');
|
||||
const preview = validBuild ? safeExperienceUrl(build?.experienceBuild.previewUrls.walking) : null;
|
||||
|
||||
return <div className="walking-workbench" aria-label="行走演示配置表单">
|
||||
<div className="walking-form-heading"><Space><strong>基础行走+可选功能</strong><Switch aria-label="配置本项目行走演示" checked={session.draft.enabled} disabled={locked} onChange={(value) => edit((s) => { s.draft.enabled = value; })} /></Space><Typography.Text type="secondary">整体选填;选择文件会开始配置,不影响整机和装配。</Typography.Text></div>
|
||||
{!available && mode !== 'create' && !loading && <Alert showIcon type="info" message="新版表单上传接口待接入:可以选择文件和配置功能,尚未上传、校验或保存到服务器。" />}
|
||||
{mode === 'create' && <Alert showIcon type="info" message="先配置并选择文件,创建项目后会保留;上传服务接入后再上传和保存。" />}
|
||||
<div className="walking-folder-entry"><Button type="primary" disabled={locked} onClick={chooseFolder}>选择行走资源文件夹</Button><Typography.Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>直接选择包含 robot.json 的工程根文件夹,无需压缩。保留内部目录和原文件,自动识别基础配置、物理模型和行走策略;其他文件进入草稿资源库,附加功能按需勾选。</Typography.Paragraph></div>
|
||||
<div className="walking-form-heading"><strong>基础行走 · 必须准备</strong><Tag color="purple">四项,按同一机器人的配置配套</Tag></div>
|
||||
<div className="walking-base-grid">
|
||||
{field('entryResource', '机器人控制配置', 'config', true, '由模型/算法人员提供 robot.json,描述模型引用、关节、观测、动作、控制参数及基础行走技能。')}
|
||||
{field('modelResource', '物理模型 XML', 'mjcf', true, 'MJCF XML。不是外观 GLB,不能用 URDF 改扩展名替代;包内路径按控制配置指定。')}
|
||||
{field('dependencyResources', '模型引用文件', 'dependency', 'referenced', '有引用就需传齐网格、贴图、include 等。可多选或选文件夹;没有外部依赖时无需另传,数量不固定。', true)}
|
||||
{field('walkPolicyResource', '基础行走策略 ONNX', 'policy', true, '至少一个与控制配置配套的 primary ONNX;Python、.pt、训练日志不能替代。')}
|
||||
</div>
|
||||
<div className="walking-base-skill"><label>基础行走技能 · 必填</label><Select aria-label="基础行走技能绑定" disabled={locked} value={session.draft.walkSkillId ?? undefined} placeholder="读取 robot.json 后选择 primary ONNX 技能" options={skillOptions.filter((s) => s.kind === 'primary' && s.controller === 'onnx').map((s) => ({ value: s.id, label: `${s.id} · ${s.policy ?? '策略路径待确认'}` }))} style={{ width: '100%' }} onChange={(id) => edit((s) => { s.draft.walkSkillId = id; })} /><Typography.Text type="secondary">本地仅读取配置声明,不代表模型、策略或控制契约已验证。</Typography.Text></div>
|
||||
<Alert type="info" showIcon message="发布 manifest 由系统生成,用户无需上传或填写文件索引、哈希。" description="平台提供地面、灯光、相机、暂停和重置。额外 GLB、kinematics.json、单独 controller.json、足球模型都不是基础行走的通用必传项。" />
|
||||
<WalkingFeatureForm session={session} presets={view?.presets ?? []} skills={skillOptions} support={view?.featureSupport ?? []} disabled={locked} onChange={edit} onPick={choose} />
|
||||
<section className="walking-material-library" aria-label="行走草稿资源库"><div className="walking-form-heading"><strong>草稿资源库</strong><Button disabled={locked} onClick={() => choose('extra', 'extra')}>添加额外素材(不启用功能)</Button></div>
|
||||
<Typography.Paragraph type="secondary">允许多传。未绑定功能的素材保留草稿,不增加按钮,不由前台加载;发布时后端只编译所选功能的实际依赖。</Typography.Paragraph>
|
||||
<Table<WalkingLocalResource> size="small" rowKey="key" dataSource={session.resources} pagination={{ pageSize: 6, showSizeChanger: false }} scroll={{ x: 760 }} columns={[
|
||||
{ title: '包内路径', render: (_, row) => <Input aria-label={`资源路径 ${row.originalPath}`} value={row.relativePath} disabled={locked || !!row.remote && !row.file} onChange={(e) => edit((s) => { s.resources = s.resources.map((r) => r.key === row.key ? { ...r, relativePath: e.target.value, remote: undefined } : r); })} /> },
|
||||
{ title: '大小', width: 90, render: (_, row) => formatSize(row.file?.size ?? row.remote?.bytes ?? 0) },
|
||||
{ title: '状态', render: (_, row) => <><Tag color={row.problem || row.remote?.status === 'FAILED' ? 'red' : row.remote ? 'blue' : undefined}>{row.problem ? '需要处理' : row.remote?.status === 'PROCESSING' ? '处理中' : row.remote?.status === 'FAILED' ? '处理失败' : row.remote ? '已上传,待校验' : '已选择,尚未上传'}</Tag>{row.problem && <small>{row.problem}</small>}</> },
|
||||
{ title: '用途', width: 160, render: (_, row) => used.has(row.key) ? '所选功能引用(待校验)' : '未用于展示' },
|
||||
{ title: '操作', width: 80, render: (_, row) => <Popconfirm title="从当前草稿移除此素材?服务器历史版本不会删除。" onConfirm={() => edit((s) => { s.resources = s.resources.filter((r) => r.key !== row.key); })}><Button size="small" danger disabled={locked || used.has(row.key)}>移除</Button></Popconfirm> },
|
||||
]} locale={{ emptyText: '尚未选择素材' }} />
|
||||
{local.length > 0 && <Space wrap><Button disabled={locked || !available || !projectCode || local.every((r) => !!r.problem)} onClick={upload}>上传已选行走资源{progress ? `(${progress})` : ''}</Button><Typography.Text type="secondary">原文件直传,不限制前端大小。格式异常的素材需处理后再上传。</Typography.Text></Space>}
|
||||
</section>
|
||||
<Collapse activeKey={openSections} onChange={(keys) => setOpenSections(Array.isArray(keys) ? keys : [keys])} items={[{ key: 'zip', label: '已有资源包?导入 ZIP', children: <Space direction="vertical" style={{ width: '100%' }}><Alert type="info" message="ZIP 导入到同一表单草稿,功能绑定需确认;额外文件保留为未用于展示。包内 manifest 仅作导入资料,真实索引由系统重建。" /><Button disabled={locked} onClick={() => choose('archive', 'archive')}>选择待导入 ZIP</Button>{session.resources.filter((r) => r.kind === 'archive').map((r) => <Space key={r.key} wrap><span>{r.relativePath}</span><Tag>{r.remote ? '已上传,尚未导入' : '已选择,尚未上传'}</Tag><Button disabled={locked || !available || !r.remote || !projectCode} onClick={() => perform(async (signal) => { await runOperation(await api.importWalkingResources(projectCode!, viewRef.current!.revision, r.remote!.resourceId, signal), signal); })}>读取到表单并确认</Button></Space>)}</Space> }, ...(props.legacy ? [{ key: 'legacy', label: '旧版兼容资源与检查(不改变新表单)', children: props.legacy }] : [])]} />
|
||||
{error && <Alert type="error" showIcon message={error} />}{phase && <Alert type="info" message={phase} />}
|
||||
<div className="walking-form-actions"><Space wrap>
|
||||
<Button disabled={locked || !available || !dirty} onClick={() => perform(async (signal) => { await save(signal); })}>保存行走草稿</Button>
|
||||
<Button type="primary" disabled={locked || !available || !session.draft.enabled} onClick={() => {
|
||||
const baseSession = { ...sessionRef.current, draft: { ...sessionRef.current.draft, features: Object.fromEntries(Object.entries(sessionRef.current.draft.features).map(([id, feature]) => [id, { ...feature, enabled: false }])) } };
|
||||
const problems = walkingFormProblems(baseSession, true); if (problems.length) { setError(problems.join(';')); return; }
|
||||
perform(async (signal) => { const current = dirtyRef.current ? await save(signal) : viewRef.current!; setPhase('正在检查基础与各个已选功能'); await runOperation(await api.checkWalkingEditor(projectCode!, current.revision, revision(), signal), signal); });
|
||||
}}>检查行走资源</Button>
|
||||
{projectCode && (dirty ? <Popconfirm title="刷新并核对服务器状态?保留当前本地表单与文件。" onConfirm={() => load()}><Button disabled={busy || picking}>刷新行走状态</Button></Popconfirm> : <Button loading={loading} disabled={busy} onClick={() => load()}>刷新行走状态</Button>)}
|
||||
{jobId && !busy && <Button onClick={() => perform(async (signal) => { await runOperation({ jobId, view: null }, signal); }, true)}>继续查询行走处理结果</Button>}
|
||||
</Space>{dirty && <Tag color="orange">有本地修改,旧检查结果不适用</Tag>}</div>
|
||||
{basicProblems.length > 0 && session.draft.enabled && <Collapse items={[{ key: 'pending', label: `检查前待补充 ${basicProblems.length} 项(允许先保存不完整草稿)`, children: <ul>{basicProblems.map((problem) => <li key={problem}>{problem}</li>)}</ul> }]} />}
|
||||
<section className="walking-feature-report" aria-label="按功能检查与发布"><strong>按功能检查与发布</strong>
|
||||
<div className="walking-check-row"><span>基础行走</span><Tag color={currentCheck?.base.status === 'PASSED' ? 'green' : currentCheck?.base.status === 'FAILED' ? 'red' : undefined}>{currentCheck ? currentCheck.base.status === 'PASSED' ? '通过' : currentCheck.base.message : '未检查'}</Tag></div>
|
||||
{walkingFeatures.map((def) => { const check = currentCheck?.features.find((f) => f.capabilityId === def.id); return <div className="walking-check-row" key={def.id}><span>{def.label}</span><div><Tag color={check?.status === 'PASSED' ? 'green' : check?.status === 'FAILED' ? 'red' : undefined}>{!session.draft.features[def.id].enabled ? '未启用,无需上传' : check?.status === 'PASSED' ? '通过' : check?.message ?? '未检查'}</Tag>{check?.issues.map((issue) => <small key={`${issue.code}-${issue.path}`}>{issue.path ? `${issue.path}:` : ''}{issue.message}</small>)}</div></div>; })}
|
||||
{currentCheck?.base.issues.map((issue) => <Alert key={`${issue.code}-${issue.path}`} type="error" message={`${issue.path ?? '基础行走'}:${issue.message}`} />)}
|
||||
{currentCheck && currentCheck.communityRuntime !== 'supported' && <Alert type="warning" message="社区运行器尚未支持本版本,保留草稿,暂不能生成可发布演示。" />}
|
||||
<Button disabled={locked || !available || !ready.length} onClick={() => setConfirmCapabilities(ready)}>仅用已通过功能生成发布版本</Button>
|
||||
{preview && <a href={preview} target="_blank" rel="noreferrer">预览本版本行走演示</a>}
|
||||
{build && <Button type="primary" disabled={locked || !validBuild || !props.canPublish || !props.onPublish} onClick={() => props.onPublish?.(build.experienceBuild)}>发布已确认的功能</Button>}
|
||||
</section>
|
||||
<Modal title="确认本次发布功能" open={!!confirmCapabilities} okText="确认功能并生成发布版本" cancelText="继续补充资源" onCancel={() => setConfirmCapabilities(null)} onOk={() => {
|
||||
const ids = confirmCapabilities!; setConfirmCapabilities(null);
|
||||
perform(async (signal) => { const current = viewRef.current!; const checked = readyCapabilities(current); if (ids.some((id) => !checked.includes(id))) throw new Error('检查结果已变化,请重新确认。'); const rev = await latestProps.current.beforeBuild?.() ?? revision(); await runOperation(await api.buildWalkingEditor(projectCode!, current.revision, rev, current.check!.checkId, ids, signal), signal); setPhase('发布版本已生成,请预览后确认发布;尚未更新前台。'); });
|
||||
}}><Typography.Paragraph>将为以下已通过功能重新编译机器人配置、输入绑定与实际依赖。未通过或未选功能不会发布,其草稿文件仍保留。</Typography.Paragraph><Checkbox.Group value={confirmCapabilities ?? []} onChange={(values) => { const ids: WalkingFeatureId[] = ['walk']; for (const def of walkingFeatures) if (values.includes(def.id as WalkingFeatureId) && def.dependsOn.every((id) => ids.includes(id as WalkingFeatureId))) ids.push(def.id as WalkingFeatureId); setConfirmCapabilities(ids); }} options={ready.map((id) => ({ label: labelFor(id), value: id, disabled: id === 'walk' }))} />
|
||||
{confirmCapabilities && <Descriptions column={1} size="small"><Descriptions.Item label="将显示的道具">{publicationSummary(session.draft, confirmCapabilities).props.join('、') || '无足球及额外道具'}</Descriptions.Item><Descriptions.Item label="未发布的已选功能">{enabledCapabilityIds(session.draft).filter((id) => !confirmCapabilities.includes(id)).map(labelFor).join('、') || '无'}</Descriptions.Item></Descriptions>}
|
||||
</Modal>
|
||||
<Modal title="确认 ZIP 导入的配置与功能" open={!!importCandidate} okText="应用到本地表单" cancelText="取消" onCancel={() => setImportCandidate(null)} onOk={() => { if (!importCandidate) return; edit((s) => { s.robot = null; s.draft = { ...emptyWalkingSession().draft, ...importCandidate, features: { ...emptyWalkingSession().draft.features, ...importCandidate.features } }; }); setImportCandidate(null); }}><Typography.Paragraph>候选不会直接保存或发布,请核对导入后的基础文件与功能绑定。无绑定额外素材保留在草稿库。</Typography.Paragraph><p>{importCandidate ? enabledCapabilityIds(importCandidate).map(labelFor).join('、') : ''}</p></Modal>
|
||||
<Collapse items={[{ key: 'debug', label: '联调数据(高级)', children: <><Typography.Paragraph type="secondary">这是后台表单数据,不是播放器 manifest。未上传文件不会伪造资源编号或文件哈希。</Typography.Paragraph><Typography.Paragraph copyable={{ text: JSON.stringify({ apiVersion: 1, draft: session.draft, files: session.resources.map((r) => ({ clientId: r.key, relativePath: r.relativePath, originalPath: r.originalPath, kind: r.kind, sizeBytes: r.file?.size ?? r.remote?.bytes, resourceId: r.remote?.resourceId })) }, null, 2) }}>复制当前表单与上传字段,供后端对接</Typography.Paragraph></> }]} />
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
.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-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-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; }
|
||||
@@ -0,0 +1,23 @@
|
||||
.experience-upload-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; width: 100%; }
|
||||
.experience-upload-grid .ant-card { margin: 0 !important; min-width: 0; }
|
||||
.experience-section-title { display: inline-flex; align-items: center; gap: 10px; }
|
||||
.experience-section-icon { display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; border-radius: 9px; background: #eef2ff; color: #4f46e5; font-size: 17px; }
|
||||
.experience-section-number { font-size: 11px; color: #9ca3af; font-weight: 400; }
|
||||
.experience-section-description { margin: 0 !important; color: #374151; min-height: 44px; }
|
||||
.experience-current { border-top: 1px solid #eef0f5; padding-top: 14px; }
|
||||
.experience-workspace-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; }
|
||||
.experience-workspace-heading h4 { margin: 0 0 6px; color: #111827; font-size: 18px; }
|
||||
.experience-publish-actions { display: flex; justify-content: space-between; gap: 16px; flex-wrap: wrap; align-items: center; }
|
||||
.experience-create-card .ant-card-head-title { white-space: normal; }
|
||||
.experience-create-card .ant-card-head { min-height: 80px; }
|
||||
.experience-create-intro { margin: 0 0 20px; color: #6b7280; }
|
||||
.experience-create-card { scroll-margin-top: 85px; }
|
||||
.project-fields-compact { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-areas: 'name type' 'description description' 'cover owner'; gap: 0 28px; }
|
||||
.project-fields-compact .project-field-name { grid-area: name; }
|
||||
.project-fields-compact .project-field-type { grid-area: type; }
|
||||
.project-fields-compact .project-field-description { grid-area: description; }
|
||||
.project-fields-compact .project-field-cover { grid-area: cover; }
|
||||
.project-fields-compact .project-field-owner { grid-area: owner; }
|
||||
@media (max-width: 1050px) { .experience-upload-grid { grid-template-columns: minmax(0, 1fr); } }
|
||||
@media (max-width: 640px) { .experience-workspace-heading { flex-direction: column; } }
|
||||
@media (max-width: 700px) { .project-fields-compact { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'name' 'type' 'description' 'cover' 'owner'; } }
|
||||
@@ -0,0 +1,25 @@
|
||||
.walking-workbench { display: flex; flex-direction: column; gap: 18px; min-width: 0; }
|
||||
.walking-form-heading { display: flex; gap: 12px; justify-content: space-between; align-items: center; flex-wrap: wrap; }
|
||||
.walking-form-heading > .ant-typography { font-size: 12px; }
|
||||
.walking-base-grid, .walking-feature-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
|
||||
.walking-form-field { padding: 14px; border: 1px solid #e6e8f3; border-radius: 9px; background: #fcfcff; min-width: 0; }
|
||||
.walking-form-field-title { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; margin-bottom: 8px; }
|
||||
.walking-form-field > .ant-typography { font-size: 12px; margin: 6px 0 12px; }
|
||||
.walking-field-file { margin-top: 8px; overflow-wrap: anywhere; }
|
||||
.walking-feature-card { border: 1px solid #e5e8f1; border-radius: 9px; padding: 14px; min-width: 0; background: #fafbfe; }
|
||||
.walking-feature-card.selected { border-color: #a99af0; background: #fdfcff; }
|
||||
.walking-feature-card > .ant-tag { float: right; margin-top: 2px; }
|
||||
.walking-feature-card .walking-form-field { padding: 10px; }
|
||||
.walking-feature-card .ant-space-item { min-width: 0; width: 100%; }
|
||||
.walking-base-skill { display: flex; flex-direction: column; gap: 8px; }
|
||||
.walking-base-skill .ant-typography { font-size: 12px; }
|
||||
.walking-shared-prop, .walking-feature-report, .walking-material-library { border: 1px solid #e6e8f3; border-radius: 9px; padding: 16px; min-width: 0; }
|
||||
.walking-shared-prop { background: #faf9ff; display: flex; flex-direction: column; gap: 14px; }
|
||||
.walking-prop-preset .ant-typography { margin: 8px 0; font-size: 12px; }
|
||||
.walking-prop-preset .ant-collapse { margin-top: 10px; }
|
||||
.walking-form-actions { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 12px; }
|
||||
.walking-feature-report > .ant-btn, .walking-feature-report > a { margin: 12px 12px 0 0; }
|
||||
.walking-feature-report small, .walking-material-library small { display: block; color: #8a5860; overflow-wrap: anywhere; }
|
||||
.walking-material-library > .ant-space { margin-top: 12px; }
|
||||
@media (max-width: 900px) { .walking-base-grid, .walking-feature-grid { grid-template-columns: minmax(0,1fr); } }
|
||||
@media (max-width: 600px) { .walking-form-field, .walking-shared-prop, .walking-feature-report, .walking-material-library { padding: 10px; } .walking-feature-card > .ant-tag { float: none; display: block; width: fit-content; margin-top: 8px; } .walking-workbench .ant-btn { max-width: 100%; height: auto; min-height: 34px; white-space: normal; } .walking-workbench .ant-select { min-width: 0; } }
|
||||
@@ -0,0 +1,64 @@
|
||||
.experience-upload-walking { grid-column: 1 / -1; }
|
||||
.experience-upload-walking .experience-section-description { min-height: 0; }
|
||||
.walking-upload-guide { min-width: 0; }
|
||||
.walking-template-heading { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
|
||||
.walking-template-heading .ant-typography, .walking-template-note { font-size: 12px; }
|
||||
.walking-upload-actions { margin: 14px 0; }
|
||||
.walking-upload-guide > .ant-alert { margin-bottom: 14px; }
|
||||
.walking-upload-columns { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 20px; align-items: start; }
|
||||
.walking-requirements, .walking-checklist { border: 1px solid #e8ebf3; border-radius: 10px; background: #fcfcff; padding: 16px; min-width: 0; }
|
||||
.walking-checklist { background: #fafbfe; }
|
||||
.walking-block-heading { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 12px; }
|
||||
.walking-block-heading > span { color: #8991a4; font-size: 12px; }
|
||||
.walking-requirement { display: grid; grid-template-columns: 125px minmax(0, 1fr); gap: 12px; padding: 12px 0; border-top: 1px solid #ebedf5; }
|
||||
.walking-requirement-name { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; font-size: 13px; }
|
||||
.walking-requirement small, .walking-policy-row small { display: block; color: #8891a5; font-size: 12px; line-height: 1.6; margin-top: 4px; }
|
||||
.walking-path.ant-typography { display: block; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; word-break: break-word; min-width: 0; }
|
||||
.walking-policy-requirements { margin: 4px 0 8px; }
|
||||
.walking-policy-title { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: 13px; }
|
||||
.walking-policy-title > span:last-child { color: #6250d7; font-size: 12px; }
|
||||
.walking-policy-row { border-bottom: 1px solid #e8ebf4; padding: 9px 0; }
|
||||
.walking-policy-row:last-child { border: 0; }
|
||||
.walking-policy-row strong { margin-right: 8px; font-size: 13px; }
|
||||
.walking-required-note.ant-typography { font-size: 12px; margin: 8px 0; }
|
||||
.walking-requirements .ant-alert { margin-top: 10px; font-size: 12px; }
|
||||
.walking-requirements > .ant-btn { white-space: normal; height: auto; padding-inline: 0; margin-top: 6px; text-align: left; }
|
||||
.walking-template-note.ant-typography { margin: 12px 0 0; }
|
||||
.walking-package-name { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; margin: 12px 0 4px; overflow-wrap: anywhere; }
|
||||
.walking-robot.ant-typography { font-size: 12px; overflow-wrap: anywhere; }
|
||||
.walking-stage-list { border: 1px solid #e8ebf3; background: #fff; border-radius: 8px; padding: 2px 12px; margin: 14px 0; }
|
||||
.walking-stage { display: flex; gap: 8px; flex-wrap: wrap; justify-content: space-between; padding: 7px 0; border-bottom: 1px solid #f0f1f7; font-size: 13px; }
|
||||
.walking-stage:last-child { border: 0; }
|
||||
.walking-stage small { width: 100%; color: #7c8497; }
|
||||
.walking-policy-summary { color: #5a4ab7; font-size: 12px; margin: 12px 0; }
|
||||
.walking-check-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; padding: 10px 0; border-bottom: 1px solid #e8ebf3; font-size: 13px; }
|
||||
.walking-check-row > .ant-tag { align-self: start; margin: 0; }
|
||||
.walking-check-row strong { font-weight: 500; }
|
||||
.walking-check-message, .walking-check-help { font-size: 12px; margin-top: 4px; overflow-wrap: anywhere; }
|
||||
.walking-check-help { color: #7c8497; }
|
||||
.walking-checklist > .ant-alert { margin-top: 12px; }
|
||||
.walking-checklist > .ant-btn { margin-top: 16px; }
|
||||
.walking-check-note.ant-typography { margin: 12px 0 0; font-size: 12px; }
|
||||
.walking-file-tree { padding: 16px; background: #f6f7fc; border: 1px solid #e5e8f2; border-radius: 10px; font-size: 12px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.walking-file-details { width: 100%; }
|
||||
.walking-file-details h4 { margin: 0 0 14px; }
|
||||
.walking-file-detail { margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #e8ebf4; }
|
||||
.walking-file-detail > .ant-typography.walking-path { margin-top: 6px; }
|
||||
.walking-file-detail p { margin: 6px 0; font-size: 13px; }
|
||||
@media (max-width: 950px) { .walking-upload-columns { grid-template-columns: minmax(0, 1fr); } }
|
||||
@media (max-width: 600px) { .walking-requirements, .walking-checklist { padding: 12px; } .walking-requirement { grid-template-columns: minmax(0, 1fr); gap: 6px; } .walking-requirement-name { flex-direction: row; align-items: center; } .walking-block-heading { flex-wrap: wrap; } .walking-check-row { gap: 6px; } .walking-file-tree { font-size: 10px; padding: 10px; } }
|
||||
@media (max-width: 600px) {
|
||||
.experience-upload-walking .ant-space-item { min-width: 0; max-width: 100%; }
|
||||
.walking-template-heading > .ant-tag { white-space: normal; overflow-wrap: anywhere; max-width: 100%; box-sizing: border-box; }
|
||||
.walking-upload-actions .ant-btn { max-width: 100%; white-space: normal; height: auto; min-height: 32px; }
|
||||
.walking-policy-title .ant-tag { white-space: normal; }
|
||||
}
|
||||
.walking-selection-actions { padding: 12px; border: 1px solid #e4def8; border-radius: 8px; margin-bottom: 16px; background: #fcfaff; }
|
||||
.walking-selection-actions .ant-table-cell { overflow-wrap: anywhere; }
|
||||
.walking-template-example { border: 1px solid #e6e8f2; border-radius: 8px; margin-top: 16px; padding: 16px; }
|
||||
.walking-template-example > .ant-space, .walking-template-example > .ant-btn { margin: 14px 0; }
|
||||
.walking-capabilities { padding: 12px; margin: 12px 0; border: 1px solid #e8ebf3; border-radius: 8px; background: #fff; }
|
||||
.walking-capability { margin-top: 8px; font-size: 13px; }
|
||||
.walking-capability small { display: block; color: #8790a6; }
|
||||
.walking-dependency-details { border: 1px solid #e6e8f2; border-radius: 8px; padding: 10px 12px; margin: 12px 0; font-size: 13px; }
|
||||
.walking-dependency-details > summary { cursor: pointer; overflow-wrap: anywhere; color: #6050c8; }
|
||||
@@ -9,6 +9,7 @@ export function pickFiles(opts: { directory?: boolean; multiple?: boolean; accep
|
||||
if (opts.accept) input.accept = opts.accept;
|
||||
if (opts.directory) input.setAttribute('webkitdirectory', '');
|
||||
input.onchange = () => resolve(Array.from(input.files ?? []));
|
||||
input.addEventListener('cancel', () => resolve([]), { once: true });
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,605 @@
|
||||
{
|
||||
"uiSpecVersion": 3,
|
||||
"status": "implementation_contract_not_integrated",
|
||||
"scope": "后台最低必传 + 选填功能,前台按已发布能力适配;这是交接配置,不是运行包或已上线接口。",
|
||||
"normativeDocument": "../admin-walking-upload-generic-spec.md",
|
||||
"defaultTitle": "行走演示",
|
||||
"defaultDescription": "基础行走只需准备下面四项。其他动作按需添加,不用全部上传。",
|
||||
"moduleOptional": true,
|
||||
"selectionMode": "explicit_capability_selection",
|
||||
"inferCapabilitiesFromRobotNameOrFilename": false,
|
||||
"currentBaselineMode": "mjcf_onnx",
|
||||
"minimumUploadSet": [
|
||||
{
|
||||
"id": "robot_config",
|
||||
"label": "机器人控制配置",
|
||||
"requirement": "required",
|
||||
"entry": "robot.json",
|
||||
"preparedBy": "机器人模型/算法工程提供;可由后台工具辅助配置",
|
||||
"contents": [
|
||||
"物理模型路径与依赖映射",
|
||||
"关节对应关系与默认姿态",
|
||||
"观测和动作契约",
|
||||
"执行器及控制时序",
|
||||
"基础行走技能",
|
||||
"渲染方式与输入绑定"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "physics_model",
|
||||
"label": "物理模型 XML",
|
||||
"requirement": "required",
|
||||
"format": "mjcf",
|
||||
"pathSource": "robot.model",
|
||||
"fixedFilename": false
|
||||
},
|
||||
{
|
||||
"id": "model_dependencies",
|
||||
"label": "模型引用文件",
|
||||
"requirement": "required_if_referenced",
|
||||
"contents": [
|
||||
"网格",
|
||||
"贴图",
|
||||
"include",
|
||||
"递归引用资源"
|
||||
],
|
||||
"fixedCount": null,
|
||||
"zeroFilesAllowedIfNoExternalReferences": true,
|
||||
"validation": "配置映射与物理模型 VFS 的完整依赖闭包"
|
||||
},
|
||||
{
|
||||
"id": "walk_policy",
|
||||
"label": "基础行走策略",
|
||||
"requirement": "required",
|
||||
"format": "onnx",
|
||||
"minimumPrimaryControllers": 1,
|
||||
"initialGenericPrimaryControllers": 1,
|
||||
"pathSource": "walk 能力绑定的 primary 技能 controller.policy",
|
||||
"fixedFilename": false,
|
||||
"validation": "同一机器人的控制配置、真实输入输出及运行效果匹配"
|
||||
}
|
||||
],
|
||||
"platformProvided": [
|
||||
{
|
||||
"id": "publish_manifest",
|
||||
"label": "发布清单",
|
||||
"source": "后台生成",
|
||||
"userUploadRequired": false,
|
||||
"contents": [
|
||||
"入口",
|
||||
"发布功能",
|
||||
"资源路径",
|
||||
"实际字节数",
|
||||
"SHA256",
|
||||
"版本"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "basic_scene",
|
||||
"label": "基础场景",
|
||||
"source": "平台内置",
|
||||
"userUploadRequired": false,
|
||||
"contents": [
|
||||
"地面",
|
||||
"灯光",
|
||||
"相机",
|
||||
"暂停与重置界面"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "football",
|
||||
"label": "标准足球",
|
||||
"source": "平台内置外观及固定版本物理预设",
|
||||
"userUploadRequired": false,
|
||||
"userConfigurationRequiredIfUsed": "选择与该策略兼容且已验证的预设"
|
||||
}
|
||||
],
|
||||
"notUniversallyRequired": [
|
||||
"整机 GLB",
|
||||
"kinematics.json",
|
||||
"单独 controller.json",
|
||||
"足球 GLB",
|
||||
"球场素材",
|
||||
"踢球策略",
|
||||
"翻滚策略",
|
||||
"起身策略",
|
||||
"训练源码",
|
||||
"训练日志"
|
||||
],
|
||||
"optionalCapabilities": [
|
||||
{
|
||||
"id": "head",
|
||||
"label": "头部摆动",
|
||||
"requires": [
|
||||
"对应头部关节组",
|
||||
"运行器支持的控制器及参数"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"policyRule": "controller=onnx 时引用策略必需;受支持的 oscillator 无需额外策略",
|
||||
"controls": [
|
||||
"头部摆动"
|
||||
],
|
||||
"props": [],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过"
|
||||
},
|
||||
{
|
||||
"id": "sit_stand",
|
||||
"label": "坐下/站起",
|
||||
"requires": [
|
||||
"支持的姿态动作及触发/结束规则",
|
||||
"对应控制配置及引用资源"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"controls": [
|
||||
"已验证的坐下/站起操作"
|
||||
],
|
||||
"props": [],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过",
|
||||
"policyRule": "所选控制器引用的策略必须提供;允许复用文件,不强制每项另传一个策略"
|
||||
},
|
||||
{
|
||||
"id": "roll",
|
||||
"label": "翻滚",
|
||||
"requires": [
|
||||
"翻滚控制配置及引用资源",
|
||||
"结束、取消与恢复行走规则"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"controls": [
|
||||
"翻滚"
|
||||
],
|
||||
"props": [],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过",
|
||||
"policyRule": "所选控制器引用的策略必须提供;允许复用文件,不强制每项另传一个策略"
|
||||
},
|
||||
{
|
||||
"id": "kick_left",
|
||||
"label": "左脚踢球",
|
||||
"requires": [
|
||||
"左脚踢球控制配置及引用资源",
|
||||
"与策略兼容的足球物理预设",
|
||||
"结束、取消与恢复行走规则"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"controls": [
|
||||
"左脚踢球"
|
||||
],
|
||||
"props": [
|
||||
"football"
|
||||
],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"doesNotRequire": [
|
||||
"kick_right",
|
||||
"自定义足球 GLB"
|
||||
],
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过",
|
||||
"policyRule": "所选控制器引用的策略必须提供;允许复用文件,不强制每项另传一个策略"
|
||||
},
|
||||
{
|
||||
"id": "kick_right",
|
||||
"label": "右脚踢球",
|
||||
"requires": [
|
||||
"右脚踢球控制配置及引用资源",
|
||||
"与策略兼容的足球物理预设",
|
||||
"结束、取消与恢复行走规则"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"controls": [
|
||||
"右脚踢球"
|
||||
],
|
||||
"props": [
|
||||
"football"
|
||||
],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"doesNotRequire": [
|
||||
"kick_left",
|
||||
"自定义足球 GLB"
|
||||
],
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过",
|
||||
"policyRule": "所选控制器引用的策略必须提供;允许复用文件,不强制每项另传一个策略"
|
||||
},
|
||||
{
|
||||
"id": "recovery",
|
||||
"label": "跌倒起身",
|
||||
"requires": [
|
||||
"起身控制配置及引用资源",
|
||||
"适用姿态、触发及结束规则"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"controls": [
|
||||
"起身"
|
||||
],
|
||||
"props": [],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"autoTriggerDefault": false,
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过",
|
||||
"policyRule": "所选控制器引用的策略必须提供;允许复用文件,不强制每项另传一个策略"
|
||||
},
|
||||
{
|
||||
"id": "ground_pick",
|
||||
"label": "俯身拾取",
|
||||
"requires": [
|
||||
"拾取控制配置及引用资源",
|
||||
"拾取对象的经验证物理配置和道具绑定",
|
||||
"结束、取消与恢复行走规则"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"controls": [
|
||||
"拾取"
|
||||
],
|
||||
"props": [
|
||||
"pickup_target"
|
||||
],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过",
|
||||
"policyRule": "所选控制器引用的策略必须提供;允许复用文件,不强制每项另传一个策略"
|
||||
},
|
||||
{
|
||||
"id": "rollers",
|
||||
"label": "滚轮行驶",
|
||||
"requires": [
|
||||
"滚轮物理模型或模型变体及引用资源",
|
||||
"滚轮行驶控制配置及引用策略",
|
||||
"模式切换和重置规则"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"controls": [
|
||||
"切换滚轮模式",
|
||||
"配置支持的滚轮控制"
|
||||
],
|
||||
"props": [],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"doesNotRequire": [
|
||||
"roller_crouch"
|
||||
],
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过",
|
||||
"policyRule": "所选控制器引用的策略必须提供;允许复用文件,不强制每项另传一个策略"
|
||||
},
|
||||
{
|
||||
"id": "roller_crouch",
|
||||
"label": "滚轮蹲伏",
|
||||
"requires": [
|
||||
"滚轮蹲伏控制配置及引用资源",
|
||||
"结束与恢复行驶规则"
|
||||
],
|
||||
"skillBinding": true,
|
||||
"controls": [
|
||||
"滚轮蹲伏"
|
||||
],
|
||||
"props": [],
|
||||
"dependsOn": [
|
||||
"rollers"
|
||||
],
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过",
|
||||
"policyRule": "所选控制器引用的策略必须提供;允许复用文件,不强制每项另传一个策略"
|
||||
},
|
||||
{
|
||||
"id": "visual_model",
|
||||
"label": "高精度显示模型",
|
||||
"requires": [
|
||||
"显示 GLB",
|
||||
"所选渲染器需要的节点/关节映射",
|
||||
"显示与物理模型的匹配检查"
|
||||
],
|
||||
"skillBinding": false,
|
||||
"renderBinding": "robot.render",
|
||||
"controls": [],
|
||||
"props": [],
|
||||
"dependsOn": [
|
||||
"walk"
|
||||
],
|
||||
"preserveSourceMaterials": true,
|
||||
"defaultSelected": false,
|
||||
"requirementWhenNotSelected": "none",
|
||||
"requirementWhenSelected": "该功能的控制配置和全部实际引用必须完整,且当前运行器支持并试运行通过"
|
||||
}
|
||||
],
|
||||
"featureBindingContract": {
|
||||
"controllerConfigRequired": true,
|
||||
"skillIdSource": "robot.skills[].id",
|
||||
"requiredSemantics": [
|
||||
"支持的控制器",
|
||||
"关节所有权",
|
||||
"观测与动作约定",
|
||||
"触发与退出条件",
|
||||
"取消/重置行为",
|
||||
"与基础行走的切换规则"
|
||||
],
|
||||
"barePolicyFileIsSufficient": false,
|
||||
"sharedPolicyFileAllowed": true,
|
||||
"uploadedExecutableCodeAllowed": false,
|
||||
"unsupportedControllerState": "needs_runtime_support"
|
||||
},
|
||||
"propRules": [
|
||||
{
|
||||
"id": "football",
|
||||
"enabledWhenAnyReady": [
|
||||
"kick_left",
|
||||
"kick_right"
|
||||
],
|
||||
"maximumInstances": 1,
|
||||
"platformDefaultVisual": true,
|
||||
"physicsPresetRequired": true,
|
||||
"physicsPresetVersionRequired": true,
|
||||
"bothKicksMustShareCompatiblePhysics": true,
|
||||
"customVisualUploadOptional": true,
|
||||
"customVisualEnablesKick": false,
|
||||
"relatedControls": [
|
||||
"重置球",
|
||||
"球视角(若播放器提供)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "pickup_target",
|
||||
"enabledWhenAnyReady": [
|
||||
"ground_pick"
|
||||
],
|
||||
"physicsBindingRequired": true,
|
||||
"canShareFootballWhenExplicitlyBoundAndValidated": true
|
||||
}
|
||||
],
|
||||
"uploadFlow": {
|
||||
"primary": "individual_slots",
|
||||
"alternative": "zip_import_to_same_draft",
|
||||
"zipIsNotExecutable": true,
|
||||
"relativePathsPreserved": true,
|
||||
"extraUnboundFiles": "保留草稿,不启用动作,不进入发布依赖,不由前台加载",
|
||||
"manifestGeneratedByBackend": true,
|
||||
"unselectedCapabilities": "不产生缺资源错误",
|
||||
"selectedInvalidCapabilities": "留草稿;用户明确选择仅发布已通过功能后,重新编译并校验所选配置",
|
||||
"sharedBaseDependencyFailure": "基础失败,不能当作单个选填功能失败跳过"
|
||||
},
|
||||
"validation": {
|
||||
"scopes": [
|
||||
"base",
|
||||
"feature"
|
||||
],
|
||||
"reportFields": [
|
||||
"scope",
|
||||
"capabilityId",
|
||||
"code",
|
||||
"path",
|
||||
"status",
|
||||
"message",
|
||||
"assetVersion"
|
||||
],
|
||||
"stages": [
|
||||
"uploaded",
|
||||
"files_valid",
|
||||
"control_contract_valid",
|
||||
"runtime_supported",
|
||||
"runtime_verified",
|
||||
"published"
|
||||
],
|
||||
"errorCodes": [
|
||||
"BASE_FILE_MISSING",
|
||||
"FEATURE_FILE_MISSING",
|
||||
"RESOURCE_IS_LFS_POINTER",
|
||||
"CONFIG_REFERENCE_INVALID",
|
||||
"POLICY_CONTRACT_MISMATCH",
|
||||
"RUNTIME_CAPABILITY_UNSUPPORTED",
|
||||
"FEATURE_DEPENDENCY_MISSING",
|
||||
"PROP_CONFIG_CONFLICT",
|
||||
"RUNTIME_PREVIEW_FAILED"
|
||||
],
|
||||
"publishedRevisionImmutable": true,
|
||||
"newUploadsInvalidateOldReport": true,
|
||||
"preservePreviousPublicationOnFailure": true
|
||||
},
|
||||
"publishContract": {
|
||||
"status": "proposed_not_implemented",
|
||||
"projectField": "walkingManifestUrl",
|
||||
"noDemoValue": null,
|
||||
"schemaVersion": 2,
|
||||
"kind": "walking",
|
||||
"runtimeProfile": "robot-package-v1",
|
||||
"entry": "robot.json",
|
||||
"autoWalk": false,
|
||||
"capabilities": {
|
||||
"minimum": [
|
||||
"walk"
|
||||
],
|
||||
"uniqueIds": true,
|
||||
"onlyValidatedSelectedFeatures": true,
|
||||
"skillBindingsMustResolve": true
|
||||
},
|
||||
"props": "由已发布能力及经验证的道具绑定生成,含固定版本物理预设;踢球共享唯一 football",
|
||||
"files": {
|
||||
"mustNotBeEmpty": true,
|
||||
"fields": [
|
||||
"path",
|
||||
"bytes",
|
||||
"sha256"
|
||||
],
|
||||
"scope": "入口 + 基础 + 已发布选填功能的完整依赖;共享路径去重"
|
||||
},
|
||||
"exampleHeaderOnlyNotRunnable": {
|
||||
"schemaVersion": 2,
|
||||
"kind": "walking",
|
||||
"runtimeProfile": "robot-package-v1",
|
||||
"entry": "robot.json",
|
||||
"autoWalk": false,
|
||||
"capabilities": [
|
||||
{
|
||||
"id": "walk",
|
||||
"skillIds": [
|
||||
"walk"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "head",
|
||||
"skillIds": [
|
||||
"head"
|
||||
]
|
||||
}
|
||||
],
|
||||
"props": [],
|
||||
"files": []
|
||||
}
|
||||
},
|
||||
"frontendRules": {
|
||||
"availability": "按已发布且验证通过的能力与运行器支持生成操作;未下载显示待加载操作,加载完成才执行,失败时停用",
|
||||
"loadBaseBeforeOptionalPolicies": true,
|
||||
"optionalPolicies": "按需加载和缓存;使用前有加载状态",
|
||||
"optionalFetchFailure": "只停用对应功能和无其他使用者的道具;基础资源完好时继续可用",
|
||||
"actionExecutionFailure": "按已验证的退出逻辑恢复;无法恢复时暂停并重置",
|
||||
"autoWalk": false,
|
||||
"autoRunOptionalActions": false,
|
||||
"clearInputOnBlurHideCloseCancel": true,
|
||||
"controlsFromConfiguredAxesAndCapabilities": true,
|
||||
"mobileOverflowActions": "更多动作面板",
|
||||
"performance": [
|
||||
"限制渲染分辨率和像素比",
|
||||
"可选策略懒加载",
|
||||
"关闭/离屏暂停",
|
||||
"释放场景和推理资源",
|
||||
"不随意修改控制步长或策略频率"
|
||||
],
|
||||
"preserveGlbMaterialsAndColors": true
|
||||
},
|
||||
"acceptanceScenarios": [
|
||||
{
|
||||
"id": "base_only",
|
||||
"capabilities": [
|
||||
"walk"
|
||||
],
|
||||
"expectedExtraControls": [],
|
||||
"expectedProps": [],
|
||||
"missingOptionalPoliciesAllowed": true
|
||||
},
|
||||
{
|
||||
"id": "walk_head",
|
||||
"capabilities": [
|
||||
"walk",
|
||||
"head"
|
||||
],
|
||||
"headController": "oscillator",
|
||||
"extraOnnxRequired": false,
|
||||
"expectedExtraControls": [
|
||||
"头部摆动"
|
||||
],
|
||||
"expectedProps": []
|
||||
},
|
||||
{
|
||||
"id": "left_kick_only",
|
||||
"capabilities": [
|
||||
"walk",
|
||||
"kick_left"
|
||||
],
|
||||
"expectedExtraControls": [
|
||||
"左脚踢球",
|
||||
"重置球"
|
||||
],
|
||||
"expectedProps": [
|
||||
"football"
|
||||
],
|
||||
"mustNotShow": [
|
||||
"右脚踢球"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "both_kicks",
|
||||
"capabilities": [
|
||||
"walk",
|
||||
"kick_left",
|
||||
"kick_right"
|
||||
],
|
||||
"expectedExtraControls": [
|
||||
"左脚踢球",
|
||||
"右脚踢球",
|
||||
"重置球"
|
||||
],
|
||||
"expectedProps": [
|
||||
"football"
|
||||
],
|
||||
"footballCount": 1
|
||||
},
|
||||
{
|
||||
"id": "roll_without_kick",
|
||||
"capabilities": [
|
||||
"walk",
|
||||
"roll"
|
||||
],
|
||||
"expectedExtraControls": [
|
||||
"翻滚"
|
||||
],
|
||||
"expectedProps": []
|
||||
}
|
||||
],
|
||||
"currentImplementation": {
|
||||
"community": "旧 Microduck v1,尚未接入上述发布契约",
|
||||
"downloadedGeneric": "一个 ONNX primary + 不重叠关节的 oscillator overlays;其他动作需运行器适配",
|
||||
"downloadedMicroduck": "声明 9 个策略,旧基础启动依赖 7 个;需要拆分可选依赖才能只传基础行走",
|
||||
"legacyV1CompatibilityRetained": true,
|
||||
"newContractDoesNotRelaxLegacyLoaderAutomatically": true,
|
||||
"dynamicAssetUrlsAndMobileIntegration": "pending"
|
||||
},
|
||||
"sourceExamples": [
|
||||
{
|
||||
"id": "microban",
|
||||
"configExample": "microban.robot.json",
|
||||
"baseOnnxCount": 1,
|
||||
"modelMeshReferences": 25,
|
||||
"optionalHeadUses": "oscillator",
|
||||
"glbRequired": false,
|
||||
"separateKinematicsRequired": false,
|
||||
"separateControllerJsonRequired": false,
|
||||
"downloadedState": "contains_26_lfs_pointers_not_runnable",
|
||||
"inspection": "microban-download-inspection.json"
|
||||
},
|
||||
{
|
||||
"id": "microduck-legs",
|
||||
"status": "legacy_coupling_requires_refactor",
|
||||
"declaredOnnxPolicyCount": 9,
|
||||
"coreStartupPolicyCount": 7,
|
||||
"notGlobalUploadRequirements": true
|
||||
}
|
||||
],
|
||||
"uiLabels": {
|
||||
"required": "必传",
|
||||
"referenced": "有引用必传",
|
||||
"optional": "选填",
|
||||
"builtIn": "内置控制器,无需策略文件",
|
||||
"generated": "系统生成,无需上传",
|
||||
"unbound": "未用于展示",
|
||||
"unsupported": "需要播放器适配",
|
||||
"selectedOnly": "已选择,尚未上传"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
{
|
||||
"uiSpecVersion": 1,
|
||||
"purpose": "仅供旧版 Microduck v1 兼容模板;不得作为所有机器人的默认要求,不代表已接通的检查结果。",
|
||||
"title": "Microduck 鸭子行走演示",
|
||||
"robotId": "microduck-alpha",
|
||||
"runtimeProfile": "microduck-alpha-v1",
|
||||
"recommendedInitialMode": "zip-with-visible-checklist",
|
||||
"intro": "上传与 Microduck 匹配的行走资源包。模型、物理配置和动作策略需要配套,只有一个 GLB 文件不能生成行走演示。",
|
||||
"requiredFiles": [
|
||||
{
|
||||
"id": "model",
|
||||
"label": "运动模型",
|
||||
"path": "robot/mjlab/microduck.glb",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "模型人员/已验证演示工程",
|
||||
"help": "运动模型内部网格名称必须与物理配置和运动映射匹配,不能用任意整机 GLB 替换。"
|
||||
},
|
||||
{
|
||||
"id": "physics",
|
||||
"label": "物理配置",
|
||||
"path": "robot/mjlab/robot_allcollisions.xml",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "机器人/算法人员",
|
||||
"help": "MJCF 格式,定义关节、碰撞与执行器;URDF 改扩展名不能替代。"
|
||||
},
|
||||
{
|
||||
"id": "kinematics",
|
||||
"label": "运动映射",
|
||||
"path": "robot/mjlab/kinematics.json",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "同一模型的导出工具",
|
||||
"help": "关联关节与显示模型,必须和物理模型配套。"
|
||||
},
|
||||
{
|
||||
"id": "walk",
|
||||
"label": "行走策略",
|
||||
"path": "policies/BEST_alpha_walking.onnx",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "算法人员/已验证演示工程",
|
||||
"help": "控制行走动作。当前运行器启动时必需。"
|
||||
},
|
||||
{
|
||||
"id": "sitstand",
|
||||
"label": "起坐策略",
|
||||
"path": "policies/BEST_alpha_sitstand.onnx",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "算法人员/已验证演示工程",
|
||||
"help": "控制起坐动作。当前运行器启动时必需。"
|
||||
},
|
||||
{
|
||||
"id": "roll",
|
||||
"label": "翻滚策略",
|
||||
"path": "policies/roulade.onnx",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "算法人员/已验证演示工程",
|
||||
"help": "控制翻滚动作。当前运行器启动时必需。"
|
||||
},
|
||||
{
|
||||
"id": "kickL",
|
||||
"label": "左脚踢球策略",
|
||||
"path": "policies/ball_kick_left.onnx",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "算法人员/已验证演示工程",
|
||||
"help": "控制左脚踢球动作。当前运行器启动时必需。"
|
||||
},
|
||||
{
|
||||
"id": "kickR",
|
||||
"label": "右脚踢球策略",
|
||||
"path": "policies/ball_kick_right.onnx",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "算法人员/已验证演示工程",
|
||||
"help": "控制右脚踢球动作。当前运行器启动时必需。"
|
||||
},
|
||||
{
|
||||
"id": "groundpick",
|
||||
"label": "俯身拾取策略",
|
||||
"path": "policies/alpha_ground_pick.onnx",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "算法人员/已验证演示工程",
|
||||
"help": "控制俯身拾取动作。当前运行器启动时必需。"
|
||||
},
|
||||
{
|
||||
"id": "stand",
|
||||
"label": "起身恢复策略",
|
||||
"path": "policies/BEST_alpha_stand.onnx",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "算法人员/已验证演示工程",
|
||||
"help": "用于起身恢复。当前运行器启动时必需。"
|
||||
},
|
||||
{
|
||||
"id": "controller",
|
||||
"label": "控制配置",
|
||||
"path": "controller.json",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "已验证的对应模板或算法人员",
|
||||
"help": "最终包必备。逐项打包时可选标准模板,但不能根据策略维度猜测关节顺序或控制语义。"
|
||||
},
|
||||
{
|
||||
"id": "manifest",
|
||||
"label": "文件清单",
|
||||
"path": "manifest.json",
|
||||
"requiredInFinalPackage": true,
|
||||
"preparedBy": "配套打包工具/后台",
|
||||
"help": "最终包必备。完整 ZIP 导入时应已包含;逐项打包功能接通后由系统生成真实文件索引和哈希。"
|
||||
}
|
||||
],
|
||||
"dependencyGroups": [
|
||||
{
|
||||
"id": "meshes",
|
||||
"label": "网格依赖",
|
||||
"path": "robot/mjlab/meshes/",
|
||||
"rule": "每个几何引用均可解析;GLB 已提供对应命名几何时运行器可在内存重建 STL,否则读取对应网格文件。",
|
||||
"userHelp": "请保留原演示工程的 meshes 文件夹,由系统按引用检查,不需要手工数文件。"
|
||||
},
|
||||
{
|
||||
"id": "assets",
|
||||
"label": "模板配套素材",
|
||||
"path": "assets/",
|
||||
"rule": "本期保留完整模板内容,不把未审计的资源标成可删除。",
|
||||
"userHelp": "音效、图片等随完整示例提供,无需逐个制作。"
|
||||
},
|
||||
{
|
||||
"id": "provenance",
|
||||
"label": "来源与使用说明",
|
||||
"paths": [
|
||||
"LICENSE",
|
||||
"NOTICE",
|
||||
"UPSTREAM.md",
|
||||
"README.txt"
|
||||
],
|
||||
"rule": "保留所用资源对应的许可与来源说明。",
|
||||
"userHelp": "沿用模板说明;其他来源资源保留自己的来源文件。"
|
||||
}
|
||||
],
|
||||
"optionalExtension": {
|
||||
"label": "滚轮扩展",
|
||||
"requiredForBaseDemo": false,
|
||||
"paths": [
|
||||
"policies/BEST_roller.onnx",
|
||||
"policies/BEST_roller_crouch.onnx",
|
||||
"robot/mjlab/robot_allcollisions_rollers.xml",
|
||||
"robot/mjlab/kinematics_rollers.json"
|
||||
],
|
||||
"help": "当前完整示例附带,基础七策略启动不要求;导入后保留,不自动删除。"
|
||||
},
|
||||
"validationStages": [
|
||||
{
|
||||
"id": "identify",
|
||||
"label": "文件识别"
|
||||
},
|
||||
{
|
||||
"id": "integrity",
|
||||
"label": "资源完整性"
|
||||
},
|
||||
{
|
||||
"id": "compatibility",
|
||||
"label": "运行器兼容性"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"label": "实际试运行"
|
||||
},
|
||||
{
|
||||
"id": "review",
|
||||
"label": "预览确认"
|
||||
}
|
||||
],
|
||||
"itemStates": [
|
||||
"not_checked",
|
||||
"found_pending_validation",
|
||||
"missing",
|
||||
"checking",
|
||||
"passed",
|
||||
"mismatch",
|
||||
"runtime_failed"
|
||||
],
|
||||
"fixedControllerReference": {
|
||||
"schemaVersion": 1,
|
||||
"runtimeProfile": "microduck-alpha-v1",
|
||||
"observationLayout": "angular-velocity,projected-gravity,joint-position-offset,joint-velocity,previous-action,command",
|
||||
"observationSize": 61,
|
||||
"actionSize": 14,
|
||||
"commandSize": 13,
|
||||
"jointNames": [
|
||||
"left_hip_yaw",
|
||||
"left_hip_roll",
|
||||
"left_hip_pitch",
|
||||
"left_knee",
|
||||
"left_ankle",
|
||||
"neck_pitch",
|
||||
"head_pitch",
|
||||
"head_yaw",
|
||||
"head_roll",
|
||||
"right_hip_yaw",
|
||||
"right_hip_roll",
|
||||
"right_hip_pitch",
|
||||
"right_knee",
|
||||
"right_ankle"
|
||||
],
|
||||
"defaultPose": [
|
||||
0,
|
||||
-0.0872664600610733,
|
||||
-0.4579240083694458,
|
||||
-0.004939999897032976,
|
||||
0.4529840052127838,
|
||||
0.3490658402442932,
|
||||
0.3490658402442932,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0.0872664600610733,
|
||||
0.4579240083694458,
|
||||
0.004939999897032976,
|
||||
-0.4529840052127838
|
||||
],
|
||||
"actionMode": "position-offset",
|
||||
"actionScale": 1,
|
||||
"physicsTimestep": 0.005,
|
||||
"controlDecimation": 4,
|
||||
"actuatorParameters": "mjcf"
|
||||
},
|
||||
"autoWalk": false,
|
||||
"example": {
|
||||
"fileName": "microduck-walking.zip",
|
||||
"zipBytes": 12786579,
|
||||
"zipSha256": "7114a32b7a3e7b6264312e83dc88aa9d38760230c866eacdeadf9fba3e59bcd4",
|
||||
"manifestEntryCount": 164,
|
||||
"basePolicyCount": 7,
|
||||
"extraRollerPolicyCount": 2,
|
||||
"note": "本示例的数量与大小不作为所有包的固定验收条件。"
|
||||
}
|
||||
}
|
||||
+52
-14
@@ -1,11 +1,17 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { App, Button, Card, Form, Space } from 'antd';
|
||||
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Card, Form, Space, Typography } from 'antd';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { TypeView } from '@/api/types';
|
||||
import ProjectFields from '@/components/ProjectFields';
|
||||
import OwnerSelect from '@/components/OwnerSelect';
|
||||
import { errorText } from '@/utils/format';
|
||||
import ModelAssetUpload from '@/components/project/experiences/ModelAssetUpload';
|
||||
import { emptyExperienceFiles, experienceFileSections, queueExperienceFiles } from '@/utils/experienceFiles';
|
||||
import { assemblyManifest, prepareAssemblySession, queueAssemblySession, stageAssemblyFiles, type AssemblySession } from '@/utils/assemblyEditor';
|
||||
import WalkingFolderUpload from '@/components/project/experiences/WalkingFolderUpload';
|
||||
|
||||
const AssemblyEditor = lazy(() => import('@/components/project/experiences/AssemblyEditor'));
|
||||
|
||||
export default function ProjectCreatePage() {
|
||||
const navigate = useNavigate();
|
||||
@@ -13,39 +19,71 @@ export default function ProjectCreatePage() {
|
||||
const [form] = Form.useForm();
|
||||
const [types, setTypes] = useState<TypeView[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [files, setFiles] = useState(emptyExperienceFiles);
|
||||
const [plan, setPlan] = useState<AssemblySession | null>(null);
|
||||
const [editor, setEditor] = useState<AssemblySession | null>(null);
|
||||
const [openingEditor, setOpeningEditor] = useState(false);
|
||||
const creating = useRef(false);
|
||||
const [fileError, setFileError] = useState('');
|
||||
const hasFiles = experienceFileSections.some((section) => files[section].selected.length);
|
||||
const checking = experienceFileSections.some((section) => files[section].checking);
|
||||
|
||||
useEffect(() => {
|
||||
api.listProjectTypes().then(setTypes).catch((e) => message.error(errorText(e)));
|
||||
}, [message]);
|
||||
|
||||
const onFinish = async (v: { name: string; description?: string; projectType: string; coverUrl?: string; ownerUserCode?: string }) => {
|
||||
if (creating.current || checking) return;
|
||||
if (experienceFileSections.some((section) => files[section].problems.length)) {
|
||||
setFileError('请先修正下方已选模型或演示文件的格式,再创建项目。');
|
||||
return;
|
||||
}
|
||||
creating.current = true;
|
||||
setFileError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const p = await api.createProject(
|
||||
{ name: v.name.trim(), description: v.description ?? '', projectType: v.projectType, coverUrl: v.coverUrl || null },
|
||||
v.ownerUserCode,
|
||||
);
|
||||
message.success('项目已创建(未发布),可上传文件');
|
||||
navigate(`/projects/${p.projectCode}`, { replace: true });
|
||||
if (hasFiles) queueExperienceFiles(p.projectCode, files);
|
||||
if (plan) queueAssemblySession(p.projectCode, plan);
|
||||
message.success(hasFiles ? '项目已创建,仓库就绪后将自动上传已选文件' : '项目已创建(未发布),可继续添加装配与仿真');
|
||||
navigate(`/projects/${p.projectCode}?tab=experiences`, { replace: true });
|
||||
window.scrollTo(0, 0);
|
||||
} catch (e) {
|
||||
message.error(errorText(e));
|
||||
} finally {
|
||||
creating.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card title={<Space><a onClick={() => navigate('/projects')}>项目管理</a>/<span>新建项目</span></Space>}>
|
||||
<Form form={form} layout="vertical" style={{ maxWidth: 720 }} onFinish={onFinish}>
|
||||
<ProjectFields types={types} />
|
||||
<Form.Item name="ownerUserCode" label="归属" extra="创建后不支持变更归属">
|
||||
<OwnerSelect />
|
||||
</Form.Item>
|
||||
<Form form={form} layout="vertical" onFinish={onFinish} disabled={loading}>
|
||||
<Card className="page-card" title={<Space><a onClick={() => navigate('/projects')}>项目管理</a>/<span>新建项目</span></Space>}
|
||||
extra={<Button type="link" onClick={() => document.getElementById('new-project-models')?.scrollIntoView({ behavior: 'smooth', block: 'start' })}>添加装配与仿真 ↓</Button>}>
|
||||
<ProjectFields types={types} compact extraFields={<Form.Item name="ownerUserCode" label="归属" extra="创建后不支持变更归属"><OwnerSelect /></Form.Item>} />
|
||||
</Card>
|
||||
<Card id="new-project-models" className="page-card experience-create-card" title={<div><span>装配与仿真文件</span><Typography.Paragraph type="secondary" style={{ fontWeight: 400, fontSize: 13, margin: '5px 0 0' }}>整机和零件分别上传,四项内容都可在这里选择,也可以创建后再补充。</Typography.Paragraph></div>}>
|
||||
<p className="experience-create-intro">先在下方选好文件,点击“创建项目并继续上传”后会直接进入模型管理,仓库就绪后自动上传已选文件。项目不会自动发布到前台。</p>
|
||||
<ModelAssetUpload resourceProtocol mode="create" value={files} onChange={setFiles} busy={loading || openingEditor}
|
||||
renderWalking={() => <WalkingFolderUpload selected={files.walking.selected} busy={loading} onChange={selected => setFiles(old => ({ ...old, walking: { ...old.walking, selected } }))} />}
|
||||
configured={{ assembly: !!plan }} onEditAssembly={async () => {
|
||||
setOpeningEditor(true);
|
||||
try { setEditor(await prepareAssemblySession(plan, plan?.assembly ?? null, [], files)); }
|
||||
catch (cause) { message.error(errorText(cause)); }
|
||||
finally { setOpeningEditor(false); }
|
||||
}} renderCurrent={(section) => section === 'assembly' && plan ? <Typography.Text type="success">已制作 {plan.assembly.steps.length} 个步骤,创建项目后会保留。</Typography.Text> : null} />
|
||||
</Card>
|
||||
{editor && <Suspense fallback={<Alert type="info" message="正在打开装配编辑器…" />}><AssemblyEditor saveHint="保存后自动生成 JSON;创建项目并就绪后自动上传。" initial={editor} onClose={() => setEditor(null)} onSave={(session) => { const generated = new File([JSON.stringify(assemblyManifest(session.assembly, session.sources), null, 2)], 'assembly.json', { type: 'application/json' }); const next = stageAssemblyFiles(session, files); setFiles({ ...next, assembly: { ...next.assembly, selected: [{ file: generated, relativePath: generated.name }], problems: [] } }); setPlan(session); setEditor(null); message.success('装配流程已生成,创建项目并就绪后自动上传并绑定'); }} /></Suspense>}
|
||||
<Card className="page-card">
|
||||
{fileError && <Alert type="error" showIcon message={fileError} style={{ marginBottom: 16 }} />}
|
||||
<Space>
|
||||
<Button type="primary" htmlType="submit" loading={loading}>创建</Button>
|
||||
<Button onClick={() => navigate(-1)}>取消</Button>
|
||||
<Button type="primary" htmlType="submit" loading={loading || checking} disabled={checking}>创建项目并继续上传</Button>
|
||||
<Button disabled={loading} onClick={() => navigate(-1)}>取消</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
</Card>
|
||||
</Card>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
+38
-13
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { lazy, Suspense, useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
@@ -16,9 +16,10 @@ import {
|
||||
Tabs,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom';
|
||||
import * as api from '@/api';
|
||||
import type { ManagedProjectView, TaskView, TypeView } from '@/api/types';
|
||||
import type { ExperienceBuild } from '@/api/experience-types';
|
||||
import { AdminApiError } from '@/api/request';
|
||||
import StatusTag from '@/components/StatusTag';
|
||||
import ImportTaskActions from '@/components/ImportTaskActions';
|
||||
@@ -37,16 +38,22 @@ import {
|
||||
repoStatusLabel,
|
||||
} from '@/utils/labels';
|
||||
|
||||
const ProjectResourcesPanel = lazy(() => import('@/components/project/experiences/ProjectResourcesPanel'));
|
||||
const ExperiencePanel = lazy(() => import('@/components/project/experiences/ExperiencePanel'));
|
||||
|
||||
export default function ProjectDetailPage() {
|
||||
const { projectCode = '' } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { message } = App.useApp();
|
||||
const [data, setData] = useState<ManagedProjectView | null>(null);
|
||||
const [types, setTypes] = useState<TypeView[]>([]);
|
||||
const [tasks, setTasks] = useState<TaskView[]>([]);
|
||||
const [tab, setTab] = useState('files');
|
||||
const [tab, setTab] = useState(() => searchParams.get('tab') === 'experiences' ? 'experiences' : 'files');
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [experienceBuild, setExperienceBuild] = useState<ExperienceBuild | null>(null);
|
||||
const [experienceRefresh, setExperienceRefresh] = useState(0);
|
||||
const [blocking, setBlocking] = useState(false);
|
||||
const [snapshot, setSnapshot] = useState<string | undefined>();
|
||||
const [historyKey, setHistoryKey] = useState(0);
|
||||
@@ -55,6 +62,7 @@ export default function ProjectDetailPage() {
|
||||
try {
|
||||
const d = await api.getProject(projectCode);
|
||||
setData(d);
|
||||
if (d.project.repoStatus !== 'READY') setTab((current) => current === 'files' ? 'experiences' : current);
|
||||
// 仅仓库未就绪或迁移来的项目才需要展示迁移任务
|
||||
if (d.project.repoStatus !== 'READY' || d.project.sourceRepositoryUrl) {
|
||||
api.listImports({ projectCode, page: 1, size: 10 }).then((r) => setTasks(r.items)).catch(() => {});
|
||||
@@ -74,6 +82,14 @@ 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="加载装配与仿真" />}>
|
||||
{'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}
|
||||
onProjectRefresh={load}
|
||||
onPublish={(build) => { setExperienceBuild(build); setPublishing(true); }}
|
||||
/>}
|
||||
</Suspense>;
|
||||
|
||||
const act = async (fn: () => Promise<unknown>, ok: string) => {
|
||||
try {
|
||||
@@ -107,7 +123,7 @@ export default function ProjectDetailPage() {
|
||||
<Space wrap>
|
||||
<Button onClick={() => setEditing(true)}>编辑信息</Button>
|
||||
{ready && !blocked && (
|
||||
<Button type="primary" onClick={() => setPublishing(true)}>
|
||||
<Button type="primary" onClick={() => { setExperienceBuild(null); setPublishing(true); }}>
|
||||
{p.publishStatus === 'PUBLISHED' ? '更新发布' : '发布'}
|
||||
</Button>
|
||||
)}
|
||||
@@ -206,12 +222,12 @@ export default function ProjectDetailPage() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{ready && (
|
||||
<Card className="page-card">
|
||||
<Tabs
|
||||
activeKey={tab}
|
||||
activeKey={ready ? tab : 'experiences'}
|
||||
onChange={setTab}
|
||||
items={[
|
||||
...(ready ? [
|
||||
{
|
||||
key: 'files',
|
||||
label: '文件',
|
||||
@@ -259,11 +275,12 @@ export default function ProjectDetailPage() {
|
||||
/>
|
||||
),
|
||||
},
|
||||
...(tasks.length ? [{ key: 'imports', label: '迁移任务', children: <ImportTaskTable tasks={tasks} /> }] : []),
|
||||
] : []),
|
||||
{ key: 'experiences', label: '装配与仿真', children: experiences },
|
||||
...(ready && tasks.length ? [{ key: 'imports', label: '迁移任务', children: <ImportTaskTable tasks={tasks} /> }] : []),
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<EditProjectModal
|
||||
project={p}
|
||||
@@ -276,8 +293,9 @@ export default function ProjectDetailPage() {
|
||||
open={publishing}
|
||||
projectCode={p.projectCode}
|
||||
publishedSha={p.publishedCommitSha}
|
||||
onClose={() => setPublishing(false)}
|
||||
onDone={() => { setPublishing(false); load(); setHistoryKey((k) => k + 1); }}
|
||||
experienceBuild={experienceBuild}
|
||||
onClose={() => { setPublishing(false); setExperienceBuild(null); }}
|
||||
onDone={() => { setPublishing(false); setExperienceBuild(null); load(); setHistoryKey((k) => k + 1); setExperienceRefresh((key) => key + 1); }}
|
||||
/>
|
||||
<BlockModal
|
||||
open={blocking}
|
||||
@@ -318,12 +336,14 @@ function PublishModal({
|
||||
open,
|
||||
projectCode,
|
||||
publishedSha,
|
||||
experienceBuild,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
open: boolean;
|
||||
projectCode: string;
|
||||
publishedSha: string | null;
|
||||
experienceBuild: ExperienceBuild | null;
|
||||
onClose: () => void;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
@@ -348,7 +368,10 @@ function PublishModal({
|
||||
if (!sha) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
await api.publishProject(projectCode, sha);
|
||||
await api.publishProject(projectCode, sha, experienceBuild ? {
|
||||
experienceBuildId: experienceBuild.buildId,
|
||||
expectedDraftRevision: experienceBuild.draftRevision,
|
||||
} : undefined);
|
||||
message.success('发布成功');
|
||||
onDone();
|
||||
} catch (e) {
|
||||
@@ -372,8 +395,10 @@ function PublishModal({
|
||||
>
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Typography.Paragraph>
|
||||
将把当前 <b>main</b> 工作区版本发布到社区。请先在「文件」中检查内容,发布后再提交的文件不会自动更新社区版本。
|
||||
将把当前 <b>main</b> 工作区版本发布到社区。请先检查文件{experienceBuild ? '及本次装配与仿真预览' : ''},后续修改不会自动更新发布版本。
|
||||
</Typography.Paragraph>
|
||||
{experienceBuild ? <Alert type="info" showIcon message={`本次原子发布代码及资源版本 ${experienceBuild.buildId}(草稿 ${experienceBuild.draftRevision})`} />
|
||||
: <Alert type="info" showIcon message="本次只更新代码,保留当前已发布的装配与仿真。发布新资源请在“装配与仿真”中生成版本并点击“发布此资源版本”。" />}
|
||||
<Descriptions column={1} bordered size="small">
|
||||
<Descriptions.Item label="待发布版本">
|
||||
{sha ? <Typography.Text className="mono" copyable>{sha}</Typography.Text> : error ? '—' : <Spin size="small" />}
|
||||
@@ -382,7 +407,7 @@ function PublishModal({
|
||||
<span className="mono">{publishedSha ?? '—'}</span>
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
{sha && sha === publishedSha && <Alert type="info" showIcon message="该版本已是当前发布版本" />}
|
||||
{sha && sha === publishedSha && <Alert type="info" showIcon message={experienceBuild ? '代码版本未变化,本次仍会发布新的装配与仿真快照' : '该版本已是当前发布版本'} />}
|
||||
{conflict && <Alert type="warning" showIcon message="工作区版本已变化,请点击「刷新版本」并重新检查后再发布" />}
|
||||
{error && !conflict && <Alert type="error" showIcon message={error} />}
|
||||
</Space>
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import type { AssemblyPart, ExperienceDraftContent, ModelAsset, Vector3 } from '@/api/experience-types';
|
||||
import type { ExperienceFileSelections } from './experienceFiles';
|
||||
import { experiencePathProblem } from './modelAssets';
|
||||
|
||||
export type Assembly = NonNullable<ExperienceDraftContent['assembly']>;
|
||||
export interface AssemblySource { asset: ModelAsset; file?: File }
|
||||
export interface AssemblySession { assembly: Assembly; sources: AssemblySource[]; reference?: AssemblySource }
|
||||
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);
|
||||
export function entryOffset(side: EntrySide, millimeters: number): Vector3 {
|
||||
const offset: Vector3 = [0, 0, 0];
|
||||
offset[['x', 'y', 'z'].indexOf(side[0])] = millimeters / 1000 * (side[1] === '-' ? -1 : 1);
|
||||
return offset;
|
||||
}
|
||||
export const sourcePart = (asset: ModelAsset): AssemblyPart => ({
|
||||
id: newEditorId('part'), name: asset.relativePath.split('/').pop()!.replace(/\.glb$/i, ''), assetId: asset.assetId,
|
||||
parentId: null, position: [0, 0, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [0, 0.08, 0],
|
||||
});
|
||||
|
||||
async function localSource(file: File, relativePath: string, type: 'part-glb' | 'whole-glb'): Promise<AssemblySource> {
|
||||
const bytes = await file.arrayBuffer();
|
||||
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), (v) => v.toString(16).padStart(2, '0')).join('');
|
||||
return { file, asset: { assetId: `local-${type}-${hash}-${relativePath}`, type, relativePath, bytes: file.size, sha256: hash, status: 'READY', downloadUrl: null } };
|
||||
}
|
||||
|
||||
export async function prepareAssemblySession(existing: AssemblySession | null, assembly: Assembly | null, assets: ModelAsset[], files: ExperienceFileSelections, referenceAssetId?: string): Promise<AssemblySession> {
|
||||
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 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)))];
|
||||
// 摘要与预览都读取原文件;不重写、压缩或改变 GLB 的材质。
|
||||
for (const selected of localParts) {
|
||||
if (!sources.some((s) => s.file === selected.file && s.asset.relativePath === selected.relativePath)) {
|
||||
const next = await localSource(selected.file, selected.relativePath, 'part-glb');
|
||||
const i = sources.findIndex((s) => s.asset.assetId === next.asset.assetId);
|
||||
if (i >= 0) sources[i] = next; else sources.push(next);
|
||||
}
|
||||
}
|
||||
for (const asset of assets.filter((a) => a.status === 'READY' && (a.type === 'part-glb' || a.type === 'whole-glb' && (a.assetId === referenceAssetId || a.assetId === assembly?.referenceAssetId || referenced.has(a.assetId))))) {
|
||||
const i = sources.findIndex((s) => s.asset.assetId === asset.assetId);
|
||||
if (i >= 0) sources[i] = { ...sources[i], asset }; else sources.push({ asset });
|
||||
}
|
||||
const prior = assembly;
|
||||
const defaults = sources.filter((s) => s.asset.type === 'part-glb' && (localParts.length ? !!s.file && currentFiles.has(s.file) : readyParts.some((a) => a.assetId === s.asset.assetId)));
|
||||
const next: Assembly = prior ? copyAssembly(prior) : {
|
||||
enabled: true, title: '机器人装配流程', unit: 'meter', referenceAssetId: referenceAssetId ?? null,
|
||||
displayQuaternion: [0, 0, 0, 1], parts: defaults.map((s) => sourcePart(s.asset)), steps: [], editorGroups: [],
|
||||
};
|
||||
let reference = sources.find((s) => s.asset.assetId === (next.referenceAssetId ?? referenceAssetId));
|
||||
if (files.whole.type === 'whole-glb' && !files.whole.checking && !files.whole.problems.length && files.whole.selected[0]) {
|
||||
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);
|
||||
}
|
||||
|
||||
/** 唯一匹配才关联;版本歧义保持待上传状态,绝不悄悄换成同名文件。 */
|
||||
export function bindAssemblySession(session: AssemblySession, assets: ModelAsset[]): AssemblySession {
|
||||
const replacements = new Map<string, ModelAsset>();
|
||||
for (const source of session.sources) {
|
||||
if (!source.file || !source.asset.assetId.startsWith('local-')) continue;
|
||||
const matches = assets.filter((a) => a.status === 'READY' && a.type === source.asset.type && a.relativePath === source.asset.relativePath && a.bytes === source.asset.bytes && a.sha256 === source.asset.sha256);
|
||||
if (matches.length === 1) replacements.set(source.asset.assetId, matches[0]);
|
||||
}
|
||||
const sources = new Map<string, AssemblySource>();
|
||||
for (const source of session.sources) {
|
||||
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()] };
|
||||
}
|
||||
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-'));
|
||||
}
|
||||
|
||||
/** 保留流程使用的本地原文件,避免更换选择或移除卡片选择后无从上传。 */
|
||||
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));
|
||||
if (!needed.length) return files;
|
||||
const selected = files.parts.type === 'part-glb' ? [...files.parts.selected] : [];
|
||||
for (const source of needed) {
|
||||
const current = selected.find((s) => s.relativePath === source.asset.relativePath);
|
||||
if (current && current.file !== source.file) throw new Error(`存在同路径的不同零件文件:${source.asset.relativePath}。请用不同名称或文件夹区分后再制作。`);
|
||||
if (!current) selected.push({ file: source.file!, relativePath: source.asset.relativePath });
|
||||
}
|
||||
return { ...files, parts: { type: 'part-glb', selected, problems: files.parts.type === 'part-glb' ? files.parts.problems : [], checking: false } };
|
||||
}
|
||||
|
||||
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 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);
|
||||
const quat = (v: number[]) => finite(v, 4) && Math.abs(Math.hypot(...v) - 1) <= 0.001;
|
||||
if (!quat(assembly.displayQuaternion)) problems.push('模型显示方向无效,请重新载入。');
|
||||
for (const p of assembly.parts) {
|
||||
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(p.id)) problems.push('有零件编号无效,请重新载入对应文件。');
|
||||
if (!finite(p.position, 3) || !quat(p.quaternion) || !finite(p.scale, 3) || p.scale.some((v) => v <= 0) || !finite(p.installOffset, 3)) problems.push(`${p.name} 的位置或方向无效,请调整后重试。`);
|
||||
const visited = new Set([p.id]);
|
||||
for (let id = p.parentId; id; id = byId.get(id)?.parentId ?? null) {
|
||||
if (!byId.has(id) || visited.has(id)) { problems.push(`${p.name} 的父零件层级无效。`); break; }
|
||||
visited.add(id);
|
||||
}
|
||||
}
|
||||
const assigned = new Set<string>();
|
||||
const stepIds = new Set<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 (stepIds.has(step.id)) problems.push(`第 ${i + 1} 步重复。`);
|
||||
stepIds.add(step.id);
|
||||
if (!step.parts.length) problems.push(`第 ${i + 1} 步还没有选择零件。`);
|
||||
const current = new Set(step.parts);
|
||||
if (current.size !== step.parts.length) problems.push(`第 ${i + 1} 步包含重复零件。`);
|
||||
for (const id of current) {
|
||||
const p = byId.get(id);
|
||||
if (!p || assigned.has(id)) problems.push(`第 ${i + 1} 步包含不存在或已经安装的零件。`);
|
||||
else if (p.parentId && !assigned.has(p.parentId) && !current.has(p.parentId)) problems.push(`请把 ${p.name} 的父零件安排在同一步或更早安装。`);
|
||||
}
|
||||
current.forEach((id) => assigned.add(id));
|
||||
}
|
||||
const missing = assembly.parts.filter((p) => !assigned.has(p.id));
|
||||
if (assembly.steps.length && missing.length) problems.push(`还有 ${missing.length} 个零件未安排步骤。`);
|
||||
return [...new Set(problems)];
|
||||
}
|
||||
|
||||
export function assemblyManifest(assembly: Assembly, sources: AssemblySource[]) {
|
||||
const problems = assemblyProblems(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 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}`;
|
||||
paths.set(assetId, path); usedPaths.add(path);
|
||||
files.push({ path, bytes: asset.bytes, sha256: asset.sha256 });
|
||||
}
|
||||
return {
|
||||
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] })),
|
||||
steps: assembly.steps.map((s) => ({ ...s, parts: [...s.parts] })),
|
||||
};
|
||||
}
|
||||
|
||||
const queued = new Map<string, AssemblySession>();
|
||||
export const queueAssemblySession = (code: string, session: AssemblySession) => queued.set(code, session);
|
||||
export const peekAssemblySession = (code: string) => queued.get(code);
|
||||
export const releaseAssemblySession = (code: string) => queued.delete(code);
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ModelAssetType } from '@/api/experience-types';
|
||||
import type { SelectedFile } from '@/api/types';
|
||||
|
||||
export type ExperienceFileSection = 'whole' | 'parts' | 'assembly' | 'walking';
|
||||
export interface ExperienceFileSelection {
|
||||
type: ModelAssetType;
|
||||
selected: SelectedFile[];
|
||||
problems: string[];
|
||||
checking: boolean;
|
||||
ignoredCount?: number;
|
||||
}
|
||||
export type ExperienceFileSelections = Record<ExperienceFileSection, ExperienceFileSelection>;
|
||||
export const experienceFileSections: ExperienceFileSection[] = ['whole', 'parts', 'assembly', 'walking'];
|
||||
export function emptyExperienceFiles(): ExperienceFileSelections {
|
||||
return {
|
||||
whole: { type: 'whole-glb', selected: [], problems: [], checking: false },
|
||||
parts: { type: 'part-glb', selected: [], problems: [], checking: false },
|
||||
assembly: { type: 'assembly-manifest', selected: [], problems: [], checking: false },
|
||||
walking: { type: 'walking-zip', selected: [], problems: [], checking: false },
|
||||
};
|
||||
}
|
||||
|
||||
// 大模型文件仅在创建页到详情的一次 SPA 跳转中通过内存传递,不序列化到历史或本地存储。
|
||||
const pendingFiles = new Map<string, ExperienceFileSelections>();
|
||||
export const queueExperienceFiles = (code: string, files: ExperienceFileSelections) => pendingFiles.set(code, files);
|
||||
export const peekExperienceFiles = (code: string) => pendingFiles.get(code);
|
||||
export const releaseExperienceFiles = (code: string) => pendingFiles.delete(code);
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { ModelAssetType, ModelUploadSignature } from '@/api/experience-types';
|
||||
import type { SelectedFile } from '@/api/types';
|
||||
import { signModelAssets, completeModelAssets } from '@/api/experiences';
|
||||
import { uploadOssFile } from '@/api/request';
|
||||
import { parseServerTime } from './format';
|
||||
|
||||
export const modelAssetLabels: Record<ModelAssetType, string> = {
|
||||
'whole-glb': '整机 GLB', 'part-glb': '零件 GLB', 'parts-zip': '零件库 ZIP',
|
||||
'assembly-zip': '装配资源 ZIP', 'assembly-manifest': '装配清单 JSON', 'walking-zip': '行走资源 ZIP',
|
||||
};
|
||||
|
||||
export const emptyExperienceDraft = () => ({ wholeModel: null, assembly: null, walking: null });
|
||||
|
||||
export function experiencePathProblem(path: string): string | null {
|
||||
if (!path || /[\\:%?#\x00-\x1f\x7f]/.test(path)
|
||||
|| path.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
|
||||
return '必须是包内相对路径,不能包含空段、..、反斜杠、冒号、%、?、# 或控制字符';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface ManifestFile {
|
||||
path: string;
|
||||
bytes: number;
|
||||
sha256: string;
|
||||
}
|
||||
|
||||
export interface ModelFileInspection {
|
||||
problems: string[];
|
||||
manifestFiles: ManifestFile[];
|
||||
}
|
||||
|
||||
/** 只检查文件类型和结构;大小、数量、资源完整性和算法兼容性由后端决定。 */
|
||||
export async function inspectModelFiles(type: ModelAssetType, selected: SelectedFile[]): Promise<ModelFileInspection> {
|
||||
const problems: string[] = [];
|
||||
let manifestFiles: ManifestFile[] = [];
|
||||
const paths = new Set<string>();
|
||||
if (type !== 'part-glb' && selected.length > 1) problems.push('该资源类型每次选择一个文件');
|
||||
for (const { file, relativePath } of selected) {
|
||||
const pathProblem = experiencePathProblem(relativePath);
|
||||
if (pathProblem) problems.push(`${relativePath}:${pathProblem}`);
|
||||
if (paths.has(relativePath)) problems.push(`路径重复:${relativePath}`);
|
||||
paths.add(relativePath);
|
||||
try {
|
||||
if (type === 'whole-glb' || type === 'part-glb') {
|
||||
if (!/\.glb$/i.test(file.name)) throw new Error('请选择 .glb 文件');
|
||||
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 文件');
|
||||
} else if (type.endsWith('-zip')) {
|
||||
if (!/\.zip$/i.test(file.name)) throw new Error('请选择 .zip 文件');
|
||||
const header = new Uint8Array(await file.slice(0, 4).arrayBuffer());
|
||||
if (header[0] !== 0x50 || header[1] !== 0x4b
|
||||
|| !((header[2] === 3 && header[3] === 4) || (header[2] === 5 && header[3] === 6) || (header[2] === 7 && header[3] === 8))) {
|
||||
throw new Error('不是有效的 ZIP 文件头');
|
||||
}
|
||||
} else {
|
||||
if (!/\.json$/i.test(file.name)) throw new Error('请选择 .json 文件');
|
||||
const raw = JSON.parse((await file.text()).replace(/^\uFEFF/, ''));
|
||||
if (!raw || raw.schemaVersion !== 1 || raw.kind !== 'assembly' || raw.unit !== 'meter'
|
||||
|| !Array.isArray(raw.files) || !Array.isArray(raw.parts) || !Array.isArray(raw.steps)) {
|
||||
throw new Error('需要 schemaVersion=1、kind=assembly、unit=meter 及 files/parts/steps 数组');
|
||||
}
|
||||
const manifestPaths = new Set<string>();
|
||||
manifestFiles = raw.files.map((item: unknown) => {
|
||||
const value = item as ManifestFile;
|
||||
if (!value || typeof value.path !== 'string' || experiencePathProblem(value.path)
|
||||
|| manifestPaths.has(value.path) || !Number.isSafeInteger(value.bytes) || value.bytes <= 0
|
||||
|| typeof value.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(value.sha256)) {
|
||||
throw new Error('files 中存在重复/非法路径、无效字节数或 SHA256');
|
||||
}
|
||||
manifestPaths.add(value.path);
|
||||
return { path: value.path, bytes: value.bytes, sha256: value.sha256 };
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
problems.push(`${relativePath}:${error instanceof Error ? error.message : '无法读取文件格式'}`);
|
||||
}
|
||||
}
|
||||
return { problems, manifestFiles };
|
||||
}
|
||||
|
||||
export interface ModelUploadBatch {
|
||||
type: ModelAssetType;
|
||||
selected: SelectedFile[];
|
||||
signature: ModelUploadSignature;
|
||||
uploaded: Set<string>;
|
||||
uploadUncertain?: boolean;
|
||||
}
|
||||
|
||||
export async function uploadModelFiles(
|
||||
projectCode: string,
|
||||
type: ModelAssetType,
|
||||
selected: SelectedFile[],
|
||||
previous: ModelUploadBatch | null,
|
||||
signal: AbortSignal,
|
||||
onBatch: (batch: ModelUploadBatch) => void,
|
||||
onProgress: (done: number, total: number) => void,
|
||||
) {
|
||||
if (!selected.length) throw new Error('请先选择文件');
|
||||
let batch = previous;
|
||||
const sameSelection = batch?.type === type && batch.selected.length === selected.length
|
||||
&& batch.selected.every((item, index) => item.file === selected[index].file && item.relativePath === selected[index].relativePath);
|
||||
const expired = batch && batch.uploaded.size < selected.length
|
||||
&& parseServerTime(batch.signature.expiresAt).getTime() <= Date.now();
|
||||
if (!sameSelection || expired || batch?.uploadUncertain) {
|
||||
const signature = await signModelAssets(projectCode, type, selected);
|
||||
const returnedPaths = new Set(signature.files.map((item) => item.relativePath));
|
||||
if (returnedPaths.size !== selected.length || signature.files.length !== selected.length
|
||||
|| selected.some((item) => !returnedPaths.has(item.relativePath))) throw new Error('上传签名与本地文件清单不一致,请重新申请');
|
||||
batch = { type, selected, signature, uploaded: new Set() };
|
||||
onBatch(batch);
|
||||
}
|
||||
if (!batch) throw new Error('缺少上传批次');
|
||||
signal.throwIfAborted();
|
||||
const current = batch;
|
||||
const byPath = new Map(selected.map((item) => [item.relativePath, item.file]));
|
||||
const queue = current.signature.files.filter((item) => !current.uploaded.has(item.relativePath));
|
||||
let failed = false;
|
||||
onProgress(current.uploaded.size, selected.length);
|
||||
const worker = async () => {
|
||||
while (!failed && queue.length) {
|
||||
const item = queue.shift()!;
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
await uploadOssFile(current.signature.uploadUrl, item.formFields, byPath.get(item.relativePath)!, signal);
|
||||
current.uploaded.add(item.relativePath);
|
||||
onProgress(current.uploaded.size, selected.length);
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
// 断网/中断不代表对象未写入;下次人工重试使用新批次,避免覆盖未知结果。
|
||||
if (error instanceof TypeError || error instanceof DOMException && error.name === 'AbortError') current.uploadUncertain = true;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
// 所有在途请求结束后才交还表单;同批次只补传失败/未开始的文件。
|
||||
const outcomes = await Promise.allSettled(Array.from({ length: Math.min(4, queue.length) }, worker));
|
||||
const rejected = outcomes.find((result): result is PromiseRejectedResult => result.status === 'rejected');
|
||||
if (rejected) throw rejected.reason;
|
||||
signal.throwIfAborted();
|
||||
return completeModelAssets(projectCode, current.signature.batchCode);
|
||||
}
|
||||
|
||||
export function safeExperienceUrl(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value, window.location.origin);
|
||||
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return null;
|
||||
if (window.location.protocol === 'https:' && url.protocol !== 'https:') return null;
|
||||
return url.href;
|
||||
} catch { return null; }
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import profile from '@/config/walking-upload-profiles.json';
|
||||
import type { WalkingEditorView, WalkingFeatureBinding, WalkingFeatureId, WalkingFormDraft, WalkingResource, WalkingResourceKind, WalkingSkill } from '@/api/walking-editor-types';
|
||||
import { experiencePathProblem } from './modelAssets';
|
||||
export const walkingFormSpec = profile;
|
||||
export const walkingFeatures = profile.optionalCapabilities;
|
||||
export interface WalkingLocalResource {
|
||||
key: string; relativePath: string; originalPath: string; kind: WalkingResourceKind;
|
||||
file?: File; remote?: WalkingResource; problem?: string;
|
||||
config?: RobotConfigSummary;
|
||||
}
|
||||
export interface RobotConfigSummary { model: string; adapter: string; skills: WalkingSkill[]; assets: string[]; renderSource: string }
|
||||
export interface WalkingLocalSession { draft: WalkingFormDraft; resources: WalkingLocalResource[]; robot: RobotConfigSummary | null }
|
||||
export const emptyFeature = (): WalkingFeatureBinding => ({ enabled: false, skillIds: [], configResource: null, policyResources: [], modelResource: null, dependencyResources: [], mappingResource: null, autoTrigger: false });
|
||||
export const emptyWalkingSession = (): WalkingLocalSession => ({ draft: { enabled: false, entryResource: null, modelResource: null, dependencyResources: [], walkPolicyResource: null, walkSkillId: null, features: Object.fromEntries(walkingFeatures.map((f) => [f.id, emptyFeature()])), football: null, pickupTarget: null, resourceIds: [] }, resources: [], robot: null });
|
||||
export function sessionFromView(view: WalkingEditorView): WalkingLocalSession {
|
||||
return { draft: { ...emptyWalkingSession().draft, ...view.draft, features: { ...emptyWalkingSession().draft.features, ...view.draft.features } }, resources: view.resources.map((remote) => ({ key: remote.resourceId, relativePath: remote.relativePath, originalPath: remote.originalPath, kind: remote.kind, remote })), robot: null };
|
||||
}
|
||||
export function readRobotConfig(raw: unknown): RobotConfigSummary {
|
||||
if (!raw || typeof raw !== 'object') throw new Error('请选择机器人控制配置 JSON。');
|
||||
const config = raw as { schema?: unknown; model?: unknown; adapter?: unknown; skills?: unknown; assets?: unknown; render?: { source?: unknown } };
|
||||
if (config.schema !== 1 || typeof config.model !== 'string' || !Array.isArray(config.skills)) throw new Error('需要原工程 robot.json(schema=1,包含 model 与 skills),不能使用发布 manifest 或文件要求说明代替。');
|
||||
const skills: WalkingSkill[] = config.skills.map((entry) => {
|
||||
const s = entry as { id?: unknown; kind?: unknown; owns?: unknown; controller?: { type?: unknown; policy?: unknown } };
|
||||
if (typeof s.id !== 'string' || typeof s.kind !== 'string' || typeof s.controller?.type !== 'string') throw new Error('配置中的技能缺少 id、kind 或 controller.type,请由算法人员补齐。');
|
||||
return { id: s.id, kind: s.kind, controller: s.controller.type, policy: typeof s.controller.policy === 'string' ? s.controller.policy : undefined, owns: typeof s.owns === 'string' ? s.owns : undefined };
|
||||
});
|
||||
if (new Set(skills.map((s) => s.id)).size !== skills.length) throw new Error('机器人配置中有重复技能编号。');
|
||||
return { model: config.model, adapter: typeof config.adapter === 'string' ? config.adapter : '', skills, assets: Array.isArray(config.assets) ? config.assets.flatMap((a) => typeof a?.path === 'string' ? [a.path] : []) : [], renderSource: typeof config.render?.source === 'string' ? config.render.source : '' };
|
||||
}
|
||||
export async function inspectWalkingFile(file: File, kind: WalkingResourceKind): Promise<string | undefined> {
|
||||
const text = new TextDecoder().decode(await file.slice(0, 512).arrayBuffer()).trimStart();
|
||||
if (text.startsWith('version https://git-lfs.github.com/spec/v1')) return '这是 Git LFS 占位文件,请取得实际大文件后重新选择。';
|
||||
if (/^<!doctype html|^<html[\s>]/i.test(text)) return '文件内容是 HTML 页面,请下载真实模型或策略文件。';
|
||||
const extensions: Partial<Record<WalkingResourceKind, RegExp>> = { config: /\.json$/i, mjcf: /\.xml$/i, policy: /\.onnx$/i, glb: /\.glb$/i, mapping: /\.json$/i, archive: /\.zip$/i };
|
||||
if (extensions[kind] && !extensions[kind]!.test(file.name)) return '文件格式不符合此上传项,请重新选择。';
|
||||
if (kind === 'config' || kind === 'mapping') { try { JSON.parse((await file.text()).replace(/^\uFEFF/, '')); } catch { return '不是有效的 JSON 文件。'; } }
|
||||
if (kind === 'mjcf') { const xml = new DOMParser().parseFromString(await file.text(), 'application/xml'); if (xml.querySelector('parsererror') || xml.documentElement.nodeName !== 'mujoco') return '需要 MJCF XML(mujoco 根节点),不能用 URDF 改后缀替代。'; }
|
||||
if (kind === 'archive') { const bytes = new Uint8Array(await file.slice(0, 4).arrayBuffer()); if (bytes[0] !== 0x50 || bytes[1] !== 0x4b) return '不是有效的 ZIP 文件头。'; }
|
||||
// 这只是本地格式/占位识别,不宣称 ONNX 可推理或模型已兼容。
|
||||
}
|
||||
export function enabledCapabilityIds(draft: WalkingFormDraft): WalkingFeatureId[] {
|
||||
return draft.enabled ? ['walk', ...walkingFeatures.filter((f) => draft.features[f.id]?.enabled).map((f) => f.id as WalkingFeatureId)] : [];
|
||||
}
|
||||
export function activeResourceKeys(session: WalkingLocalSession, ids = enabledCapabilityIds(session.draft)): Set<string> {
|
||||
const d = session.draft, keys = new Set<string>();
|
||||
const add = (key: string | null | undefined) => { if (key) keys.add(key); };
|
||||
if (!ids.includes('walk')) return keys;
|
||||
[d.entryResource, d.modelResource, d.walkPolicyResource, ...d.dependencyResources].forEach(add);
|
||||
for (const id of ids.filter((id) => id !== 'walk')) {
|
||||
const f = d.features[id]; if (!f) continue;
|
||||
[f.configResource, f.modelResource, f.mappingResource, ...f.policyResources, ...f.dependencyResources].forEach(add);
|
||||
}
|
||||
if (ids.includes('kick_left') || ids.includes('kick_right')) add(d.football?.visualResource);
|
||||
if (ids.includes('ground_pick')) add(d.pickupTarget?.visualResource);
|
||||
return keys;
|
||||
}
|
||||
export function walkingFormProblems(session: WalkingLocalSession, uploaded = false): string[] {
|
||||
const d = session.draft; if (!d.enabled) return [];
|
||||
const errors: string[] = [];
|
||||
const requireResource = (key: string | null, label: string) => {
|
||||
const resource = session.resources.find((r) => r.key === key);
|
||||
if (!resource) errors.push(`请提供${label}。`);
|
||||
else if (resource.problem) errors.push(`${label}:${resource.problem}`);
|
||||
else if (uploaded && resource.remote?.status !== 'READY') errors.push(`${label}尚未上传或仍在处理。`);
|
||||
};
|
||||
requireResource(d.entryResource, '机器人控制配置'); requireResource(d.modelResource, '物理模型 XML'); requireResource(d.walkPolicyResource, '基础行走策略 ONNX');
|
||||
if (!d.walkSkillId) errors.push('请选择配置中的基础行走 primary 技能。');
|
||||
const skills = session.robot?.skills;
|
||||
const base = skills?.find((s) => s.id === d.walkSkillId);
|
||||
if (skills && (!base || base.kind !== 'primary' || base.controller !== 'onnx')) errors.push('基础行走必须绑定一个 ONNX primary 技能。');
|
||||
const enabled = enabledCapabilityIds(d);
|
||||
for (const id of enabled.filter((id) => id !== 'walk')) {
|
||||
const def = walkingFeatures.find((f) => f.id === id)!, f = d.features[id];
|
||||
for (const dependency of def.dependsOn) if (!enabled.includes(dependency as WalkingFeatureId)) errors.push(`${def.label}需要先启用${walkingFeatures.find((x) => x.id === dependency)?.label ?? '基础行走'}。`);
|
||||
if (def.skillBinding && !f.skillIds.length) errors.push(`请为${def.label}绑定实际技能。`);
|
||||
if (f.configResource) requireResource(f.configResource, `${def.label}配套控制配置`);
|
||||
if (id === 'visual_model') { requireResource(f.modelResource, '高精度显示 GLB'); requireResource(f.mappingResource, '显示模型映射配置'); }
|
||||
if (id === 'rollers') requireResource(f.modelResource, '滚轮物理模型');
|
||||
for (const skillId of f.skillIds) {
|
||||
const skill = skills?.find((s) => s.id === skillId);
|
||||
if (skills && !skill && !f.configResource) errors.push(`${def.label}绑定的技能不在机器人配置中,请提供配套控制配置。`);
|
||||
if (skill?.controller === 'onnx' && ![d.walkPolicyResource, ...f.policyResources, ...d.dependencyResources].some((key) => session.resources.find((r) => r.key === key)?.relativePath === skill.policy)) errors.push(`${def.label}缺少技能引用的策略 ${skill.policy}。`);
|
||||
}
|
||||
}
|
||||
if ((enabled.includes('kick_left') || enabled.includes('kick_right')) && !d.football) errors.push('请为踢球功能选择兼容且有版本的足球物理预设。');
|
||||
if (enabled.includes('ground_pick') && !d.pickupTarget) errors.push('请为俯身拾取选择道具物理预设。');
|
||||
const paths = new Set<string>();
|
||||
const active = activeResourceKeys(session);
|
||||
for (const r of session.resources) {
|
||||
const problem = experiencePathProblem(r.relativePath);
|
||||
if (problem && active.has(r.key)) errors.push(`${r.relativePath}:${problem}`);
|
||||
if (active.has(r.key)) {
|
||||
if (paths.has(r.relativePath)) errors.push(`资源路径冲突:${r.relativePath},请明确调整路径,不能覆盖同名文件。`);
|
||||
paths.add(r.relativePath);
|
||||
}
|
||||
}
|
||||
if (session.robot) {
|
||||
const model = session.resources.find((r) => r.key === d.modelResource);
|
||||
if (model && model.relativePath !== session.robot.model) errors.push(`物理模型路径需与配置一致:${session.robot.model}。`);
|
||||
if (base?.policy && session.resources.find((r) => r.key === d.walkPolicyResource)?.relativePath !== base.policy) errors.push(`行走策略路径需与配置一致:${base.policy}。`);
|
||||
// 只靠 assets 数组无法区分基础与可选动作的真实依赖;完整闭包由后端编译 MJCF 检查。
|
||||
}
|
||||
for (const key of active) {
|
||||
const resource = session.resources.find((r) => r.key === key);
|
||||
if (!resource) errors.push('存在已删除或未提供的资源引用,请重新选择。');
|
||||
else if (resource.problem) errors.push(`${resource.relativePath}:${resource.problem}`);
|
||||
else if (uploaded && resource.remote?.status !== 'READY') errors.push(`${resource.relativePath}:尚未上传或检查完成。`);
|
||||
}
|
||||
return [...new Set(errors)];
|
||||
}
|
||||
export function serializeWalkingDraft(session: WalkingLocalSession): WalkingFormDraft {
|
||||
const map = (key: string | null, optional = false): string | null => {
|
||||
if (!key) return null;
|
||||
const r = session.resources.find((r) => r.key === key);
|
||||
if (!r?.remote || r.remote.status !== 'READY') { if (optional) return null; throw new Error('请先上传表单引用的资源,再保存到服务器。'); }
|
||||
return r.remote.resourceId;
|
||||
};
|
||||
const f = session.draft;
|
||||
return { ...f, entryResource: map(f.entryResource, !f.enabled), modelResource: map(f.modelResource, !f.enabled), walkPolicyResource: map(f.walkPolicyResource, !f.enabled), dependencyResources: f.dependencyResources.flatMap((k) => map(k, !f.enabled) ? [map(k, !f.enabled)!] : []),
|
||||
features: Object.fromEntries(Object.entries(f.features).map(([id, b]) => [id, { ...b, configResource: map(b.configResource, !b.enabled || !f.enabled), policyResources: b.policyResources.flatMap((k) => map(k, !b.enabled || !f.enabled) ? [map(k, !b.enabled || !f.enabled)!] : []), modelResource: map(b.modelResource, !b.enabled || !f.enabled), dependencyResources: b.dependencyResources.flatMap((k) => map(k, !b.enabled || !f.enabled) ? [map(k, !b.enabled || !f.enabled)!] : []), mappingResource: map(b.mappingResource, !b.enabled || !f.enabled) }])),
|
||||
football: f.football ? { ...f.football, visualResource: map(f.football.visualResource, !f.enabled || !(f.features.kick_left?.enabled || f.features.kick_right?.enabled)) } : null,
|
||||
pickupTarget: f.pickupTarget ? { ...f.pickupTarget, visualResource: map(f.pickupTarget.visualResource, !f.enabled || !f.features.ground_pick?.enabled) } : null,
|
||||
resourceIds: session.resources.flatMap((r) => r.remote ? [r.remote.resourceId] : []),
|
||||
};
|
||||
}
|
||||
export function readyCapabilities(view: WalkingEditorView): WalkingFeatureId[] {
|
||||
const check = view.check;
|
||||
if (!view.draft.enabled || !check || check.draftRevision !== view.revision || check.sourceVersion !== view.sourceVersion || check.base.status !== 'PASSED' || check.communityRuntime !== 'supported') return [];
|
||||
const ids: WalkingFeatureId[] = ['walk'];
|
||||
for (const def of walkingFeatures) {
|
||||
if (!view.draft.features[def.id]?.enabled || !check.features.some((f) => f.capabilityId === def.id && f.status === 'PASSED')) continue;
|
||||
if (def.dependsOn.every((id) => ids.includes(id as WalkingFeatureId))) ids.push(def.id as WalkingFeatureId);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
export function publicationSummary(draft: WalkingFormDraft, ids: WalkingFeatureId[]) {
|
||||
const football = ids.includes('kick_left') || ids.includes('kick_right') || ids.includes('ground_pick') && draft.pickupTarget?.kind === 'football';
|
||||
return { capabilities: ids, props: [...(football ? ['football'] : []), ...(ids.includes('ground_pick') && draft.pickupTarget?.kind === 'pickup_target' ? ['pickup_target'] : [])] };
|
||||
}
|
||||
const queued = new Map<string, WalkingLocalSession>();
|
||||
export const queueWalkingSession = (code: string, session: WalkingLocalSession) => queued.set(code, session);
|
||||
export const peekWalkingSession = (code: string) => queued.get(code);
|
||||
export const releaseWalkingSession = (code: string) => queued.delete(code);
|
||||
|
||||
/** 目录即工程根目录,只自动绑定明确的基础资源;其他素材保留待用户选用。 */
|
||||
export async function readWalkingFolder(files: File[]): Promise<WalkingLocalSession> {
|
||||
const session = emptyWalkingSession();
|
||||
const entries = files.map((file) => ({ file, path: (file.webkitRelativePath || file.name).split('/').slice(file.webkitRelativePath ? 1 : 0).join('/') }));
|
||||
const entry = entries.find((r) => r.path === 'robot.json');
|
||||
let configProblem: string | undefined;
|
||||
if (entry) {
|
||||
try {
|
||||
configProblem = await inspectWalkingFile(entry.file, 'config');
|
||||
if (!configProblem) session.robot = readRobotConfig(JSON.parse((await entry.file.text()).replace(/^\uFEFF/, '')));
|
||||
} catch (error) { configProblem = error instanceof Error ? error.message : '机器人配置读取失败'; }
|
||||
}
|
||||
const robot = session.robot;
|
||||
const primary = robot?.skills.filter((s) => s.kind === 'primary' && s.controller === 'onnx') ?? [];
|
||||
for (const { file, path } of entries) {
|
||||
const kind: WalkingResourceKind = path === 'robot.json' ? 'config' : path === robot?.model ? 'mjcf' : /\.onnx$/i.test(path) ? 'policy' : /\.glb$/i.test(path) ? 'glb' : 'extra';
|
||||
const row: WalkingLocalResource = { key: `local-${crypto.randomUUID()}`, relativePath: path, originalPath: file.webkitRelativePath || file.name, file, kind };
|
||||
row.problem = experiencePathProblem(path) ?? (path === 'robot.json' ? configProblem : await inspectWalkingFile(file, kind));
|
||||
if (path === 'robot.json') { session.draft.entryResource = row.key; row.config = robot ?? undefined; }
|
||||
if (path === robot?.model) session.draft.modelResource = row.key;
|
||||
if (primary.length === 1 && path === primary[0].policy) session.draft.walkPolicyResource = row.key;
|
||||
session.resources.push(row);
|
||||
}
|
||||
session.draft.enabled = files.length > 0;
|
||||
session.draft.walkSkillId = primary.length === 1 ? primary[0].id : null;
|
||||
// robot.assets 可能混有可选动作依赖;不把整个目录当成基础依赖闭包,交给后端按引用解析。
|
||||
return session;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import * as api from '@/api/walking-editor';
|
||||
import { uploadOssFile } from '@/api/request';
|
||||
import type { WalkingUploadSignature } from '@/api/walking-editor-types';
|
||||
import type { WalkingLocalResource } from './walkingForm';
|
||||
import { experiencePathProblem } from './modelAssets';
|
||||
import { parseServerTime } from './format';
|
||||
export interface WalkingUploadBatch { rows: WalkingLocalResource[]; signature: WalkingUploadSignature; uploaded: Set<string>; uncertain?: boolean }
|
||||
export async function uploadWalkingRows(code: string, rows: WalkingLocalResource[], previous: WalkingUploadBatch | null, signal: AbortSignal, onBatch: (batch: WalkingUploadBatch) => void, progress: (done: number, total: number) => void) {
|
||||
if (!rows.length) return [];
|
||||
for (const r of rows) if (!r.file || r.problem || experiencePathProblem(r.relativePath)) throw new Error('请先修正待上传文件的格式和路径。');
|
||||
if (new Set(rows.map((r) => r.relativePath)).size !== rows.length) throw new Error('上传路径有重复,不能覆盖同名文件。');
|
||||
let batch = previous;
|
||||
if (!batch || batch.uncertain || batch.rows.length !== rows.length || batch.rows.some((r, i) => r.file !== rows[i].file || r.relativePath !== rows[i].relativePath || r.key !== rows[i].key)
|
||||
|| batch.uploaded.size < rows.length && parseServerTime(batch.signature.expiresAt).getTime() <= Date.now()) {
|
||||
const signature = await api.signWalkingResources(code, rows.map((r) => ({ clientId: r.key, relativePath: r.relativePath, originalPath: r.originalPath, sizeBytes: r.file!.size, kind: r.kind })), signal);
|
||||
if (signature.files.length !== rows.length || new Set(signature.files.map((r) => r.clientId)).size !== rows.length || rows.some((r) => !signature.files.some((f) => f.clientId === r.key && f.relativePath === r.relativePath))) throw new Error('签名返回的文件与所选资源不一致,未开始上传。');
|
||||
batch = { rows, signature, uploaded: new Set() }; onBatch(batch);
|
||||
}
|
||||
const current = batch;
|
||||
const pending = current.signature.files.filter((f) => !current.uploaded.has(f.clientId));
|
||||
let index = 0, stopped = false;
|
||||
const results = await Promise.allSettled(Array.from({ length: Math.min(4, pending.length) }, async () => {
|
||||
while (!stopped && index < pending.length) {
|
||||
const signed = pending[index++];
|
||||
try {
|
||||
await uploadOssFile(current.signature.uploadUrl, signed.formFields, rows.find((r) => r.key === signed.clientId)!.file!, signal);
|
||||
current.uploaded.add(signed.clientId); progress(current.uploaded.size, rows.length);
|
||||
} catch (cause) { stopped = true; if (cause instanceof TypeError) current.uncertain = true; throw cause; }
|
||||
}
|
||||
}));
|
||||
signal.throwIfAborted();
|
||||
const failure = results.find((r): r is PromiseRejectedResult => r.status === 'rejected');
|
||||
if (failure) throw failure.reason;
|
||||
const result = await api.completeWalkingResources(code, current.signature.batchCode, signal);
|
||||
// complete 必须按上传时的 clientId 返回一一对应结果,不能按叶文件名猜。
|
||||
if (new Set(result.resources.map((r) => r.resourceId)).size !== rows.length || result.resources.some((r) => !r.resourceId || !/^[a-f0-9]{64}$/i.test(r.sha256) || !['READY', 'PROCESSING', 'FAILED'].includes(r.status)) || result.resources.length !== rows.length || rows.some((row) => !result.resources.some((r) => (r as typeof r & { clientId?: string }).clientId === row.key && r.relativePath === row.relativePath && r.bytes === row.file!.size))) throw new Error('资源确认结果不完整,请刷新核对,不会自动重新提交。');
|
||||
return result.resources;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import legacySpec from '@/config/walking-upload-requirements.json';
|
||||
import profiles from '@/config/walking-upload-profiles.json';
|
||||
import type { ExperienceReport, ModelAsset, WalkingCheckItem, WalkingItemState, WalkingRequirement } from '@/api/experience-types';
|
||||
|
||||
export const legacyWalkingSpec = legacySpec;
|
||||
export const walkingProfiles = profiles;
|
||||
export const walkingExampleUrl = `${import.meta.env.BASE_URL}examples/${legacySpec.runtimeProfile}/${legacySpec.example.zipSha256.slice(0, 12)}/${legacySpec.example.fileName}`;
|
||||
export const microbanConfigUrl = `${import.meta.env.BASE_URL}examples/robot-package/microban.robot.json`;
|
||||
export const walkingGeneralRequirements = [
|
||||
{ label: '机器人配置', rule: '描述模型、关节、控制方式与动作;Robot Package 使用 robot.json 或发布清单指定的入口。', source: '机器人/算法人员' },
|
||||
{ label: '物理模型', rule: '使用配置指定的 MJCF 文件,不要求固定文件名。', source: '机器人/模型人员' },
|
||||
{ label: '模型依赖', rule: '按模型引用准备网格、贴图、include 等,保持路径完整。', source: '原演示工程' },
|
||||
{ label: '动作策略', rule: '只提供配置实际引用的策略;内置参数控制器不需要额外 ONNX。', source: '算法人员/原演示工程' },
|
||||
{ label: '额外显示模型', rule: '按渲染方式决定;不是所有机器人都需要 GLB、运动映射或单独控制配置。', source: '对应模型与运行器' },
|
||||
{ label: '来源说明', rule: '保留所用资源的许可与来源记录。', source: '资源提供方' },
|
||||
];
|
||||
export const legacyWalkingRequirements: WalkingRequirement[] = [
|
||||
...legacySpec.requiredFiles.map((file): WalkingRequirement => ({ key: file.id, label: file.label, path: file.path, required: true,
|
||||
category: file.path.endsWith('.onnx') ? 'policy' : file.id === 'model' ? 'render' : file.id === 'physics' ? 'model' : 'config', help: file.help, preparedBy: file.preparedBy })),
|
||||
...legacySpec.dependencyGroups.map((group): WalkingRequirement => ({ key: group.id, label: group.label, required: false, category: group.id === 'provenance' ? 'provenance' : 'dependency', help: group.userHelp })),
|
||||
];
|
||||
export const walkingStateLabels: Record<WalkingItemState, { label: string; color?: string }> = {
|
||||
not_checked: { label: '未检查' }, found_pending_validation: { label: '已找到,待校验', color: 'blue' },
|
||||
missing: { label: '缺失', color: 'red' }, checking: { label: '检查中', color: 'processing' },
|
||||
passed: { label: '通过', color: 'green' }, mismatch: { label: '不匹配', color: 'orange' }, runtime_failed: { label: '运行失败', color: 'red' },
|
||||
};
|
||||
export interface WalkingResourceContext {
|
||||
asset?: ModelAsset | null;
|
||||
sourceAssetId?: string | null;
|
||||
report?: ExperienceReport | null;
|
||||
inspectedFile?: File;
|
||||
identity?: { sourceAssetId: string; robotId: string; runtimeProfile: string } | null;
|
||||
}
|
||||
export function resolveWalkingResource(context: WalkingResourceContext, selectedFile?: File) {
|
||||
const { sourceAssetId, report, identity, asset } = context;
|
||||
const newFile = !!selectedFile && selectedFile !== context.inspectedFile;
|
||||
const scopedReport = !newFile && sourceAssetId && (!report?.walking || report.walking.sourceAssetId === sourceAssetId) ? report : null;
|
||||
const inspection = scopedReport?.walking;
|
||||
const matchedIdentity = identity?.sourceAssetId === sourceAssetId ? identity : null;
|
||||
const matchedAsset = asset?.assetId === sourceAssetId ? asset : null;
|
||||
const robotId = !newFile ? inspection?.robotId ?? matchedAsset?.metadata?.robotId ?? matchedIdentity?.robotId : null;
|
||||
const profile = !newFile ? inspection?.runtimeProfile ?? matchedAsset?.metadata?.runtimeProfile ?? matchedIdentity?.runtimeProfile : null;
|
||||
// 机器人名称不是格式识别条件;新版专用适配器也不能套用旧七策略清单。
|
||||
const legacy = inspection?.format ? inspection.format === 'legacy-walking-v1' : !newFile && !!sourceAssetId && profile === legacySpec.runtimeProfile;
|
||||
const formatLabel = legacy ? '旧版 Microduck 演示包' : inspection?.format === 'robot-package' ? 'Robot Package' : inspection?.format === 'walking-transport-v2' ? '新版发布清单(待社区接入)' : '尚未识别包格式';
|
||||
const requirements: WalkingRequirement[] = legacy ? legacyWalkingRequirements : inspection?.requirements ?? [];
|
||||
// 文件路径去重,保留所有引用动作,不把一个共享策略数成多份。
|
||||
const unique = new Map<string, WalkingRequirement>();
|
||||
for (const requirement of requirements) {
|
||||
const key = requirement.path ?? requirement.key, prior = unique.get(key);
|
||||
unique.set(key, prior ? { ...prior, ...(requirement.category === 'policy' ? { category: requirement.category, label: requirement.label } : {}), required: prior.required || requirement.required, skills: [...new Set([...(prior.skills ?? []), ...(requirement.skills ?? [])])] } : requirement);
|
||||
}
|
||||
return { newFile, scopedReport, inspection, robotId, profile, legacy, formatLabel, requirements: [...unique.values()] };
|
||||
}
|
||||
export function walkingFileCheck(report: ExperienceReport | null | undefined, sourceAssetId: string | null | undefined, key: string, path?: string): WalkingCheckItem | undefined {
|
||||
if (!sourceAssetId || !report || report.walking && report.walking.sourceAssetId !== sourceAssetId) return undefined;
|
||||
const issue = path && report.errors?.find((item) => item.path === path);
|
||||
if (issue) {
|
||||
const missing = /MISSING|NOT_FOUND/.test(issue.code);
|
||||
return { key, path, state: missing ? 'missing' : /RUNTIME_FAILED/.test(issue.code) ? 'runtime_failed' : 'mismatch', message: issue.message };
|
||||
}
|
||||
return report.walking?.items?.find((item) => path ? (item.path ?? item.key) === path : item.key === key);
|
||||
}
|
||||
export function walkingRequirementsText(requirements?: WalkingRequirement[], legacy = false) {
|
||||
if (!requirements?.length) return [profiles.defaultTitle, '', profiles.defaultDescription, '', ...walkingGeneralRequirements.map((r) => `${r.label}:${r.rule}\n准备:${r.source}`), '',
|
||||
'实际文件要求以当前包配置和适配器依赖为准。踢球、翻滚、起身等不是所有机器人的必需动作。',
|
||||
'ONNX 动作需提供声明的策略;内置控制器不额外要求策略文件。未知控制器需要运行器适配。',
|
||||
'上传成功不等于可播放;引用完整性、控制契约、运行器支持和实际试运行需要分别检查。',
|
||||
'文件大小与数量由后端控制。'].join('\n');
|
||||
return [legacy ? '旧版 Microduck 演示包专用要求(不适用于其他机器人)' : '当前机器人资源包文件要求', '',
|
||||
...requirements.map((r) => `${r.label}:${r.path ?? '按配置引用'}(${r.required ? '本包必备' : '按引用/随资源保留'})\n${r.help ?? ''}${r.skills?.length ? `\n关联动作:${r.skills.join('、')}` : ''}`),
|
||||
'', legacy ? '旧版 Microduck 播放器启动需要全部 7 个基础策略;这不是通用上传要求。' : '仅要求本包声明的动作策略,不套用其他机器人的动作清单。',
|
||||
'已找到文件不等于内容完整或可运行;系统不会用示例策略静默补全用户缺项。'].join('\n');
|
||||
}
|
||||
export function missingWalkingHelp(path: string, requirement?: WalkingRequirement, legacy = false, code?: string) {
|
||||
if (/LFS|PLACEHOLDER/.test(code ?? '')) return `发现 Git LFS 占位文件:${path}。这不是完整模型数据,请从原仓库取得实际大文件后重新上传。`;
|
||||
if (legacy) {
|
||||
const item = legacySpec.requiredFiles.find((f) => f.path === path);
|
||||
if (item?.id === 'manifest') return '未找到 manifest.json。请选择配套工具生成的完整行走包,或下载旧版 Microduck 示例查看结构。';
|
||||
if (item?.path.endsWith('.onnx')) return `缺少${item.label} ${path}。仅旧版 Microduck 播放器启动需要全部 7 个策略,请补齐后重新上传。`;
|
||||
}
|
||||
if (requirement?.skills?.length) return `缺少 ${path}:它由“${requirement.skills.join('、')}”动作引用,请补充对应策略后重新上传。`;
|
||||
return `请补充当前包配置引用的${requirement?.label ?? '资源'} ${path},保留正确路径后重新上传。`;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user