3 Commits
Author SHA1 Message Date
opendance 9eae6f3e43 feat(models): 骨骼重绑定——修复 MMD 模型 humanoid 恒为 0/22(契约 skeleton-topology 0.2.0)
根因:normalizeBoneName() 只保留 a-z0-9,**中日文字符被整个丢掉**:
'上半身'/'左ひじ'/'首' 归一化后都是空串,MMD 模型的骨名必然失配,
humanoid 覆盖率恒为 0/22 -> 不可驱动 -> 只能回退交付 GLB 并标记不可用。

修复:
1. 归一化保留 CJK/平假名/片假名/长音符/々,并把全角 ASCII(足IK)折成半角;
2. 候选表补齐四类命名(22 根 x 8-13 个候选):VRoid / Mixamo /
   MMD 标准骨架(下半身/上半身/上半身2/首/頭/左肩/左腕/左ひじ/左手首/
   左足/左ひざ/左足首/左つま先)/ 常见中文名(臀部/头/脖子/左大臂/左大腿…);
   精确匹配保证「左足IK」不会抢占「左足」;
3. Windows 客户端 humanoid_map.gd 的 CANDIDATES 由服务端表**生成写入**,
   normalize() 同步改造,parity 测试断言键/候选顺序完全一致;
4. 契约 skeleton-topology -> 0.2.0:新增 §6「内部动作标准与模型骨骼重绑定」
   (三层标准、22/16 根骨、归一化与匹配规则、实测记录);
5. 新增 4 项测试;规模 17 文件 / 229 项。

实测:奥黛塔 PMX 0/22 -> 21/22、初音未来 PMX 0/22 -> 19/22,均 drivable=true 且产出 VRM。
版本 0.4.0。
2026-09-17 00:10:07 +08:00
opendance 39bfd390e3 feat(models): 模型一律转 VRM(契约 0.5.0)+ 可用性门槛 + 管理端版本号展示
按《DSH 开发文档 v1.6》4.9 与第十一章实现,Web 端第一步:

1. 契约先行(先改 contracts/ 再同步三端):
   * model-formats.md -> 0.5.0:模型主力格式改为 VRM,所有上传模型一律转 VRM
     (.pmx/.fbx: assimp -> GLB -> VRM;glb/gltf: 包装为 VRM);
     新增 humanoid 硬门槛与"不达标回退 GLB + usable=false"的交付表;
   * data-models.md -> 0.5.0:Model 新增 usable / unusableReason,明确
     usable=false 不进入 catalog/export;format 说明改为主力 vrm;
   * VERSION 与 contract-versions.ts 同步(三端契约文件逐字节一致)。
2. 实现:
   * MODEL_CONVERT_FORMAT 默认改为 vrm(deploy/.env.example 同步);
   * 新增 isUsableModel()/unusableReason():usable 等价于"已产出 VRM",
     原因从 stats 里带出 humanoid 覆盖度;
   * catalog/export 与 catalog/version 指纹都只统计 format=vrm 的已发布模型,
     resolveDefaultModelId 同样只在可用模型中选;
   * 管理端:模型列表与审核面板显示「不可用」及原因;
   * 管理端左下角展示当前版本号(构建期从 web-server/package.json 注入
     __APP_VERSION__,与 GET /health 同源),并去掉写死的"契约 rest-api 0.1.0"。
3. 测试:新增 test/model-usability.spec.ts 5 项;规模 16 文件 / 225 项。
4. 版本 0.3.0。
2026-09-17 00:05:02 +08:00
opendance eebccd55b4 fix(models): MMD 材质对齐——补回双面标志、规范化 PBR 参数、可选 unlit 着色
背景(用户反馈 + 本地用真 Assimp 6.0.4 复现):
PMX 的着色模型(卡通阶梯 + 球面贴图 + 平坦环境光)与 glTF PBR 不是一回事,
Assimp 转换会丢掉其中一部分。实测样本【奥黛塔】_by_原神.zip(39 个材质):

1. 主因:PMX 里 36 个材质带 drawFlag bit0(不剔除背面),而导出的 GLB 里
   doubleSided 一个都没有 -> 头发/裙摆/睫毛这类薄片被单面剔除,
   看起来就是颜色/贴图不对;
2. PMX 的 shininess/specular/ambient 与 PBR 无映射;Assimp 还会带上
   KHR_materials_specular / KHR_materials_volume 等与 MMD 无关的扩展;
3. Assimp 把 accessor.min/max 写坏(实测 min = 2.2250738585072014e-308),
   Godot 等客户端用它算包围盒。

修复:
1. 新增 src/models/pmx-materials.ts:只读 PMX 材质段(布局与权威库 mmd-parser
   一致,注意贴图索引宽度是 1 字节),拿到 name/diffuse/specular/shininess/
   ambient/drawFlag/球面贴图/toon/faceCount;
2. 新增 src/models/glb-materials.ts:转换后按索引把 PMX 参数补回 GLB ——
   doubleSided、metallicFactor=0、roughnessFactor=clamp(1-shininess/100,0.5,1)、
   baseColorFactor x diffuse(含 alpha);清掉与 MMD 无关的扩展;
   修正全部浮点 accessor 的 min/max;支持 KHR_materials_unlit(MODEL_SHADING);
3. 抽出 src/common/glb-chunks.ts(JSON/BIN chunk 读写),vrm-writer 改为复用;
4. 能力边界写清楚:PMX 的球面贴图(该模型 15 项)与 toon 阶梯在 glTF core 里
   没有对应槽位,任何转换器都无法保留,数量写进 conversion_note 供审核查看;
5. 新增 test/mmd-materials.spec.ts 9 项;规模 15 文件 / 220 项;
6. 新增 MODEL_SHADING 配置(默认 pbr,可选 unlit),文档同步(README.md/.txt、DSH.md、.env.example)。
2026-09-16 18:55:25 +08:00
36 changed files with 1486 additions and 136 deletions
+13 -2
View File
@@ -101,7 +101,7 @@ opendance-web/
│ ├── admin/ # React 管理端
│ │ ├── src/components/ModelReviewPanel.tsx # 模型审核面板 + 骨骼详细界面
│ │ └── src/lib/bone-tree.ts # 骨骼树过滤(搜索保留祖先链)
│ ├── test/ # 单元测试 + 端到端冒烟(14 文件 / 211 项)
│ ├── test/ # 单元测试 + 端到端冒烟(17 文件 / 229 项)
│ │ # mmd-vmd 31 / model-archive 24 / model-inspector 25
│ │ # / model-thumbnail 8 / admin-bone-filter 8
│ │ # / preprocess 25 / init-env 16 / admin-port 16
@@ -196,6 +196,7 @@ ASSIMP_BIN=assimp # 可选;上传.zip 模型包或.pmx/.fbx 单文
MODEL_CONVERT_FORMAT=glb # PMX/FBX 交付格式:glb(默认)| vrm
# vrm = GLB 之上补 VRMC_vrm 扩展;humanoid 不全则回退 GLB
# 产物一律 `assimp info` 回读校验
MODEL_SHADING=pbr # 转换后模型着色:pbr(默认)| unlit(KHR_materials_unlit,颜色=贴图)
MODEL_CONVERT_PMX="Hatsune Miku.pmx" # 压缩包内优先选用的 PMX 文件名(大小写不敏感)
MODEL_CONVERT_TIMEOUT_MS=180000
DEFAULT_MODEL_ID=1 # 可选;未设置时按 src/config/default-model.ts 的种子匹配
@@ -283,6 +284,16 @@ POST /api/models ─┬─.glb /.vrm /.gltf ─▶ importModelFile() 直接导
**每一步产物都必须用 `assimp info` 回读校验**:实测 Assimp 会"写出损坏文件"
(FBX 导出退出码 11、回读报 `FBX-DOM no Objects dictionary found`),只看退出码
会把坏文件入库。
- **MMD 材质对齐(v0.2.5)**: Assimp 会丢掉 PMX 的**双面(不剔除背面)**标志与着色参数
(实测 39 个材质里 36 个双面,导出后 `doubleSided` 一个都没有 → 头发/裙摆/睫毛被单面剔除)。
转换后由 `models/pmx-materials.ts`(只读 PMX 材质段)+ `models/glb-materials.ts` 补:
`doubleSided`、`metallicFactor=0`、`roughnessFactor=clamp(1-shininess/100,0.5,1)`、
`baseColorFactor x diffuse`、清掉 `KHR_materials_specular/volume/transmission/ior`、
修正 Assimp 写坏的 `accessor.min/max`。PMX 的球面贴图与 toon 阶梯在 glTF core 里
没有槽位,数量写入 `conversion_note`。`MODEL_SHADING=unlit` 可交付"颜色=贴图"的平涂观感。
- **模型一律转 VRM(v0.5.0)**: `MODEL_CONVERT_FORMAT` 默认 `vrm`; humanoid 必需骨齐全才产出
VRM, 不达标时回退交付 GLB 且 `usable=false`(可入库可审核, **不进入 `catalog/export`**),
待按 `skeleton-topology` 标准重绑定骨骼后重新导入即转为可用。
- **入库后自动**: `inspectModelFile()` 分析写入 `models.stats`
(迁移 `AddModelStats1789460000000`,新增 `models.stats TEXT`);
`renderModelThumbnail()` 写入 `models.thumbnail_asset_id` / `thumbnailUrl`。
@@ -335,7 +346,7 @@ POST /api/models ─┬─.glb /.vrm /.gltf ─▶ importModelFile() 直接导
T-pose 角色图;真实 10MB VRM(83 关节、5307 顶点)单张耗时 60-121ms(中位 79ms)。
- 管理端 3D 预览放开到 `vrm/glb/gltf`(`fbx` 仍提示"仅归档,请先转换为 GLB/VRM");
列表页显示 40px 缩略图。
- 测试:`npx vitest run` -> **14 个文件 / 211 项通过**
- 测试:`npx vitest run` -> **17 个文件 / 229 项通过**
(`model-inspector` 25、`model-thumbnail` 8、`admin-bone-filter` 8、
`model-archive` 24、`mmd-vmd` 31、`preprocess` 25、`init-env` 16、
`admin-port` 16、`access-log` 9、`vrm-inspector` 6)。
+30 -9
View File
@@ -10,7 +10,26 @@ OpenDance Studio **阶段一**: Web 管理服务端(NestJS + TypeORM + 现有 My
## 状态
**阶段一已完成**: T-WEB-001 -> T-WEB-010 全部落地,当前版本 **v0.2.4**(契约 `rest-api / data-models / model-formats 0.4.0`、`database 0.3.0`)。
**阶段一已完成**: T-WEB-001 -> T-WEB-010 全部落地,当前版本 **v0.3.0**(契约 `rest-api / data-models / model-formats 0.4.0`、`database 0.3.0`)。
v0.3.0 修订(**VRM 主力化**,契约 data-models / model-formats -> 0.5.0):
1. **所有上传的模型一律转 VRM**:`MODEL_CONVERT_FORMAT` 默认改为 `vrm` —— `.pmx/.fbx` 经 `assimp -> GLB -> VRM 1.0`,`glb/gltf` 导入后包装为 VRM;支持库沿用自研 `vrm-writer`/`vrm-inspector` + Assimp(可选 `@gltf-transform/core` 做结构校验);
2. **humanoid 门槛与可用性标记**(`usable`):必需骨齐全才产出 VRM;不达标(如 MMD 日文骨名 `0/22`)时回退交付 GLB、`usable=false` —— **可入库、可审核,但不进入 `catalog/export`**(`/api/catalog/version` 指纹同步过滤);待骨骼重绑定后重新导入即转为可用;
3. 模型列表与审核面板显示 **「不可用」及其原因**(`unusableReason`,例如 `humanoid 不达标(0/22),未产出 VRM`);`resolveDefaultModelId` 只在可用模型中选择;
4. **管理端左下角展示当前版本号**(v1.5 文档第十一章要求):构建期从 `web-server/package.json` 注入 `v__APP_VERSION__`,与 `GET /health` 的 version **同源**;顺带修掉右下角写死的 `契约 rest-api 0.1.0`;
5. 新增 5 项测试(`test/model-usability.spec.ts`);规模 16 文件 / 225 项。
v0.2.5 修订:
**MMD 材质/着色对齐**:PMX 的着色模型(卡通阶梯 + 球面贴图 + 平坦环境光)与 glTF PBR 不是一回事,Assimp 转换会丢东西。实测样本 `【奥黛塔】_by_原神.zip`(39 个材质):
1. **修复"看起来颜色/贴图不对"的主因**:PMX 里 **36 个材质带"不剔除背面"标志**,而 Assimp 导出的 GLB 里 `doubleSided` **一个都没有** -> 头发/裙摆/睫毛这类薄片被单面剔除。现在新增 `pmx-materials.ts`(只读 PMX 材质段)并在转换后按 `drawFlag` 补回 `doubleSided`;
2. **PBR 参数规范化**(`glb-materials.ts`):`metallicFactor=0`、`roughnessFactor=clamp(1-shininess/100, 0.5, 1)`(MMD 常见 shininess=1 -> 0.99 哑光)、`baseColorFactor` 乘上 PMX diffuse(含 alpha);清掉 Assimp 带出的、与 MMD 无关的 `KHR_materials_specular` / `volume` / `transmission` / `ior` / `emissive_strength`;顺手修正 Assimp 写坏的 `accessor.min/max`(实测 min 被写成 `2.2e-308`,Godot 用它算包围盒);
3. **新增 `MODEL_SHADING`**(默认 `pbr`,可选 `unlit`):`unlit` 会给每个材质写 `KHR_materials_unlit`,颜色 = 贴图 x baseColorFactor、与场景光照无关,最接近 MMD 的平涂观感(three.js 与 Godot 都支持);
4. **说明(能力边界)**:PMX 的**球面贴图(该模型 15 项)与卡通 toon 阶梯在 glTF core 里没有对应槽位**,任何转换器都无法原样保留;服务端会把数量写进 `conversion_note`(审核面板可见),不会假装保留;
5. 新增 9 项测试(`test/mmd-materials.spec.ts`);测试规模 15 文件 / 220 项;
6. **注意**:材质修正在**转换时**生效,已有模型需重新导入(不是 `reanalyze-models.mjs`,它只刷新分析与缩略图)。
v0.2.4 修订:
@@ -66,15 +85,15 @@ v0.2.0 主要变更:
3. 取得发布包并校验(地址用你们自己的制品库替换; 下面是本仓库的发布地址)
```bash
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.2.4/opendance-web-v0.2.4.tar.gz
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.2.4/SHA256SUMS
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.4.0/opendance-web-v0.4.0.tar.gz
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.4.0/SHA256SUMS
sha256sum -c SHA256SUMS # 期望输出 "OK"
```
4. 解压并生成配置(交互式引导,逐项问答,口令不回显)
```bash
tar -xzf opendance-web-v0.2.4.tar.gz && cd opendance-web-v0.2.4
tar -xzf opendance-web-v0.4.0.tar.gz && cd opendance-web-v0.4.0
bash deploy/init-env.sh
```
@@ -144,8 +163,8 @@ FLUSH PRIVILEGES;
### 5. 部署步骤
```bash
tar -xzf opendance-web-v0.2.4.tar.gz
cd opendance-web-v0.2.4
tar -xzf opendance-web-v0.4.0.tar.gz
cd opendance-web-v0.4.0
bash deploy/init-env.sh # 首次启动引导: 逐项问答生成 deploy/.env(见下)
bash deploy/install.sh # 已以 root 登录, 不需要 sudo
```
@@ -286,6 +305,7 @@ bash /opt/opendance/deploy/ctl.sh status | restart | logs
| 服务本机 curl 通、外部访问不了 | `bash deploy/check-access.sh` 一次定位:打印 `HOST`/`PORT`、实际监听地址、对外 IP 自测、80/443 有无反代、防火墙放行情况,并给出修复命令 |
| 管理页面打开是 404 | 说明访问的是软件 API 端口(默认 3000);管理页面在管理端端口(默认 3001) |
| 上传 `.zip` / `.pmx` / `.fbx` 报转换失败(ENOENT / Assimp 不可用) | PMX/FBX 转换依赖外部 Assimp:`apt-get install -y assimp-utils`(RHEL 系 `dnf install -y assimp`,`install.sh` 现在会尝试自动安装)。装好后**不需要重启服务**;若不在服务 PATH 中,在 `deploy/.env` 设 `ASSIMP_BIN` 为绝对路径。只上传 `.glb` / `.vrm` 则不需要它 |
| 导入后的模型颜色/观感与 MMD 里不一致 | PMX 的着色(卡通阶梯、球面贴图、平坦环境光)在 glTF 里没有等价实现。v0.2.5 起会补回**双面**、规范化 PBR 参数并清掉无关扩展;想要最接近 MMD 的平涂颜色,把 `MODEL_SHADING=unlit` 写进 `deploy/.env` 后**重新导入**模型。球面贴图与 toon 阶梯无法保留,数量会记在模型的"转换说明"里 |
| 列表/审核里的缩略图是"白模"(纯白模型) | v0.2.4 前的缩略图渲染器不采样贴图,而 MMD 模型的 `baseColorFactor` 是白色。升级到 v0.2.4 后重新生成缩略图:`cd /opt/opendance/web-server && node scripts/reanalyze-models.mjs --url http://127.0.0.1:3000 --force` |
| 导入模型返回 **500 Internal server error** | 老库上多为 `models.stats` 超长(骨骼树按骨骼展开,643 骨骼即 70,980 字节 > TEXT 上限):执行 `ALTER TABLE models MODIFY stats MEDIUMTEXT NULL;` 或部署 v0.2.3(`install.sh` 会自动跑迁移)。v0.2.3 起服务端另有兜底,不会再 500 |
| 安装时报 `command not found` / 退出码 127,且提示指向 `deploy/.env` 某一行 | 该行的值含空格或 shell 元字符却没加引号,被 shell 当成命令执行了。按预检提示给这个值加引号(如 `MODEL_CONVERT_PMX="Hatsune Miku.pmx"`)后重跑;`deploy/env-lib.sh` 会提前拦住并给出行号 |
@@ -317,12 +337,12 @@ npm run dev # http://localhost:5173(/api 与 /health 代理到 3000)
cd web-server
npm run contracts:check # 契约版本一致性
npm run typecheck # TypeScript 严格检查
npm run test # 211 项单元测试 / 14 个文件(VMD 31、模型压缩包 27、
npm run test # 229 项单元测试 / 17 个文件(VMD 31、模型压缩包 27、
# 模型检查器 25、缩略图 8、骨骼过滤 8、
# 预处理 25、init-env 16、admin-port 16、
# access-log 9、VRM 检查器 6、.env 预检 12、
# Assimp 定位与安装 13、stats 容量与编码 12、
# 缩略图贴图采样 6)
# 缩略图贴图采样 6、MMD 材质对齐 9、模型可用性 5、MMD 骨名重绑定 4)
npm run build # 生产构建
npm run start:prod & # 启动
npm run test:smoke # 57 项端到端冒烟(需要数据库可连通)
@@ -345,8 +365,9 @@ cd ../admin && npm run build # 管理端构建
| `STORAGE_DIR` | `/var/lib/opendance/storage` | 上传文件存储目录(原生部署默认值) |
| `UPLOAD_MAX_BYTES` | `536870912`(512 MiB) | 单文件上限。反向代理层的同名限制必须不小于此值,否则大模型上传会在代理层被拒(nginx `client_max_body_size` / IIS `requestLimits`),详见 `deploy/proxy/README.md` |
| `ASSIMP_BIN` | `assimp` | Assimp 可执行文件(`install.sh` 会自动安装并解析出绝对路径写入此项)。`.pmx/.fbx` 模型转换与 FBX/glTF 动作预处理需要;缺失时上传会失败并给出安装命令,只上传 `.glb/.vrm` 不受影响 |
| `MODEL_CONVERT_FORMAT` | `glb` | 需要转换的模型(PMX/FBX)的交付格式:`glb`(两个客户端都原生加载)或 `vrm`。`vrm` = 在 GLB 之上补 `VRMC_vrm` 扩展(humanoid 骨骼 / 表情语义),humanoid 骨骼映射不全时自动回退交付 GLB 并写进 `conversion_note`。产物一律用 `assimp info` 回读校验 |
| `MODEL_CONVERT_FORMAT` | `vrm` | 需要转换的模型(PMX/FBX)的交付格式:`glb`(两个客户端都原生加载)或 `vrm`。`vrm` = 在 GLB 之上补 `VRMC_vrm` 扩展(humanoid 骨骼 / 表情语义),humanoid 骨骼映射不全时自动回退交付 GLB 并写进 `conversion_note`。产物一律用 `assimp info` 回读校验 |
| `MODEL_CONVERT_PMX` | `"Hatsune Miku.pmx"` | 压缩包内优先选用的 PMX 文件名(大小写不敏感);找不到时按「格式优先级 -> 目录最浅 -> 文件最大」挑选 |
| `MODEL_SHADING` | `pbr` | 转换后模型的着色模式。`pbr`:标准 PBR,并按 PMX 参数修正 `doubleSided` / `metallic` / `roughness`;`unlit`:写 `KHR_materials_unlit`,颜色 = 贴图 x `baseColorFactor`、与场景光照无关,最接近 MMD 的平涂观感 |
| `MODEL_CONVERT_TIMEOUT_MS` | `180000` | 单次转换超时(毫秒) |
| `DEFAULT_MODEL_ID` | - | 可选:显式指定默认模型 id;不设置时按源码种子 `src/config/default-model.ts` 匹配,再回落到 VRM 优先规则 |
| `CONTRACTS_DIR` | - | 可选:契约目录,设置后 `/health` 反映实时契约版本(原生部署默认指向 `/opt/opendance/contracts`) |
+64 -8
View File
@@ -1,5 +1,5 @@
================================================================
OpenDance Studio -- Web 管理服务端 v0.2.4 使用说明
OpenDance Studio -- Web 管理服务端 v0.4.0 使用说明
================================================================
本服务端是 OpenDance Studio 三端中的第一端, 负责管理歌曲、VRM 模型与
@@ -8,6 +8,52 @@ OpenDance Studio -- Web 管理服务端 v0.2.4 使用说明
重要: 本服务端 不部署、不管理 MySQL。数据库为部署方提供的现有实例,
连接信息通过 .env 注入。
v0.4.0 修订 - 骨骼重绑定(契约 skeleton-topology -> 0.2.0)
1. 修复 humanoid 覆盖率恒为 0/22 的根因: normalizeBoneName() 原先只保留 a-z0-9,
中日文字符被整个丢掉(上半身/左ひじ/首 全变空串)。现在保留 CJK/假名,
并把全角 ASCII(足IK)折成半角。
2. 候选表补齐四类命名: VRoid / Mixamo / MMD 标准骨架(下半身/上半身/上半身2/
首/頭/左肩/左腕/左ひじ/左手首/左足/左ひざ/左足首/左つま先)/ 常见中文名;
精确匹配保证 左足IK 不会抢占 左足。
3. 服务端与 Windows 客户端逐字一致: humanoid_map.gd 的 CANDIDATES 由服务端表
生成写入, normalize() 同步改造(parity 测试断言)。
4. 实测: 奥黛塔 PMX 0/22 -> 21/22、初音未来 PMX 0/22 -> 19/22, 均 drivable=true
并产出 VRM(此前只能回退 GLB 并标记不可用)。
5. 契约 skeleton-topology -> 0.2.0: 新增第 6 节"内部动作标准与模型骨骼重绑定"。
6. 新增 4 项测试; 规模 17 文件 / 229 项。
v0.3.0 修订 - VRM 主力化(契约 data-models / model-formats -> 0.5.0)
1. 所有上传的模型一律转 VRM: MODEL_CONVERT_FORMAT 默认改为 vrm -
.pmx/.fbx 经 assimp -> GLB -> VRM 1.0, glb/gltf 导入后包装为 VRM。
2. humanoid 门槛与可用性标记(usable): 必需骨齐全才产出 VRM; 不达标
(如 MMD 日文骨名 0/22)时回退交付 GLB、usable=false - 可入库、可审核,
但不进入 catalog/export(指纹同步过滤); 待骨骼重绑定后重新导入即转为可用。
3. 模型列表与审核面板显示"不可用"及原因; 默认模型只在可用模型中选择。
4. 管理端左下角展示当前版本号(构建期从 web-server/package.json 注入,
与 GET /health 的 version 同源)。
5. 新增 5 项测试; 规模 16 文件 / 225 项。
v0.2.5 修订 - MMD 材质/着色对齐
PMX 的着色模型(卡通阶梯 + 球面贴图 + 平坦环境光)与 glTF PBR 不是一回事,
Assimp 转换会丢东西。实测样本 【奥黛塔】_by_原神.zip(39 个材质):
1. 修复"看起来颜色/贴图不对"的主因: PMX 里 36 个材质带"不剔除背面"标志,
而 Assimp 导出的 GLB 里 doubleSided 一个都没有 -> 头发/裙摆/睫毛这类
薄片被单面剔除。现在新增 pmx-materials.ts(只读 PMX 材质段), 转换后按
drawFlag 补回 doubleSided。
2. PBR 参数规范化(glb-materials.ts): metallicFactor=0、
roughnessFactor=clamp(1-shininess/100, 0.5, 1)、baseColorFactor 乘上 PMX
diffuse(含 alpha); 清掉 Assimp 带出的、与 MMD 无关的 KHR_materials_specular
/ volume / transmission / ior / emissive_strength; 顺手修正 Assimp 写坏的
accessor.min/max(实测 min 被写成 2.2e-308, Godot 用它算包围盒)。
3. 新增 MODEL_SHADING(默认 pbr, 可选 unlit): unlit 给每个材质写
KHR_materials_unlit, 颜色 = 贴图 x baseColorFactor、与场景光照无关,
最接近 MMD 的平涂观感(three.js 与 Godot 都支持)。
4. 能力边界: PMX 的球面贴图(该模型 15 项)与 toon 阶梯在 glTF core 里没有
对应槽位, 任何转换器都无法原样保留; 数量会写进 conversion_note。
5. 新增 9 项测试(test/mmd-materials.spec.ts); 规模 15 文件 / 220 项。
6. 注意: 材质修正在转换时生效, 已有模型需重新导入(reanalyze-models.mjs
只刷新分析与缩略图, 不会重转材质)。
v0.2.4 修订
1. 修复缩略图"白模": 缩略图渲染器原先刻意不解码贴图, 只用 baseColorFactor
上色; 而 MMD(PMX 转换)模型的 baseColorFactor 基本都是白色, 于是列表页与
@@ -69,11 +115,11 @@ v0.2.1 修订
2. 准备一个现有的 MySQL / MariaDB 实例, 并建好库与账号(见下方"前置要求")
本项目不会创建数据库本身
3. 取得发布包并校验(地址用你们自己的制品库替换)
curl -LO https://<制品库地址>/opendance-web-v0.2.4.tar.gz
curl -LO https://<制品库地址>/opendance-web-v0.4.0.tar.gz
curl -LO https://<制品库地址>/SHA256SUMS
sha256sum -c SHA256SUMS # 期望输出 "OK"
4. 解压并生成配置(交互式引导, 逐项问答, 口令不回显)
tar -xzf opendance-web-v0.2.4.tar.gz && cd opendance-web-v0.2.4
tar -xzf opendance-web-v0.4.0.tar.gz && cd opendance-web-v0.4.0
bash deploy/init-env.sh
5. 安装(建用户与目录 -> 装依赖 -> 迁移 -> 注册系统服务 -> 等健康检查)
bash deploy/install.sh
@@ -131,8 +177,8 @@ v0.2.1 修订
(本项目不会创建数据库本身, 也不需要 GRANT OPTION / FILE / SUPER 等管理权限)
部署步骤
tar -xzf opendance-web-v0.2.4.tar.gz
cd opendance-web-v0.2.4
tar -xzf opendance-web-v0.4.0.tar.gz
cd opendance-web-v0.4.0
bash deploy/init-env.sh # 首次启动引导: 逐项问答生成 deploy/.env(见下)
bash deploy/install.sh # 已以 root 登录, 不需要 sudo
@@ -263,7 +309,12 @@ deploy/.env 初始化引导(deploy/init-env.sh)
(RHEL 系 dnf install -y assimp; install.sh 现在会尝试自动安装)。
装好后不需要重启服务; 若不在服务 PATH 中, 在 deploy/.env 里把 ASSIMP_BIN
设为绝对路径。只上传 .glb / .vrm 则不需要它。
- 列表/审核里的缩略图是"白模"(纯白模型)
- 导入后的模型颜色/观感与 MMD 里不一致
PMX 的着色(卡通阶梯、球面贴图、平坦环境光)在 glTF 里没有等价实现。
v0.2.5 起会补回双面、规范化 PBR 参数并清掉无关扩展; 想要最接近 MMD 的
平涂颜色, 把 MODEL_SHADING=unlit 写进 deploy/.env 后重新导入模型。
球面贴图与 toon 阶梯无法保留, 数量会记在模型的"转换说明"里。
- 列表/审核里的缩略图是"白模"(纯白模型)
v0.2.4 前的缩略图渲染器不采样贴图, 而 MMD 模型的 baseColorFactor 是白色。
升级到 v0.2.4 后重新生成缩略图: cd /opt/opendance/web-server &&
node scripts/reanalyze-models.mjs --url http://127.0.0.1:3000 --force
@@ -302,11 +353,12 @@ deploy/.env 初始化引导(deploy/init-env.sh)
cd web-server
npm run contracts:check # 契约版本一致性
npm run typecheck # TypeScript 严格检查
npm run test # 211 项单元测试 / 14 个文件(VMD 31、模型压缩包 24、
npm run test # 229 项单元测试 / 17 个文件(VMD 31、模型压缩包 24、
# 模型检查器 25、缩略图 8、骨骼过滤 8、
# 预处理 25、init-env 16、admin-port 16、
# access-log 9、VRM 检查器 6、.env 预检 12、
# Assimp 定位与安装 13、stats 容量与编码 12、缩略图贴图 6)
# Assimp 定位与安装 13、stats 容量与编码 12、缩略图贴图 6、
# MMD 材质对齐 9、模型可用性 5、MMD 骨名重绑定 4)
npm run build # 生产构建
npm run start:prod & # 启动
npm run test:smoke # 57 项端到端冒烟(需要数据库可连通)
@@ -364,6 +416,10 @@ deploy/.env 初始化引导(deploy/init-env.sh)
MODEL_CONVERT_PMX 压缩包内优先选用的 PMX 文件名(默认 "Hatsune Miku.pmx",
大小写不敏感); 找不到时按「格式优先级 -> 目录最浅 ->
文件最大」挑选
MODEL_SHADING 转换后模型的着色模式: pbr(默认, 标准 PBR 并按 PMX 参数修正
doubleSided/metallic/roughness)| unlit(写 KHR_materials_unlit,
颜色 = 贴图 x baseColorFactor, 与场景光照无关, 最接近 MMD
的平涂观感)
MODEL_CONVERT_TIMEOUT_MS
单次转换超时(毫秒, 默认 180000)
DEFAULT_MODEL_ID 可选: 显式指定默认模型 id; 不设置时按源码种子
+3 -3
View File
@@ -2,7 +2,7 @@
# 规则:任何字段级变更必须提升对应条目版本,并回到 opendance-web 修改后再向另两端建迁移任务。
rest-api: 0.4.0
websocket-keypoints: 0.1.0
data-models: 0.4.0
skeleton-topology: 0.1.0
model-formats: 0.4.0
data-models: 0.5.0
skeleton-topology: 0.2.0
model-formats: 0.5.0
database: 0.3.0
+4 -2
View File
@@ -1,4 +1,4 @@
# contracts/data-models.md - 数据模型契约 v0.4.0
# contracts/data-models.md - 数据模型契约 v0.5.0
Web 服务端是唯一权威定义,本文件是另两端消费的**稳定视图**。
字段名在 JSON 中统一 `camelCase`;数据库列名 `snake_case`(见 `database.md`)。
@@ -96,8 +96,10 @@ rejected 已驳回
|--|--|--|--|
| `id` | number | 读 | |
| `name` | string | ✅ | 模型名称,<=200 |
| `format` | enum | ✅ | `glb` / `vrm`(主力)/ `gltf` / `fbx`(历史数据)。上传的 PMX/FBX 会被服务端转换成 glb 或 vrm 再入库,见 model-formats.md 1.1 |
| `format` | enum | ✅ | `vrm`(主力)/ `glb`(回退或历史数据)/ `gltf` / `fbx`。**所有上传模型一律转换为 VRM**,只有 humanoid 不达标时回退为 `glb` 并置 `usable=false`,见 model-formats.md 1.1 |
| `vrmVersion` | string\|null | 读 | `0.x` / `1.0`,非 VRM 为 null |
| `usable` | boolean | 读 | **是否可被客户端使用**:等价于"已产出 VRM"(`format=vrm`)。`false` 的模型**不出现在 `catalog/export`**(v0.5.0) |
| `unusableReason` | string\|null | 读 | `usable=false` 时的原因,例如 `humanoid 不达标(0/22),未产出 VRM` |
| `isPrimary` | boolean | | 全局默认模型;**同一时刻全库至多一个 `true`** |
| `fileUrl` | string | 读 | |
| `fileSize` | number | 读 | |
+26 -5
View File
@@ -1,20 +1,41 @@
# contracts/model-formats.md - 模型与动作格式契约 v0.4.0
# contracts/model-formats.md - 模型与动作格式契约 v0.5.0
## 1. 角色模型(models)
**系统以 GLB / VRM 为主力格式**(两个客户端都原生加载),其余格式一律在服务端转换。
**v0.5.0 起模型主力格式为 VRM**: **所有上传的模型都转换为 VRM**(`MODEL_CONVERT_FORMAT`
默认 `vrm`);GLB 退为**转换中间产物**与 **humanoid 不达标时的回退交付**。
两个客户端(Godot `godot-vrm` / 管理端 `@pixiv/three-vrm`)都原生加载 VRM。
| 格式 | 扩展名 | 支持级别 | 服务端行为 |
|--|--|--|--|
| glTF Binary | `.glb` | **主力(P0)** | **直接导入**,不重编码 |
| VRM | `.vrm` | **主力(P0)** | **直接导入**; = GLB + VRM 扩展(humanoid / 表情 / springBone / meta) |
| glTF Binary | `.glb` | 输入(P0) | 导入后**包装为 VRM**(含 `VRMC_vrm`);humanoid 不齐时保留 GLB 并标记 `usable=false` |
| glTF | `.gltf` (+ `.bin`, 贴图) | P1 | 直接导入(分离文件在 zip 内可用;单文件上传会缺.bin) |
| MMD 压缩包 | `.zip` | P1 | **自动搜索包内可用模型**:优先直接导入 `.vrm`/`.glb`/`.gltf`,否则转换 `.pmx`/`.fbx`,见 1.1 |
| MMD 模型 | `.pmx` | P2(输入) | 服务端转换(优先 GLB、其次 VRM);单文件上传无贴图 |
| FBX | `.fbx` | P2(输入) | 服务端转换(优先 GLB、其次 VRM) |
| MMD 模型 | `.pmx` | P2(输入) | 服务端转换:`assimp -> GLB -> VRM`;单文件上传无贴图 |
| FBX | `.fbx` | P2(输入) | 服务端转换:`assimp -> GLB -> VRM` |
### 1.1 上传与转换策略
**v0.5.0 起的一律转换链路**:
```
.vrm -> 直接导入(已是 VRM)
.glb / .gltf -> 包装为 VRM 1.0(写 VRMC_vrm)
.pmx / .fbx -> assimp -> GLB -> 包装为 VRM 1.0
.zip -> 自动搜索包内模型,按上面三种处理
```
**humanoid 门槛(硬性)**: VRM 1.0 要求 humanoid 必需骨骼齐全。服务端判定规则:
| 情况 | 交付 | `models.usable` | 是否进入客户端目录 |
|--|--|--|--|
| humanoid 必需骨齐全 | **VRM**(`format=vrm`, `vrmVersion=1.0`) | `true` | ✅ 可发布、可选用 |
| humanoid 不齐(如 MMD 日文骨名未重绑定) | 回退交付 **GLB**, `vrmVersion=null`, `conversionNote` 注明原因 | `false` | ❌ 不进入 `catalog/export` |
即:**不达标模型仍可入库与审核,但标记为不可用、不进入已发布目录**;
待骨骼按 `skeleton-topology.md` 的标准重绑定成功后重新转换即变为可用。
**`.glb` / `.vrm` / `.gltf` 直接导入**(不重编码,零损失);**`.pmx` / `.fbx` 由服务端转换**:
**优先 GLB,其次 VRM**。
+63 -1
View File
@@ -1,4 +1,4 @@
# contracts/skeleton-topology.md - 骨骼拓扑契约 v0.1.0
# contracts/skeleton-topology.md - 骨骼拓扑契约 v0.2.0
**唯一拓扑:MediaPipe Pose 33 点。禁止引入 SMPL 及其衍生拓扑(许可风险)。**
@@ -123,3 +123,65 @@ spine = angle(neck, pelvis, midpoint(left_ankle, right_ankle))
**DTW 序列结构(冻结)**:每帧 = `[33 x (x, y, z), 9 个关节角余弦] = 108 维`。
低置信度点(`visibility < 0.5`)在插值阶段由相邻帧线性补全,不参与代价计算。
---
## 6. 内部动作标准与模型骨骼重绑定(v0.2.0)
**目的**:动作数据必须能匹配系统内的任意模型,因此把"关键点标准 + 骨架标准 + humanoid 标准"
冻结成本节,模型上传时按此**重绑定骨骼**,再包装为 VRM。
### 6.1 三层标准
| 层 | 标准 | 权威实现 |
|--|--|--|
| 关键点 | MediaPipe Pose **33 点**(顺序见 §1),动作一律先转成关键点序列(NDJSON)再入库 | `preprocess/`(BVH / VMD / FBX -> 33 点) |
| 动作骨架 | **MMD 标准骨架**(静止比例实测自参考 PMX; `足IK` 带位移时走两骨骼腿部 IK,否则 FK) | `preprocess/mmd-skeleton.ts` |
| 模型骨架 | **22 根 humanoid 规范骨**(顺序即层级,父在前),其中 **16 根为必需**(§6.2) | `models/model-inspector.ts` 的 `HUMANOID_CANDIDATES` |
评分只依赖 33 点关键点序列,**与模型骨架解耦**;因此"动作能匹配任何模型"的充要条件是
**模型可驱动**(16 根必需骨齐全,`drivable=true`)。
### 6.2 22 根 humanoid 规范骨与 16 根必需骨
```
hips -> spine -> chest -> upperChest -> neck -> head
├── leftShoulder -> leftUpperArm -> leftLowerArm -> leftHand
└── rightShoulder -> rightUpperArm -> rightLowerArm -> rightHand
hips -> leftUpperLeg -> leftLowerLeg -> leftFoot -> leftToes
hips -> rightUpperLeg -> rightLowerLeg -> rightFoot -> rightToes
```
必需 16 根(缺一即 `drivable=false`):`hips`、`spine`、`neck`、`head`、
`leftUpperArm`、`leftLowerArm`、`leftHand`、`rightUpperArm`、`rightLowerArm`、`rightHand`、
`leftUpperLeg`、`leftLowerLeg`、`leftFoot`、`rightUpperLeg`、`rightLowerLeg`、`rightFoot`。
### 6.3 重绑定规则(模型上传时执行,服务端与三端一致)
1. **归一化**:小写 → 只保留 `a-z0-9` + **中文/日文(CJK、平假名、片假名、长音符、々)**;
**全角 ASCII(A-Z a-z 0-9)折成半角**(MMD 常写「足IK」「つま先IK」)。
*v0.2.0 修正*:此前只保留 `a-z0-9`, MMD 骨名(`上半身`/`左ひじ`/`首`)被归一化成空串,
humanoid 覆盖率恒为 **0/22**。
2. **剥前缀**:只剥 `J_Bip` / `mixamorig` / `Bip01`; **不剥** `J_Aim_` / `J_Roll_` / `J_Sec_`
(VRoid 的扭转辅助骨,剥了会与真正的骨骼撞名)。
3. **变体**: `left/right` 与 `l/r` 互转(`leftupperarm` <-> `lupperarm`)。
4. **精确匹配**:归一化+变体后的名字必须与候选表**完全相等**(前缀不匹配),
因此 `左足IK`(-> `左足ik`)不会抢占 `左足`(`leftUpperLeg`)。
5. **候选表覆盖四类命名**(顺序即优先级;服务端与客户端**逐字一致**,由测试断言):
VRoid(`J_Bip_C_Hips` 等)、Mixamo(`mixamorig:LeftArm`)、
**MMD 标准骨架(`下半身`/`上半身`/`上半身2`/`首`/`頭`/`左肩`/`左腕`/`左ひじ`/`左手首`/`左足`/`左ひざ`/`左足首`/`左つま先`)**、
常见中文名(`臀部`/`头`/`脖子`/`左大臂`/`左小臂`/`左大腿`/`左脚` 等)。
6. **结果写入 VRM**:命中结果写成 `VRMC_vrm.humanoid.humanBones` 的**节点索引**(VRM 规范
不要求节点名固定,因此以索引为准,不改动几何与贴图);未命中的骨骼保留原名作为附加骨。
7. **结论必须上报**: `models.stats.humanoidMapped` / `humanoidTotal` / `missingRequiredBones` /
`drivable` 四项写库,审核界面展示;`usable` 与是否进入客户端目录见 model-formats.md 1.1。
### 6.4 实测(v0.2.0 重绑定后)
| 样本 | 重绑定前 | 重绑定后 | 结果 |
|--|--|--|--|
| `【奥黛塔】_by_原神.zip`(PMX,日文骨名) | 0/22,不可驱动 | **21/22, drivable=true** | 交付 **VRM** |
| `模型_初音未来Hatsune Miku_by_Boku_Wa_Luka.zip`(PMX) | 0/22,不可驱动 | **19/22, drivable=true** | 交付 **VRM** |
未命中的 1-3 根均为非必需骨(如 `upperChest` / `leftToes`),不影响驱动与评分。
+9 -5
View File
@@ -44,16 +44,20 @@ UPLOAD_MAX_BYTES=536870912
# ---- 可选的 Assimp(FBX/glTF 动作预处理;也用于压缩包模型的转换)----
# 上传 .zip(内含 .pmx 的 MMD 模型包)时必须能调用到它,否则转换会失败
ASSIMP_BIN=assimp
# 需要转换的模型(PMX / FBX)交付格式:glb(默认,两个客户端都原生加载)| vrm
# glb:通用,客户端直接加载
# vrm:在 GLB 之上补 VRMC_vrm 扩展(humanoid 骨骼 / 表情语义);
# humanoid 骨骼名映射不全时会自动回退交付 GLB 并写进 conversion_note
MODEL_CONVERT_FORMAT=glb
# 模型交付格式:vrm(默认,v0.5.0 起所有上传模型一律转 VRM)| glb
# vrm:在 GLB 之上补 VRMC_vrm 扩展(humanoid 骨骼 / 表情语义)
# glb:仅作为转换中间产物;humanoid 不达标时会回退交付 GLB,
# 该模型 usable=false(可入库可审核,但不进入客户端目录)
MODEL_CONVERT_FORMAT=vrm
# 压缩包里优先选用的 PMX 文件名(大小写不敏感);找不到时按"格式优先级 -> 目录最浅 -> 文件最大"挑
# 值里含空格或 shell 元字符时必须用引号包起来(install.sh 会用
# `set -a; . deploy/.env` 真的执行本文件;不加引号会把 "Miku.pmx" 当命令)
MODEL_CONVERT_PMX="Hatsune Miku.pmx"
# 单次转换超时(毫秒)
# 转换后模型的着色模式:pbr(默认,标准 PBR + 按 PMX 参数修正双面/粗糙度)
# | unlit(给材质写 KHR_materials_unlit:颜色 = 贴图 x baseColorFactor,
# 与场景光照无关,最接近 MMD 的平涂观感;three.js 与 Godot 都支持)
MODEL_SHADING=pbr
MODEL_CONVERT_TIMEOUT_MS=180000
# ---- 默认模型(可选)----
+2 -2
View File
@@ -1,5 +1,5 @@
project: opendance-web-server
version: 0.2.4
version: 0.4.0
repository: opendance-web
default_branch: main
contracts_version: 0.4.0
@@ -60,7 +60,7 @@ tasks:
status: done
deliverable:
artifact: opendance-web-v0.2.4.tar.gz
artifact: opendance-web-v0.4.0.tar.gz
packaging: Linux 业务服务(系统服务托管,双端口:软件 API + 管理端,不含 MySQL、不含反向代理、不使用 Docker)
includes:
- web-server/ # NestJS 源码 + 构建产物(含 BVH / VMD 内置解析、ZIP 读取与模型压缩包转换)
+2 -2
View File
@@ -1,6 +1,6 @@
#!/bin/bash
# ============================================================
# 打包发布产物:opendance-web-v0.2.4.tar.gz
# 打包发布产物:opendance-web-v0.4.0.tar.gz
#
# 产物结构(Linux 业务服务部署,不使用 Docker、不部署反向代理):
# web-server/ NestJS 源码 + 构建产物
@@ -21,7 +21,7 @@ set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"
VERSION="${1:-0.2.4}"
VERSION="${1:-0.4.0}"
NAME="opendance-web-v${VERSION}"
OUT_DIR="$REPO_ROOT/dist-release"
STAGE="$OUT_DIR/$NAME"
+1 -1
View File
@@ -160,7 +160,7 @@ node scripts/import-default-model.mjs --write-source-only --model-id 22 --dry-ru
```bash
cd web-server
npx vitest run # 14 个文件 / 211 项通过
npx vitest run # 17 个文件 / 229 项通过
npm run test:smoke # 冒烟 [4] 段落
```
+1 -1
View File
@@ -86,7 +86,7 @@ draft ──submit──▶ pending ──approve──▶ published
```bash
cd web-server
npx vitest run # 14 个文件 / 211 项通过(含 admin-bone-filter 8 项、.env 预检 12 项、Assimp 13 项、缩略图贴图 6 项)
npx vitest run # 17 个文件 / 229 项通过(含 admin-bone-filter 8 项、.env 预检 12 项、Assimp 13 项、缩略图贴图 6 项、MMD 材质对齐 9 项、模型可用性 5 项、MMD 骨名重绑定 4 项)
npm run test:smoke
```
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opendance-admin",
"private": true,
"version": "0.2.4",
"version": "0.4.0",
"type": "module",
"description": "OpenDance Studio 管理端(React + TypeScript + Vite)",
"scripts": {
+4
View File
@@ -160,6 +160,10 @@ export interface Model extends SourceFields {
name: string;
format: ModelFormat;
vrmVersion: string | null;
/** 是否可用于客户端(= 已产出 VRM);false 的模型不进入客户端目录(v0.5.0) */
usable: boolean;
/** usable=false 的原因,例如「humanoid 不达标(0/22),未产出 VRM」 */
unusableReason: string | null;
isPrimary: boolean;
fileUrl: string | null;
fileSize: number | null;
+7 -1
View File
@@ -1,5 +1,7 @@
import { NavLink, Outlet } from 'react-router-dom';
import { APP_VERSION_LABEL } from '../lib/version';
interface NavItem {
to: string;
label: string;
@@ -44,9 +46,13 @@ export function Layout() {
))}
</nav>
<div className="sidebar-foot">
{/* 当前版本号:左下角固定展示,来源 web-server/package.json(与 /health 同源) */}
<span className="app-version" title="当前版本号">
{APP_VERSION_LABEL}
</span>
<span>API 基址</span>
<code>{API_BASE === '' ? '同源(dev proxy / nginx)' : API_BASE}</code>
<span className="muted">契约 rest-api 0.1.0</span>
<span className="muted">契约版本见「概览」页</span>
</div>
</aside>
<main className="content">
@@ -203,6 +203,17 @@ function ModelStatsView({ model, stats }: { model: Model; stats: ModelStats }) {
<Metric label="骨骼最大层级" value={formatCount(stats.maxBoneDepth)} />
</div>
{/* 可用性门槛(v0.5.0):未产出 VRM 的模型不进入客户端目录 */}
{!model.usable ? (
<div className="banner banner-danger" role="alert">
<strong>不可用:该模型不会进入客户端目录</strong>
<span>{model.unusableReason ?? '未产出 VRM'}</span>
<span className="muted">
依据契约 model-formats 1.1,所有模型一律转 VRM;humanoid 必需骨齐全后重新导入即可转为可用。
</span>
</div>
) : null}
{/* 可驱动性结论 */}
<div className={`banner ${BANNER_CLASS[drivable.kind]}`} role={drivable.kind === 'error' ? 'alert' : 'status'}>
<strong>
+10
View File
@@ -0,0 +1,10 @@
/**
* 应用版本号(构建期由 vite.config.ts 从 web-server/package.json 注入)。
* 页面左下角必须展示它,且与 `GET /health` 的 version、发布产物文件名一致
* (开发文档 v1.5 第十一章)。SSR / 测试环境下回退为 '0.0.0'。
*/
export const APP_VERSION: string =
typeof __APP_VERSION__ === 'string' && __APP_VERSION__.length > 0 ? __APP_VERSION__ : '0.0.0';
/** 展示用:带 v 前缀 */
export const APP_VERSION_LABEL = `v${APP_VERSION}`;
+8
View File
@@ -492,6 +492,14 @@ export function ModelsPage() {
</td>
<td>
<FormatBadge format={model.format} kind="model" />
{!model.usable ? (
<span
className="badge badge-rejected"
title={model.unusableReason ?? '未产出 VRM,不进入客户端目录'}
>
不可用
</span>
) : null}
</td>
<td className="mono">{model.vrmVersion ?? '—'}</td>
<td>
+8
View File
@@ -173,6 +173,14 @@ h3 {
color: var(--text-mute);
}
.app-version {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
font-weight: 600;
color: var(--text-strong, #e8ecf3);
letter-spacing: 0.02em;
}
.sidebar-foot code {
color: var(--text-dim);
word-break: break-all;
+3
View File
@@ -7,3 +7,6 @@ interface ImportMetaEnv {
interface ImportMeta {
readonly env: ImportMetaEnv;
}
/** 构建期注入的应用版本号(来自 web-server/package.json) */
declare const __APP_VERSION__: string;
+15
View File
@@ -1,11 +1,26 @@
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
const API_TARGET = 'http://localhost:3000';
/**
* 版本号唯一来源:`web-server/package.json`(与 `GET /health` 的 version 同源)。
* 构建期注入 `__APP_VERSION__`,管理端左下角直接展示,避免代码里再手写一份
* (见开发文档 v1.5 第十一章「版本号展示」)。
*/
const serverPackage = JSON.parse(
readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'),
) as { version?: string };
const APP_VERSION = serverPackage.version ?? '0.0.0';
// base './' 让产物可挂在任意子路径;开发期 /api 与 /health 代理到 NestJS 服务。
export default defineConfig({
base: './',
define: {
__APP_VERSION__: JSON.stringify(APP_VERSION),
},
plugins: [react()],
server: {
port: 5173,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "opendance-web-server",
"version": "0.2.4",
"version": "0.4.0",
"description": "OpenDance Studio Web 管理服务端(NestJS + TypeORM + 现有 MySQL 实例)",
"license": "MIT",
"private": true,
+11 -3
View File
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { createHash } from 'node:crypto';
import { Repository } from 'typeorm';
import { PublishStatus } from '../common/enums';
import { ModelFormat, PublishStatus } from '../common/enums';
import { AppConfig } from '../config/configuration';
import { CharacterModel } from '../entities/model.entity';
import { Motion } from '../entities/motion.entity';
@@ -43,7 +43,11 @@ export class CatalogService {
const [songs, motions, models] = await Promise.all([
this.songs.find({ where: { status: PublishStatus.Published }, order: { id: 'ASC' } }),
this.motions.find({ where: { status: PublishStatus.Published }, order: { id: 'ASC' } }),
this.models.find({ where: { status: PublishStatus.Published }, order: { id: 'ASC' } }),
// v0.5.0:只交付**已产出 VRM** 的模型(usable),未产出 VRM 的不进入客户端目录
this.models.find({
where: { status: PublishStatus.Published, format: ModelFormat.Vrm },
order: { id: 'ASC' },
}),
]);
const [songDtos, motionDtos, modelDtos, defaultModelId] = await Promise.all([
@@ -71,7 +75,11 @@ export class CatalogService {
const [songs, motions, models] = await Promise.all([
this.songs.find({ where: { status: PublishStatus.Published }, order: { id: 'ASC' } }),
this.motions.find({ where: { status: PublishStatus.Published }, order: { id: 'ASC' } }),
this.models.find({ where: { status: PublishStatus.Published }, order: { id: 'ASC' } }),
// v0.5.0:只交付**已产出 VRM** 的模型(usable),未产出 VRM 的不进入客户端目录
this.models.find({
where: { status: PublishStatus.Published, format: ModelFormat.Vrm },
order: { id: 'ASC' },
}),
]);
const fingerprint = JSON.stringify({
+69
View File
@@ -0,0 +1,69 @@
/**
* GLB 容器读写:只拆/合 JSON 与 BIN 两个 chunk,不解释内容。
*
* 服务端有几处"只改 JSON、不动二进制"的后处理(补 VRM 扩展、内嵌贴图、
* 修正 MMD 材质),统一走这里,避免各写一份 chunk 解析。
*/
export const GLB_MAGIC = 0x46546c67; // 'glTF'
export const CHUNK_JSON = 0x4e4f534a; // 'JSON'
export const CHUNK_BIN = 0x004e4942; // 'BIN\0'
export function align4(value: number): number {
return value + ((4 - (value % 4)) % 4);
}
/** 解析 GLB 的 JSON 与 BIN;不是 GLB 或缺少 JSON chunk 时抛错(由调用方决定是否吞掉) */
export function parseGlbChunks<T = Record<string, unknown>>(buffer: Buffer): { json: T; bin: Buffer | null } {
if (buffer.length < 12 || buffer.readUInt32LE(0) !== GLB_MAGIC) {
throw new Error('不是有效的 GLB(魔数不正确)');
}
const total = buffer.readUInt32LE(8) || buffer.length;
const end = Math.min(total, buffer.length);
let offset = 12;
let json: T | null = null;
let bin: Buffer | null = null;
while (offset + 8 <= end) {
const length = buffer.readUInt32LE(offset);
const type = buffer.readUInt32LE(offset + 4);
const start = offset + 8;
if (start + length > buffer.length) break;
const data = buffer.subarray(start, start + length);
if (type === CHUNK_JSON) json = JSON.parse(data.toString('utf8')) as T;
else if (type === CHUNK_BIN) bin = Buffer.from(data);
offset = start + align4(length);
}
if (!json) throw new Error('GLB 里没有 JSON chunk');
return { json, bin };
}
/** 用新的 JSON + 原 BIN 重新拼一个 GLB(JSON 补空格、BIN 补零,都按 4 字节对齐) */
export function buildGlbChunks(json: unknown, bin: Buffer | null): Buffer {
const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf8');
const jsonPadded = Buffer.alloc(align4(jsonBuffer.length), 0x20);
jsonBuffer.copy(jsonPadded);
const chunks: Buffer[] = [];
const header = Buffer.alloc(12);
header.writeUInt32LE(GLB_MAGIC, 0);
header.writeUInt32LE(2, 4);
chunks.push(header);
const jsonHeader = Buffer.alloc(8);
jsonHeader.writeUInt32LE(jsonPadded.length, 0);
jsonHeader.writeUInt32LE(CHUNK_JSON, 4);
chunks.push(jsonHeader, jsonPadded);
if (bin && bin.length > 0) {
const binPadded = Buffer.alloc(align4(bin.length));
bin.copy(binPadded);
const binHeader = Buffer.alloc(8);
binHeader.writeUInt32LE(binPadded.length, 0);
binHeader.writeUInt32LE(CHUNK_BIN, 4);
chunks.push(binHeader, binPadded);
}
const out = Buffer.concat(chunks);
out.writeUInt32LE(out.length, 8);
return out;
}
+19 -2
View File
@@ -88,7 +88,23 @@ export class AppConfig {
* 设为 `vrm` 时会在 GLB 之上补 `VRMC_vrm` 扩展,humanoid 骨骼不全则回退 GLB。
*/
get modelConvertFormat(): 'glb' | 'vrm' {
return (this.config.get<string>('modelConvertFormat') ?? 'glb') === 'vrm' ? 'vrm' : 'glb';
// v0.5.0 起默认 **vrm**:所有上传模型一律转 VRM(见 contracts/model-formats.md 1.1);
// humanoid 不达标时管线自动回退交付 GLB 并置 usable=false。
return (this.config.get<string>('modelConvertFormat') ?? 'vrm') === 'glb' ? 'glb' : 'vrm';
}
/**
* 转换后模型的着色模式(`MODEL_SHADING`)。
*
* MMD 的着色模型(卡通阶梯 + 球面贴图 + 平坦环境光)在 glTF core 里没有对应实现,
* 因此提供两种交付:
* `pbr`(默认):标准 PBR;我们按 PMX 参数修正 doubleSided / metallic / roughness,
* 清掉 Assimp 带出的无关扩展;
* `unlit`:给每个材质写 `KHR_materials_unlit`,颜色 = 贴图 x baseColorFactor,
* 与场景光照无关,最接近 MMD 的平涂观感(three.js / Godot 都支持)。
*/
get modelShading(): 'pbr' | 'unlit' {
return (this.config.get<string>('modelShading') ?? 'pbr') === 'unlit' ? 'unlit' : 'pbr';
}
/** 压缩包里优先选用的 PMX 文件名(大小写不敏感);找不到时按"目录最浅、文件最大"挑 */
@@ -193,7 +209,8 @@ export const configuration = () => {
adminDir: process.env.ADMIN_DIR ?? resolve(process.cwd(), '..', 'admin'),
uploadMaxBytes: Number(process.env.UPLOAD_MAX_BYTES ?? 512 * 1024 * 1024),
assimpBin: process.env.ASSIMP_BIN ?? 'assimp',
modelConvertFormat: process.env.MODEL_CONVERT_FORMAT ?? 'glb',
modelConvertFormat: process.env.MODEL_CONVERT_FORMAT ?? 'vrm',
modelShading: process.env.MODEL_SHADING ?? 'pbr',
modelConvertPmx: process.env.MODEL_CONVERT_PMX ?? 'Hatsune Miku.pmx',
modelConvertTimeoutMs: Number(process.env.MODEL_CONVERT_TIMEOUT_MS ?? 180_000),
defaultModelId: process.env.DEFAULT_MODEL_ID ?? '',
+3 -3
View File
@@ -11,9 +11,9 @@ import { join } from 'node:path';
export const CONTRACT_VERSIONS: Readonly<Record<string, string>> = Object.freeze({
'rest-api': '0.4.0',
'websocket-keypoints': '0.1.0',
'data-models': '0.4.0',
'skeleton-topology': '0.1.0',
'model-formats': '0.4.0',
'data-models': '0.5.0',
'skeleton-topology': '0.2.0',
'model-formats': '0.5.0',
database: '0.3.0',
});
+307
View File
@@ -0,0 +1,307 @@
/**
* 把 MMD/PMX 的材质参数补回 Assimp 导出的 GLB。
*
* 为什么需要(真实故障):MMD 的着色模型与 glTF PBR 不是一回事,Assimp 转换会丢东西。
* 实测样本 `【奥黛塔】_by_原神.zip`(PMX,39 个材质):
* * PMX 里 **36 个材质带"不剔除背面"标志**,导出的 GLB 里 `doubleSided` **一个都没有**
* -> 头发、裙摆、睫毛这类薄片被单面剔除,看起来"贴图/颜色不对";
* * PMX 的 `shininess` / `specular` / `ambient` 与 PBR 的 roughness/specular 无映射,
* Assimp 会写上 `KHR_materials_specular`(甚至 `KHR_materials_volume`)等
* 与 MMD 无关的扩展,各渲染器解释不一致;
* * PMX 的 **球面贴图(SPH/SPA,15 项)与 toon 贴图(卡通阶梯)** 在 glTF core 里
* 没有对应槽位,只能记录并说明,不能凭空补出来。
*
* 这里做三件"有把握"的事:
* 1. 按 PMX 的 drawFlag 补 `doubleSided`;
* 2. 把 MMD 参数规范成可预期的 PBR:`metallicFactor = 0`、
* `roughnessFactor = clamp(1 - shininess/100, 0.5, 1)`、`baseColorFactor` 乘上 PMX diffuse;
* 3. 清掉 Assimp 带出的、与 MMD 无关的扩展;可选 `unlit` 模式让颜色与贴图完全一致。
* 另外顺手修正 Assimp 写坏的 `accessor.min/max`(实测 POSITION/TEXCOORD 的 min 都被写成 2.2e-308,
* Godot 等客户端会用它算包围盒)。
*
* 约定:解析不了就返回 null,绝不抛错——后处理失败不能影响入库。
*/
import type { PmxMaterialInfo } from './pmx-materials';
import { buildGlbChunks, parseGlbChunks } from '../common/glb-chunks';
export type ShadingMode = 'pbr' | 'unlit';
/** 与 MMD 无关、Assimp 会顺带写出的扩展(留着只会让各渲染器表现不一致) */
const STRIPPED_EXTENSIONS = [
'KHR_materials_volume',
'KHR_materials_transmission',
'KHR_materials_ior',
'KHR_materials_emissive_strength',
'KHR_materials_specular',
] as const;
interface LooseMaterial {
name?: string;
doubleSided?: boolean;
alphaMode?: string;
extensions?: Record<string, unknown>;
pbrMetallicRoughness?: {
baseColorFactor?: number[];
metallicFactor?: number;
roughnessFactor?: number;
baseColorTexture?: unknown;
};
[key: string]: unknown;
}
interface LooseAccessor {
bufferView?: number;
byteOffset?: number;
componentType?: number;
count?: number;
type?: string;
min?: number[];
max?: number[];
sparse?: unknown;
}
interface LooseBufferView {
buffer?: number;
byteOffset?: number;
byteLength?: number;
byteStride?: number;
}
interface LoosePrimitive {
attributes?: Record<string, number>;
[key: string]: unknown;
}
interface LooseDocument {
materials?: LooseMaterial[];
meshes?: { primitives?: LoosePrimitive[] }[];
accessors?: LooseAccessor[];
bufferViews?: LooseBufferView[];
extensionsUsed?: string[];
extensions?: Record<string, unknown>;
[key: string]: unknown;
}
export interface ApplyMmdMaterialsOptions {
/** PMX 材质表(与 GLB 材质按索引一一对应;null/缺失时只做通用清理) */
pmxMaterials?: PmxMaterialInfo[] | null;
/** 着色模式:pbr(默认)| unlit(KHR_materials_unlit,颜色 = 贴图 x baseColorFactor) */
shading?: ShadingMode;
}
export interface ApplyMmdMaterialsResult {
glb: Buffer;
/** 被设为双面的材质数 */
doubleSided: number;
/** 按 shininess 调整过粗糙度的材质数 */
roughnessAdjusted: number;
/** 清掉的扩展名 */
strippedExtensions: string[];
/** 修正了 min/max 的浮点 accessor 数 */
minMaxFixed: number;
/** 是否写入了 unlit 扩展 */
unlit: boolean;
}
function clamp01(value: number): number {
if (!Number.isFinite(value)) return 1;
return Math.min(1, Math.max(0, value));
}
function round2(value: number): number {
return Math.round(value * 100) / 100;
}
/** 按 PMX shininess 推一个 PBR 粗糙度:MMD 常见 1(很哑光),高值才是亮面 */
function roughnessFromShininess(shininess: number): number {
if (!Number.isFinite(shininess)) return 1;
return round2(Math.min(1, Math.max(0.5, 1 - shininess / 100)));
}
/** 读取 accessor 的浮点分量(只处理非稀疏、非交织或规范交织的 float 访问器) */
function readAccessorFloats(
doc: LooseDocument,
bin: Buffer | null,
accessorIndex: number,
components: number,
): Float32Array | null {
const accessor = doc.accessors?.[accessorIndex];
if (!accessor || accessor.sparse || typeof accessor.bufferView !== 'number') return null;
// 注意下标:components=3 对应 'VEC3'(写成 [components] 会取到 VEC4,整段静默跳过)
const expectedType = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'][components - 1];
if (accessor.componentType !== 5126 || accessor.type !== expectedType) {
return null;
}
const view = doc.bufferViews?.[accessor.bufferView];
if (!view || view.buffer !== 0 || !bin) return null;
const elementSize = components * 4;
const stride = view.byteStride ?? elementSize;
const base = (view.byteOffset ?? 0) + (accessor.byteOffset ?? 0);
const count = accessor.count ?? 0;
if (count <= 0 || base < 0) return null;
if (base + (count - 1) * stride + elementSize > bin.length) return null;
const out = new Float32Array(count * components);
for (let i = 0; i < count; i += 1) {
for (let c = 0; c < components; c += 1) {
out[i * components + c] = bin.readFloatLE(base + i * stride + c * 4);
}
}
return out;
}
/**
* 修正 Assimp 写坏的 POSITION accessor min/max(实测 min 是 2.2250738585072014e-308)。
* Godot 等客户端会用 min/max 算包围盒,坏值会导致取景异常。
*/
function fixAccessorMinMax(doc: LooseDocument, bin: Buffer | null): number {
let fixed = 0;
const componentsByType: Record<string, number> = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4 };
for (let accessorIndex = 0; accessorIndex < (doc.accessors?.length ?? 0); accessorIndex += 1) {
{
const accessor = doc.accessors?.[accessorIndex];
if (!accessor || accessor.sparse || accessor.componentType !== 5126) continue;
const components = componentsByType[accessor.type ?? ''];
if (!components) continue;
const values = readAccessorFloats(doc, bin, accessorIndex, components);
if (!values || values.length === 0) continue;
const min = new Array(components).fill(Number.POSITIVE_INFINITY);
const max = new Array(components).fill(Number.NEGATIVE_INFINITY);
let usable = true;
for (let i = 0; i < values.length; i += components) {
for (let c = 0; c < components; c += 1) {
const value = values[i + c];
if (!Number.isFinite(value)) {
usable = false;
break;
}
if (value < min[c]) min[c] = value;
if (value > max[c]) max[c] = value;
}
if (!usable) break;
}
if (!usable) continue;
const same =
Array.isArray(accessor.min) &&
Array.isArray(accessor.max) &&
accessor.min.length === components &&
accessor.max.length === components &&
accessor.min.every((value, index) => Math.abs(value - min[index]) < 1e-6) &&
accessor.max.every((value, index) => Math.abs(value - max[index]) < 1e-6);
if (same) continue;
accessor.min = min;
accessor.max = max;
fixed += 1;
}
}
return fixed;
}
/**
* 把 MMD 材质参数补进 GLB,并做 PBR 规范化。
* 返回 null 表示这个 GLB 解析不了(调用方应原样使用原 buffer)。
*/
export function applyMmdMaterials(
glb: Buffer,
options: ApplyMmdMaterialsOptions = {},
): ApplyMmdMaterialsResult | null {
let parsed: { json: LooseDocument; bin: Buffer | null };
try {
parsed = parseGlbChunks<LooseDocument>(glb);
} catch {
return null;
}
const { json, bin } = parsed;
const materials = json.materials;
if (!Array.isArray(materials) || materials.length === 0) return null;
const pmxMaterials = options.pmxMaterials ?? null;
const shading: ShadingMode = options.shading === 'unlit' ? 'unlit' : 'pbr';
const stripped = new Set<string>();
let doubleSided = 0;
let roughnessAdjusted = 0;
for (let i = 0; i < materials.length; i += 1) {
const material = materials[i];
if (!material || typeof material !== 'object') continue;
const pmx = pmxMaterials?.[i]; // Assimp 保持材质顺序(实测 39/39 对齐)
if (pmx) {
// 1) 双面:PMX drawFlag bit0
if (pmx.doubleSided) {
if (material.doubleSided !== true) doubleSided += 1;
material.doubleSided = true;
} else if (material.doubleSided === true) {
material.doubleSided = false;
}
// 2) PBR 规范化
const pbr = (material.pbrMetallicRoughness ??= {});
pbr.metallicFactor = 0;
const roughness = roughnessFromShininess(pmx.shininess);
if (pbr.roughnessFactor !== roughness) {
pbr.roughnessFactor = roughness;
roughnessAdjusted += 1;
}
const diffuse = pmx.diffuse;
const existing = Array.isArray(pbr.baseColorFactor) ? pbr.baseColorFactor : [1, 1, 1, 1];
const merged = [
clamp01((existing[0] ?? 1) * (diffuse[0] ?? 1)),
clamp01((existing[1] ?? 1) * (diffuse[1] ?? 1)),
clamp01((existing[2] ?? 1) * (diffuse[2] ?? 1)),
clamp01((existing[3] ?? 1) * (diffuse[3] ?? 1)),
];
const unchanged =
existing.length >= 4 &&
existing[0] === merged[0] &&
existing[1] === merged[1] &&
existing[2] === merged[2] &&
existing[3] === merged[3];
if (!unchanged) pbr.baseColorFactor = merged;
} else {
const pbr = material.pbrMetallicRoughness;
if (pbr && pbr.metallicFactor === undefined) pbr.metallicFactor = 0;
}
// 3) 清掉与 MMD 无关的扩展(specular 为黑色时一并清掉)
if (material.extensions) {
const specularBlack =
!pmx || (pmx.specular[0] === 0 && pmx.specular[1] === 0 && pmx.specular[2] === 0);
for (const name of STRIPPED_EXTENSIONS) {
if (name in material.extensions && (name !== 'KHR_materials_specular' || specularBlack)) {
delete material.extensions[name];
stripped.add(name);
}
}
if (Object.keys(material.extensions).length === 0) delete material.extensions;
}
// 4) 可选 unlit:颜色 = baseColorFactor x 贴图,与场景光照无关(最接近 MMD 的平涂观感)
if (shading === 'unlit') {
material.extensions = { ...(material.extensions ?? {}), KHR_materials_unlit: {} };
}
}
// extensionsUsed 与实际引用保持一致
if (shading === 'unlit') {
json.extensionsUsed = [...new Set([...(json.extensionsUsed ?? []), 'KHR_materials_unlit'])];
}
if (Array.isArray(json.extensionsUsed)) {
const stillUsed = new Set<string>();
for (const material of materials) {
for (const name of Object.keys(material.extensions ?? {})) stillUsed.add(name);
}
for (const extension of Object.keys(json.extensions ?? {})) stillUsed.add(extension);
json.extensionsUsed = json.extensionsUsed.filter((name) => stillUsed.has(name));
if (json.extensionsUsed.length === 0) delete json.extensionsUsed;
}
const minMaxFixed = fixAccessorMinMax(json, bin);
return {
glb: buildGlbChunks(json, bin),
doubleSided,
roughnessAdjusted,
strippedExtensions: [...stripped],
minMaxFixed,
unlit: shading === 'unlit',
};
}
+50 -4
View File
@@ -8,6 +8,8 @@ import { ModelFormat } from '../common/enums';
import { ZipEntry, readZipEntries } from '../common/zip-reader';
import { embedGlbImages } from './glb-textures';
import { assimpMissingMessage, resolveAssimpBinary } from '../common/assimp';
import { applyMmdMaterials, type ShadingMode } from './glb-materials';
import { parsePmxMaterials } from './pmx-materials';
import { packGltfToGlb } from './gltf-packer';
import { VrmWrapMeta, detectGlbKind, wrapGlbAsVrm } from './vrm-writer';
@@ -36,6 +38,14 @@ const run = promisify(execFile);
export interface ConvertOptions {
/** Assimp 可执行文件(默认 `assimp`,可用 ASSIMP_BIN 覆盖) */
assimpBin: string;
/**
* 着色模式(`MODEL_SHADING`):
* pbr 默认,标准 PBR(我们会按 MMD 参数规范 metallic/roughness/双面)
* unlit 写入 KHR_materials_unlit,颜色 = 贴图 x baseColorFactor,与场景光照无关
*/
shading?: ShadingMode;
/** PMX 源文件(用于把 MMD 材质参数——尤其是双面标志——补回 GLB) */
pmxSource?: Buffer | null;
/** 单次转换超时(毫秒) */
timeoutMs?: number;
/** 优先交付的格式:`glb`(默认)或 `vrm` */
@@ -333,6 +343,35 @@ async function runAssimpPipeline(
}
}
// ---- 第 2.5 步:把 MMD 材质参数补回 GLB(Assimp 会丢掉双面标志与着色参数) ----
// 实测:PMX 里 36/39 个材质是不剔除背面的,Assimp 导出的 GLB 里 doubleSided 一个都没有,
// 头发/裙摆/睫毛这类薄片会被单面剔除 —— 看起来就是"贴图颜色不对"。
const mmdMaterials = options.pmxSource ? parsePmxMaterials(options.pmxSource) : null;
const applied = applyMmdMaterials(glbBuffer, {
pmxMaterials: mmdMaterials,
shading: options.shading ?? 'pbr',
});
let materialNote = '';
if (applied) {
glbBuffer = applied.glb;
const bits: string[] = [];
if (applied.doubleSided > 0) bits.push(`双面 ${applied.doubleSided} 项`);
if (applied.roughnessAdjusted > 0) bits.push(`粗糙度按 shininess 调整 ${applied.roughnessAdjusted} 项`);
if (applied.strippedExtensions.length > 0) bits.push(`清理扩展 ${applied.strippedExtensions.join('/')}`);
if (applied.minMaxFixed > 0) bits.push(`修正 min/max ${applied.minMaxFixed} 项`);
if (applied.unlit) bits.push('unlit 着色');
if (bits.length > 0) attempts.push(`MMD 材质修正:${bits.join('、')}`);
const sphereCount = (mmdMaterials ?? []).filter((m) => m.sphereTextureIndex >= 0).length;
if (sphereCount > 0) {
attempts.push(`球面贴图 ${sphereCount} 项:glTF core 无对应槽位,未保留(MMD 高光观感会有差异)`);
}
const noteBits: string[] = [];
if (applied.doubleSided > 0) noteBits.push(`双面 ${applied.doubleSided} 项`);
if (applied.unlit) noteBits.push('unlit 着色');
if (sphereCount > 0) noteBits.push(`球面贴图 ${sphereCount} 项未保留`);
if (noteBits.length > 0) materialNote = `;MMD 材质修正:${noteBits.join('、')}`;
}
// ---- 第 3 步:按需封装成 VRM(优先 GLB,其次 VRM) ----
if (prefer === 'vrm') {
const wrapped = tryWrapVrm(glbBuffer, options.vrmMeta, modelLabel.replace(/\.[^.]+$/, ''));
@@ -340,7 +379,7 @@ async function runAssimpPipeline(
return {
buffer: wrapped.buffer,
format: ModelFormat.Vrm,
note: `${modelLabel} → VRM(基于 GLB 封装${embedNote};${wrapped.detail})`,
note: `${modelLabel} → VRM(基于 GLB 封装${embedNote}${materialNote};${wrapped.detail})`,
attempts: [...attempts, `VRM 封装:${wrapped.detail}`],
};
}
@@ -350,7 +389,7 @@ async function runAssimpPipeline(
return {
buffer: glbBuffer,
format: ModelFormat.Glb,
note: `${modelLabel} → GLB${embedNote}`,
note: `${modelLabel} → GLB${embedNote}${materialNote}`,
attempts,
};
}
@@ -402,7 +441,11 @@ export async function convertModelArchive(
modelPath,
makeResolver(contents),
candidate.entry.path.split('/').pop() ?? candidate.entry.path,
options,
{
...options,
// 只有 PMX 有 MMD 材质表;FBX 等按通用规则处理
pmxSource: candidate.sourceFormat === 'pmx' ? candidate.entry.read() : null,
},
);
return { ...result, sourceModelPath: candidate.entry.path, direct: false };
} finally {
@@ -423,7 +466,10 @@ export async function convertModelFile(
try {
const modelPath = join(workDir, basename(fileName));
await writeFile(modelPath, buffer);
const result = await runAssimpPipeline(modelPath, () => null, basename(fileName), options);
const result = await runAssimpPipeline(modelPath, () => null, basename(fileName), {
...options,
pmxSource: extname(fileName).toLowerCase() === '.pmx' ? buffer : null,
});
return { ...result, sourceModelPath: basename(fileName), direct: false };
} finally {
await rm(workDir, { recursive: true, force: true });
+83 -23
View File
@@ -143,21 +143,51 @@ export const STRIPPABLE_PREFIXES: readonly string[] = ['jbip', 'mixamorig', 'bip
* 与客户端 `humanoid_map.gd` 的 CANDIDATES 逐字一致(测试会逐键比对)。
*/
export const HUMANOID_CANDIDATES: Record<string, string[]> = {
hips: ['chips', 'hips', 'hip', 'pelvis', 'root'],
spine: ['cspine', 'spine', 'spine1', 'spinemid'],
chest: ['cchest', 'chest', 'spine2', 'spineupper'],
upperChest: ['cupperchest', 'upperchest', 'chest2', 'spine3'],
neck: ['cneck', 'neck', 'neck1'],
head: ['chead', 'head'],
leftShoulder: ['lshoulder', 'leftshoulder', 'shoulderl', 'shoulderleft', 'claviclel', 'lclavicle'],
leftUpperArm: ['lupperarm', 'leftupperarm', 'larm', 'leftarm', 'luparm'],
leftLowerArm: ['llowerarm', 'leftlowerarm', 'lforearm', 'leftforearm', 'lelbow'],
leftHand: ['lhand', 'lefthand', 'lwrist', 'leftwrist'],
rightShoulder: ['rshoulder', 'rightshoulder', 'shoulderr', 'shoulderright', 'clavicler', 'rclavicle'],
rightUpperArm: ['rupperarm', 'rightupperarm', 'rarm', 'rightarm', 'ruparm'],
rightLowerArm: ['rlowerarm', 'rightlowerarm', 'rforearm', 'rightforearm', 'relbow'],
rightHand: ['rhand', 'righthand', 'rwrist', 'rightwrist'],
leftUpperLeg: ['lupperleg', 'leftupperleg', 'lthigh', 'leftthigh', 'lupleg', 'lhip', 'lefthip'],
hips: ['chips', 'hips', 'hip', 'pelvis', 'root',
// MMD / 中文常见名
'下半身', '腰', 'センター', 'center', '臀部', '髋', '骨盆',],
spine: ['cspine', 'spine', 'spine1', 'spinemid',
// MMD / 中文常见名
'上半身', '脊椎', '脊柱',],
chest: ['cchest', 'chest', 'spine2', 'spineupper',
// MMD / 中文常见名
'上半身2', '胸部', '胸',],
upperChest: ['cupperchest', 'upperchest', 'chest2', 'spine3',
// MMD / 中文常见名
'上半身3',],
neck: ['cneck', 'neck', 'neck1',
// MMD / 中文常见名
'首', '颈', '脖子',],
head: ['chead', 'head',
// MMD / 中文常见名
'頭', '头', '头部',],
leftShoulder: ['lshoulder', 'leftshoulder', 'shoulderl', 'shoulderleft', 'claviclel', 'lclavicle',
// MMD / 中文常见名
'左肩', '左锁骨',],
leftUpperArm: ['lupperarm', 'leftupperarm', 'larm', 'leftarm', 'luparm',
// MMD / 中文常见名
'左腕', '左大臂', '左上臂', '左臂',],
leftLowerArm: ['llowerarm', 'leftlowerarm', 'lforearm', 'leftforearm', 'lelbow',
// MMD / 中文常见名
'左ひじ', '左肘', '左小臂', '左前臂',],
leftHand: ['lhand', 'lefthand', 'lwrist', 'leftwrist',
// MMD / 中文常见名
'左手首', '左手', '左手腕',],
rightShoulder: ['rshoulder', 'rightshoulder', 'shoulderr', 'shoulderright', 'clavicler', 'rclavicle',
// MMD / 中文常见名
'右肩', '右锁骨',],
rightUpperArm: ['rupperarm', 'rightupperarm', 'rarm', 'rightarm', 'ruparm',
// MMD / 中文常见名
'右腕', '右大臂', '右上臂', '右臂',],
rightLowerArm: ['rlowerarm', 'rightlowerarm', 'rforearm', 'rightforearm', 'relbow',
// MMD / 中文常见名
'右ひじ', '右肘', '右小臂', '右前臂',],
rightHand: ['rhand', 'righthand', 'rwrist', 'rightwrist',
// MMD / 中文常见名
'右手首', '右手', '右手腕',],
leftUpperLeg: ['lupperleg', 'leftupperleg', 'lthigh', 'leftthigh', 'lupleg', 'lhip', 'lefthip',
// MMD / 中文常见名
'左足', '左大腿',],
leftLowerLeg: [
'llowerleg',
'leftlowerleg',
@@ -167,10 +197,17 @@ export const HUMANOID_CANDIDATES: Record<string, string[]> = {
'leftshin',
'lknee',
'leftknee',
],
leftFoot: ['lfoot', 'leftfoot', 'lankle', 'leftankle'],
leftToes: ['ltoes', 'lefttoes', 'ltoe', 'lefttoe', 'ltoebase', 'lefttoebase'],
rightUpperLeg: ['rupperleg', 'rightupperleg', 'rthigh', 'rightthigh', 'rupleg', 'rhip', 'righthip'],
// MMD / 中文常见名
'左ひざ', '左膝', '左小腿', '左膝盖',],
leftFoot: ['lfoot', 'leftfoot', 'lankle', 'leftankle',
// MMD / 中文常见名
'左足首', '左脚', '左脚踝',],
leftToes: ['ltoes', 'lefttoes', 'ltoe', 'lefttoe', 'ltoebase', 'lefttoebase',
// MMD / 中文常见名
'左つま先', '左脚趾',],
rightUpperLeg: ['rupperleg', 'rightupperleg', 'rthigh', 'rightthigh', 'rupleg', 'rhip', 'righthip',
// MMD / 中文常见名
'右足', '右大腿',],
rightLowerLeg: [
'rlowerleg',
'rightlowerleg',
@@ -180,9 +217,14 @@ export const HUMANOID_CANDIDATES: Record<string, string[]> = {
'rightshin',
'rknee',
'rightknee',
],
rightFoot: ['rfoot', 'rightfoot', 'rankle', 'rightankle'],
rightToes: ['rtoes', 'righttoes', 'rtoe', 'righttoe', 'rtoebase', 'righttoebase'],
// MMD / 中文常见名
'右ひざ', '右膝', '右小腿', '右膝盖',],
rightFoot: ['rfoot', 'rightfoot', 'rankle', 'rightankle',
// MMD / 中文常见名
'右足首', '右脚', '右脚踝',],
rightToes: ['rtoes', 'righttoes', 'rtoe', 'righttoe', 'rtoebase', 'righttoebase',
// MMD / 中文常见名
'右つま先', '右脚趾',],
};
/* -------------------------------------------------------------- 客户端逻辑移植 */
@@ -196,7 +238,25 @@ export function normalizeBoneName(nodeName: string): string {
const lower = nodeName.toLowerCase();
let out = '';
for (const ch of lower) {
if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) out += ch;
const code = ch.codePointAt(0) ?? 0;
if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
out += ch;
continue;
}
// 全角 ASCII(A-Z a-z 0-9)折成半角:MMD 常写「足IK」「つま先IK」
if (code >= 0xff01 && code <= 0xff5e) {
out += String.fromCharCode(code - 0xfee0);
continue;
}
// **必须保留中文与日文**:MMD 骨名(上半身 / 左ひじ / 首 / 下半身)全是这些字符。
// v0.3.0 之前只保留 a-z0-9,导致 MMD 模型所有骨名归一化成空串、humanoid 覆盖率恒为 0/22。
if (
(code >= 0x3040 && code <= 0x30ff) || // 平假名 / 片假名 / 长音符
(code >= 0x4e00 && code <= 0x9fff) || // CJK 统一表意文字
code === 0x3005 // 々
) {
out += ch;
}
}
return out;
}
+31
View File
@@ -1,4 +1,5 @@
import { ModelFormat, PublishStatus, SourceType } from '../common/enums';
import type { ModelStats } from './model-inspector';
import { CharacterModel } from '../entities/model.entity';
/** 契约 data-models.md §4 的对外表示 */
@@ -7,6 +8,13 @@ export interface ModelDto {
name: string;
format: ModelFormat;
vrmVersion: string | null;
/**
* 是否可被客户端使用(v0.5.0):等价于"已产出 VRM"。
* `false` 的模型**不进入 `catalog/export`**,但仍可入库与审核。
*/
usable: boolean;
/** `usable=false` 时的原因(中文,供审核面板直接展示) */
unusableReason: string | null;
isPrimary: boolean;
fileUrl: string | null;
fileSize: number | null;
@@ -37,12 +45,35 @@ export interface ModelUrlLookup {
sourceSha256?: string | null;
}
/**
* 模型是否可用于客户端(v0.5.0 门槛):**必须已产出 VRM**。
*
* 依据 `contracts/model-formats.md` 1.1:所有上传模型一律转 VRM;
* humanoid 不达标时管线回退交付 GLB,此时模型可入库、可审核,但**不可用**、
* 不进入 `catalog/export` —— 待按 skeleton-topology 标准重绑定骨骼后重新转换即转为可用。
*/
export function isUsableModel(model: CharacterModel): boolean {
return model.format === ModelFormat.Vrm;
}
/** 不可用的原因(可用时返回 null);从 stats 取 humanoid 覆盖度,便于人工定位 */
export function unusableReason(model: CharacterModel): string | null {
if (isUsableModel(model)) return null;
const stats = (model.stats ?? null) as Partial<ModelStats> | null;
if (stats && typeof stats.humanoidMapped === 'number' && typeof stats.humanoidTotal === 'number') {
return `humanoid 不达标(${stats.humanoidMapped}/${stats.humanoidTotal}),未产出 VRM`;
}
return '未产出 VRM(格式为 GLB),不可用于客户端';
}
export function toModelDto(model: CharacterModel, urls: ModelUrlLookup): ModelDto {
return {
id: model.id,
name: model.name,
format: model.format,
vrmVersion: model.vrmVersion,
usable: isUsableModel(model),
unusableReason: unusableReason(model),
isPrimary: model.isPrimary,
fileUrl: urls.fileUrl,
fileSize: urls.fileSize ?? null,
+3 -1
View File
@@ -133,6 +133,7 @@ export class ModelsService {
timeoutMs: this.config.modelConvertTimeoutMs,
preferFormat: this.config.modelConvertFormat,
preferredPmx: this.config.modelConvertPmx,
shading: this.config.modelShading,
vrmMeta: { name, author: tuple.author ?? '', license: tuple.license },
};
@@ -450,8 +451,9 @@ export class ModelsService {
* 4. id 最小的已发布模型
*/
async resolveDefaultModelId(): Promise<number | null> {
// v0.5.0:默认模型必须来自**可用**模型(已产出 VRM);未产出 VRM 的不进客户端目录
const published = await this.models.find({
where: { status: PublishStatus.Published },
where: { status: PublishStatus.Published, format: ModelFormat.Vrm },
order: { id: 'ASC' },
});
if (published.length === 0) return null;
+207
View File
@@ -0,0 +1,207 @@
/**
* 只读 PMX 的**材质段**(布局与 PMX 2.0 规范 / mmd-parser 一致)。
*
* 为什么需要:Assimp 6.0.4 的 PMX 导入会把 MMD 的材质参数大量丢弃——
* 实测 `【奥黛塔】_by_原神.zip`(39 个材质)里 PMX 有 36 个材质带
* **不剔除背面(双面)**标志,而导出的 GLB 里 `doubleSided` 一个都没有:
* 头发、裙摆、睫毛这类薄片会被单面剔除掉,看起来就是"颜色/贴图不对"。
* 因此转换后按 PMX 原始参数把 GLB 材质补回来(见 `glb-materials.ts`)。
*
* 只读、尽力而为:任何越界/未知版本都返回 null,绝不让调用方失败。
*/
/** PMX 材质的关键参数(我们关心的子集) */
export interface PmxMaterialInfo {
name: string;
diffuse: [number, number, number, number];
specular: [number, number, number];
/** 镜面反射强度(MMD 的 specular power,常见的 0~100+) */
shininess: number;
ambient: [number, number, number];
/** 原始 drawFlag:bit0 = 不剔除背面(双面) */
flag: number;
/** 是否双面渲染(drawFlag bit0) */
doubleSided: boolean;
/** 球面贴图(SPH/SPA)索引,-1 表示没有 */
sphereTextureIndex: number;
/** 球面贴图模式:0 关闭 / 1 乘算 / 2 加算 / 3 子贴图 */
sphereMode: number;
/** 0 = 使用 toonIndex 指定的贴图;1 = 使用共享 toon */
toonFlag: number;
toonIndex: number;
/** 该材质覆盖的三角形数 */
faceCount: number;
}
const PMX_MAGIC = 'PMX ';
class Cursor {
private offset = 0;
constructor(private readonly buffer: Buffer) {}
get position(): number {
return this.offset;
}
get remaining(): number {
return this.buffer.length - this.offset;
}
u8(): number {
const value = this.buffer.readUInt8(this.offset);
this.offset += 1;
return value;
}
i8(): number {
const value = this.buffer.readInt8(this.offset);
this.offset += 1;
return value;
}
u16(): number {
const value = this.buffer.readUInt16LE(this.offset);
this.offset += 2;
return value;
}
i32(): number {
const value = this.buffer.readInt32LE(this.offset);
this.offset += 4;
return value;
}
u32(): number {
const value = this.buffer.readUInt32LE(this.offset);
this.offset += 4;
return value;
}
f32(): number {
const value = this.buffer.readFloatLE(this.offset);
this.offset += 4;
return value;
}
floats(count: number): number[] {
const out: number[] = [];
for (let i = 0; i < count; i += 1) out.push(this.f32());
return out;
}
/** 按字节宽度读索引(PMX 允许 1 / 2 / 4 字节,**有符号**:-1 表示无) */
index(size: number): number {
if (size === 1) return this.i8();
if (size === 2) {
const value = this.buffer.readInt16LE(this.offset);
this.offset += 2;
return value;
}
return this.i32();
}
skip(bytes: number): void {
this.offset += bytes;
}
/** PMX 文本:int32 字节长度 + 内容(UTF-16LE 或 UTF-8) */
text(utf16: boolean): string {
const length = this.i32();
if (length < 0) throw new Error('PMX 文本长度非法');
const raw = this.buffer.subarray(this.offset, this.offset + length);
this.offset += length;
return raw.toString(utf16 ? 'utf16le' : 'utf8');
}
}
/**
* 解析 PMX 的材质段;不是 PMX / 结构异常一律返回 null。
* 会跳过顶点、面、贴图段,只为拿到材质参数,不做几何解析。
*/
export function parsePmxMaterials(buffer: Buffer): PmxMaterialInfo[] | null {
try {
if (buffer.length < 32 || buffer.toString('ascii', 0, 4) !== PMX_MAGIC) return null;
const cursor = new Cursor(buffer);
cursor.skip(4);
cursor.f32(); // version
const globalCount = cursor.u8();
if (globalCount < 8) return null;
const globals = [];
for (let i = 0; i < globalCount; i += 1) globals.push(cursor.u8());
const encoding = globals[0]; // 0 = UTF-16LE, 1 = UTF-8
const additionalUvNum = globals[1];
const vertexIndexSize = globals[2];
const textureIndexSize = globals[3];
const boneIndexSize = globals[5];
const utf16 = encoding === 0;
// 头部 4 段文本:name / nameEn / comment / commentEn
for (let i = 0; i < 4; i += 1) cursor.text(utf16);
// 顶点段:跳过
const vertexCount = cursor.i32();
if (vertexCount < 0) return null;
for (let i = 0; i < vertexCount; i += 1) {
cursor.skip(12 + 12 + 8 + additionalUvNum * 16);
const type = cursor.u8();
if (type === 0) cursor.skip(boneIndexSize);
else if (type === 1) cursor.skip(boneIndexSize * 2 + 4);
else if (type === 2) cursor.skip(boneIndexSize * 4 + 16);
else if (type === 3) cursor.skip(boneIndexSize * 2 + 4 + 36);
else if (type === 4) cursor.skip(boneIndexSize * 4 + 16); // QDEF(PMX 2.1)
else return null;
cursor.skip(4); // edge scale
if (cursor.remaining <= 0) return null;
}
// 面段:索引个数 × 索引宽度
const faceIndexCount = cursor.i32();
if (faceIndexCount < 0) return null;
cursor.skip(faceIndexCount * vertexIndexSize);
// 贴图段:跳过
const textureCount = cursor.i32();
if (textureCount < 0) return null;
for (let i = 0; i < textureCount; i += 1) cursor.text(utf16);
// 材质段
const materialCount = cursor.i32();
if (materialCount < 0 || materialCount > 100_000) return null;
const materials: PmxMaterialInfo[] = [];
for (let i = 0; i < materialCount; i += 1) {
const name = cursor.text(utf16);
cursor.text(utf16); // englishName
const diffuse = cursor.floats(4) as [number, number, number, number];
const specular = cursor.floats(3) as [number, number, number];
const shininess = cursor.f32();
const ambient = cursor.floats(3) as [number, number, number];
const flag = cursor.u8();
cursor.skip(16 + 4); // edgeColor(4f) + edgeSize(1f)
const textureIndex = cursor.index(textureIndexSize);
const sphereTextureIndex = cursor.index(textureIndexSize);
const sphereMode = cursor.u8();
const toonFlag = cursor.u8();
const toonIndex = toonFlag === 0 ? cursor.index(textureIndexSize) : cursor.i8();
cursor.text(utf16); // comment
const faceCount = Math.floor(cursor.u32() / 3);
materials.push({
name,
diffuse,
specular,
shininess,
ambient,
flag,
doubleSided: (flag & 0x01) !== 0,
sphereTextureIndex,
sphereMode,
toonFlag,
toonIndex,
faceCount,
});
}
return materials;
} catch {
return null;
}
}
+5 -56
View File
@@ -1,4 +1,5 @@
import { ModelFormat } from '../common/enums';
import { buildGlbChunks, parseGlbChunks } from '../common/glb-chunks';
import { HUMANOID_CANDIDATES, HUMANOID_REQUIRED, normalizeBoneName, boneNameVariants } from './model-inspector';
/**
@@ -45,63 +46,11 @@ interface GltfJson {
[key: string]: unknown;
}
function align4(value: number): number {
return value + ((4 - (value % 4)) % 4);
}
/** 解析 GLB 的 JSON 与 BIN chunk(实现见 common/glb-chunks.ts) */
const parseGlb = (buffer: Buffer): { json: GltfJson; bin: Buffer | null } =>
parseGlbChunks<GltfJson>(buffer);
/** 解析 GLB 的 JSON 与 BIN chunk */
function parseGlb(buffer: Buffer): { json: GltfJson; bin: Buffer | null } {
if (buffer.length < 12 || buffer.readUInt32LE(0) !== GLB_MAGIC) {
throw new Error('不是有效的 GLB(魔数不正确)');
}
const total = buffer.readUInt32LE(8) || buffer.length;
const end = Math.min(total, buffer.length);
let offset = 12;
let json: GltfJson | null = null;
let bin: Buffer | null = null;
while (offset + 8 <= end) {
const length = buffer.readUInt32LE(offset);
const type = buffer.readUInt32LE(offset + 4);
const start = offset + 8;
if (start + length > buffer.length) break;
const data = buffer.subarray(start, start + length);
if (type === CHUNK_JSON) json = JSON.parse(data.toString('utf8')) as GltfJson;
else if (type === CHUNK_BIN) bin = Buffer.from(data);
offset = start + align4(length);
}
if (!json) throw new Error('GLB 里没有 JSON chunk');
return { json, bin };
}
function buildGlb(json: GltfJson, bin: Buffer | null): Buffer {
const jsonBuffer = Buffer.from(JSON.stringify(json), 'utf8');
const jsonPadded = Buffer.alloc(align4(jsonBuffer.length), 0x20);
jsonBuffer.copy(jsonPadded);
const chunks: Buffer[] = [];
const header = Buffer.alloc(12);
header.writeUInt32LE(GLB_MAGIC, 0);
header.writeUInt32LE(2, 4);
chunks.push(header);
const jsonHeader = Buffer.alloc(8);
jsonHeader.writeUInt32LE(jsonPadded.length, 0);
jsonHeader.writeUInt32LE(CHUNK_JSON, 4);
chunks.push(jsonHeader, jsonPadded);
if (bin && bin.length > 0) {
const binPadded = Buffer.alloc(align4(bin.length));
bin.copy(binPadded);
const binHeader = Buffer.alloc(8);
binHeader.writeUInt32LE(binPadded.length, 0);
binHeader.writeUInt32LE(CHUNK_BIN, 4);
chunks.push(binHeader, binPadded);
}
const out = Buffer.concat(chunks);
out.writeUInt32LE(out.length, 8);
return out;
}
const buildGlb = (json: GltfJson, bin: Buffer | null): Buffer => buildGlbChunks(json, bin);
/**
* 按骨骼名把 glTF 节点映射到 VRM humanoid 规范骨。
+246
View File
@@ -0,0 +1,246 @@
import { describe, expect, it } from 'vitest';
import { buildGlbChunks, parseGlbChunks } from '../src/common/glb-chunks';
import { applyMmdMaterials } from '../src/models/glb-materials';
import { type PmxMaterialInfo, parsePmxMaterials } from '../src/models/pmx-materials';
/**
* MMD(PMX)材质 → glTF 材质的补全。
*
* 背景(真实故障):Assimp 6.0.4 会把 PMX 的**双面(不剔除背面)**标志丢掉——
* 实测 39 个材质里 PMX 有 36 个是双面的,导出的 GLB 里 `doubleSided` 一个都没有,
* 头发/裙摆/睫毛这些薄片被单面剔除,看起来就是"贴图颜色不对"。
* 另外 PMX 的 shininess/specular/ambient 与 PBR 无映射,Assimp 还会带上
* `KHR_materials_specular` / `KHR_materials_volume` 等与 MMD 无关的扩展。
*/
/* ------------------------------------------------------------ PMX 夹具 */
/** 造一个最小可解析的 PMX:1 顶点 + 1 三角形 + 1 贴图 + N 个材质 */
function buildPmx(materials: Array<{ name: string; flag: number; shininess: number; diffuse?: number[] }>): Buffer {
const parts: Buffer[] = [];
const u8 = (v: number) => Buffer.from([v & 0xff]);
const i32 = (v: number) => {
const b = Buffer.alloc(4);
b.writeInt32LE(v, 0);
return b;
};
const u32 = (v: number) => {
const b = Buffer.alloc(4);
b.writeUInt32LE(v, 0);
return b;
};
const f32 = (v: number) => {
const b = Buffer.alloc(4);
b.writeFloatLE(v, 0);
return b;
};
const text = (s: string) => {
const body = Buffer.from(s, 'utf16le');
return Buffer.concat([i32(body.length), body]);
};
parts.push(Buffer.from('PMX ', 'ascii'));
parts.push(f32(2.0));
parts.push(u8(8)); // globals 数量
// encoding=UTF16, additionalUv=0, vertexIndex=4, textureIndex=1, material=1, bone=2, morph=1, rigid=2
parts.push(Buffer.from([0, 0, 4, 1, 1, 2, 1, 2]));
parts.push(text('test'), text('test'), text(''), text('')); // name/en/comment/en-comment
parts.push(i32(1)); // 顶点数
parts.push(Buffer.alloc(12 + 12 + 8)); // position + normal + uv
parts.push(u8(0)); // BDEF1
parts.push(Buffer.alloc(2)); // bone index (2 字节)
parts.push(f32(1)); // edge scale
parts.push(i32(3)); // 索引数
parts.push(Buffer.alloc(3 * 4)); // 3 个 4 字节索引
parts.push(i32(1)); // 贴图数
parts.push(text('tex/a.png'));
parts.push(i32(materials.length));
for (const material of materials) {
parts.push(text(material.name), text(''));
parts.push(Buffer.concat((material.diffuse ?? [1, 1, 1, 1]).map(f32)));
parts.push(Buffer.concat([f32(0), f32(0), f32(0)])); // specular
parts.push(f32(material.shininess));
parts.push(Buffer.concat([f32(0.5), f32(0.5), f32(0.5)])); // ambient
parts.push(u8(material.flag));
parts.push(Buffer.concat([f32(0), f32(0), f32(0), f32(1)])); // edgeColor
parts.push(f32(1)); // edgeSize
parts.push(Buffer.alloc(1)); // textureIndex (1 字节)
parts.push(Buffer.alloc(1)); // sphereTextureIndex (1 字节,0 → 无? 这里当作索引 0)
parts.push(u8(0)); // sphereMode
parts.push(u8(1)); // toonFlag = 共享 toon
parts.push(u8(0)); // toonIndex (int8)
parts.push(text('')); // comment
parts.push(u32(3)); // faceCount(索引数)= 1 个三角形
}
return Buffer.concat(parts);
}
/* ------------------------------------------------------------ GLB 夹具 */
interface MaterialSpec {
name: string;
doubleSided?: boolean;
extensions?: Record<string, unknown>;
pbr?: Record<string, unknown>;
}
/** 造一个含 POSITION(min/max 故意写错)与 N 个材质的 GLB */
function buildGlb(materials: MaterialSpec[]): Buffer {
const positions = float32([0, 0, 0, 1, 0, 0, 0, 2, 0]);
const indices = Buffer.alloc(6);
indices.writeUInt16LE(0, 0);
indices.writeUInt16LE(1, 2);
indices.writeUInt16LE(2, 4);
const bin = Buffer.concat([positions, indices]);
const json = {
asset: { version: '2.0' },
scene: 0,
scenes: [{ nodes: [0] }],
nodes: [{ mesh: 0 }],
meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
materials: materials.map((m) => ({
name: m.name,
...(m.doubleSided === undefined ? {} : { doubleSided: m.doubleSided }),
...(m.extensions ? { extensions: m.extensions } : {}),
pbrMetallicRoughness: { baseColorTexture: { index: 0 }, ...(m.pbr ?? {}) },
})),
textures: [{ source: 0 }],
images: [{ bufferView: 2, mimeType: 'image/png' }],
accessors: [
// 故意写坏的 min(Assimp 实测会写成 2.2e-308)
{ bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [5, 5, 5], max: [9, 9, 9] },
{ bufferView: 1, componentType: 5123, count: 3, type: 'SCALAR' },
],
bufferViews: [
{ buffer: 0, byteOffset: 0, byteLength: positions.length },
{ buffer: 0, byteOffset: positions.length, byteLength: indices.length },
],
buffers: [{ byteLength: bin.length }],
extensionsUsed: ['KHR_materials_specular', 'KHR_materials_volume'],
};
return buildGlbChunks(json, bin);
}
function float32(values: number[]): Buffer {
const buffer = Buffer.alloc(values.length * 4);
values.forEach((value, index) => buffer.writeFloatLE(value, index * 4));
return buffer;
}
function pmxMaterial(overrides: Partial<PmxMaterialInfo> = {}): PmxMaterialInfo {
return {
name: 'm',
diffuse: [1, 1, 1, 1],
specular: [0, 0, 0],
shininess: 1,
ambient: [0.5, 0.5, 0.5],
flag: 1,
doubleSided: true,
sphereTextureIndex: -1,
sphereMode: 0,
toonFlag: 1,
toonIndex: 0,
faceCount: 1,
...overrides,
};
}
/* ------------------------------------------------------------------ 测试 */
describe('pmx-materials:只读 PMX 材质段', () => {
it('读出材质数量与双面标志(drawFlag bit0)', () => {
// flag=31(双面) / 14(单面) / 15(双面)
const pmx = buildPmx([
{ name: '颜', flag: 31, shininess: 1 },
{ name: '裙', flag: 14, shininess: 1 },
{ name: '体', flag: 15, shininess: 20, diffuse: [0.9, 0.8, 0.7, 1] },
]);
const materials = parsePmxMaterials(pmx);
expect(materials).not.toBeNull();
expect(materials!.map((m) => m.name)).toEqual(['颜', '裙', '体']);
expect(materials!.map((m) => m.doubleSided)).toEqual([true, false, true]);
expect(materials![2].shininess).toBe(20);
const diffuse = materials![2].diffuse;
expect(diffuse[0]).toBeCloseTo(0.9, 5);
expect(diffuse[1]).toBeCloseTo(0.8, 5);
expect(diffuse[2]).toBeCloseTo(0.7, 5);
});
it('不是 PMX 时返回 null,不抛错', () => {
expect(parsePmxMaterials(Buffer.from('not a pmx file at all'))).toBeNull();
expect(parsePmxMaterials(Buffer.alloc(0))).toBeNull();
});
});
describe('glb-materials:按 PMX 参数补全并规范化', () => {
it('按 PMX 的 drawFlag 补 doubleSided,并规范化 metallic/roughness', () => {
const glb = buildGlb([{ name: 'm0' }, { name: 'm1', doubleSided: true }]);
const result = applyMmdMaterials(glb, {
pmxMaterials: [pmxMaterial({ shininess: 1 }), pmxMaterial({ doubleSided: false, shininess: 50 })],
});
expect(result).not.toBeNull();
expect(result!.doubleSided).toBe(1); // 只有 m0 需要补
const { json } = parseGlbChunks<{ materials: Array<Record<string, any>> }>(result!.glb);
expect(json.materials[0].doubleSided).toBe(true);
expect(json.materials[1].doubleSided).toBe(false);
expect(json.materials[0].pbrMetallicRoughness.metallicFactor).toBe(0);
// shininess=1 -> 0.99(哑光);shininess=50 -> 0.5(亮面)
expect(json.materials[0].pbrMetallicRoughness.roughnessFactor).toBe(0.99);
expect(json.materials[1].pbrMetallicRoughness.roughnessFactor).toBe(0.5);
});
it('把 PMX diffuse 乘进 baseColorFactor(含 alpha)', () => {
const glb = buildGlb([{ name: 'm0', pbr: { baseColorFactor: [1, 1, 1, 1] } }]);
const result = applyMmdMaterials(glb, {
pmxMaterials: [pmxMaterial({ diffuse: [1, 0.5, 0.5, 0] })],
});
const { json } = parseGlbChunks<{ materials: Array<Record<string, any>> }>(result!.glb);
expect(json.materials[0].pbrMetallicRoughness.baseColorFactor).toEqual([1, 0.5, 0.5, 0]);
});
it('清掉与 MMD 无关的扩展(specular 为黑 / volume 等)', () => {
const glb = buildGlb([
{
name: 'm0',
extensions: { KHR_materials_specular: { specularFactor: 1 }, KHR_materials_volume: { thicknessFactor: 0 } },
},
]);
const result = applyMmdMaterials(glb, { pmxMaterials: [pmxMaterial()] });
expect(result!.strippedExtensions.sort()).toEqual(['KHR_materials_specular', 'KHR_materials_volume']);
const { json } = parseGlbChunks<{ materials: Array<Record<string, any>>; extensionsUsed?: string[] }>(result!.glb);
expect(json.materials[0].extensions).toBeUndefined();
expect(json.extensionsUsed).toBeUndefined();
});
it('unlit 模式:每个材质写 KHR_materials_unlit 并登记 extensionsUsed', () => {
const glb = buildGlb([{ name: 'm0' }, { name: 'm1', doubleSided: true }]);
const result = applyMmdMaterials(glb, { pmxMaterials: [pmxMaterial(), pmxMaterial()], shading: 'unlit' });
expect(result!.unlit).toBe(true);
const { json } = parseGlbChunks<{ materials: Array<Record<string, any>>; extensionsUsed?: string[] }>(result!.glb);
expect(json.materials[0].extensions.KHR_materials_unlit).toEqual({});
expect(json.materials[1].extensions.KHR_materials_unlit).toEqual({});
expect(json.extensionsUsed).toEqual(['KHR_materials_unlit']);
});
it('修正 Assimp 写坏的 accessor min/max(Godot 用它算包围盒)', () => {
const glb = buildGlb([{ name: 'm0' }]);
const result = applyMmdMaterials(glb, { pmxMaterials: null });
expect(result!.minMaxFixed).toBeGreaterThan(0);
const { json } = parseGlbChunks<{ accessors: Array<Record<string, any>> }>(result!.glb);
expect(json.accessors[0].min).toEqual([0, 0, 0]);
expect(json.accessors[0].max).toEqual([1, 2, 0]);
});
it('没有 PMX 材质表时也做通用清理,且不改材质数量', () => {
const glb = buildGlb([{ name: 'm0' }, { name: 'm1' }]);
const result = applyMmdMaterials(glb, { pmxMaterials: null });
const { json } = parseGlbChunks<{ materials: unknown[] }>(result!.glb);
expect(json.materials.length).toBe(2);
expect(result!.doubleSided).toBe(0);
});
it('不是 GLB 时返回 null(后处理失败不能影响入库)', () => {
expect(applyMmdMaterials(Buffer.from('not a glb'), { pmxMaterials: [pmxMaterial()] })).toBeNull();
});
});
+56
View File
@@ -406,6 +406,62 @@ describe('morphTargets 统计', () => {
});
});
/* --------------------- 5.5 MMD / 中文骨名映射(T-WEB-013 骨骼重绑定) */
describe('MMD 与中文骨名映射(T-WEB-013)', () => {
async function statsFor(names: string[], file: string): Promise<ModelStats> {
const doc = buildHumanoidDocument(names);
return inspectModelFile(write(file, Buffer.from(JSON.stringify(doc))));
}
it('归一化必须保留中日文,并把全角 ASCII 折成半角', () => {
expect(normalizeBoneName('上半身')).toBe('上半身');
expect(normalizeBoneName('左ひじ')).toBe('左ひじ');
expect(normalizeBoneName('首')).toBe('首');
// MMD 的「足IK」是全角字母:折成半角后是 足ik,与「左足」精确匹配不上(安全)
expect(normalizeBoneName('左足IK')).toBe('左足ik');
expect(normalizeBoneName('J_Bip_C_Hips')).toBe('jbipchips');
});
it('MMD 标准骨架名 → 16 根必需骨齐全、drivable=true(0/22 的修复点)', async () => {
const stats = await statsFor(
[
'全ての親', 'センター', '下半身', '上半身', '上半身2', '首', '頭',
'左肩', '左腕', '左ひじ', '左手首', '右肩', '右腕', '右ひじ', '右手首',
'左足', '左ひざ', '左足首', '右足', '右ひざ', '右足首',
],
'mmd-standard.gltf',
);
expect(stats.missingRequiredBones).toEqual([]);
expect(stats.drivable).toBe(true);
expect(stats.humanoidMapped).toBeGreaterThanOrEqual(16);
});
it('MMD 的 IK 骨(足IK / つま先IK)不得抢占 humanoid 骨', async () => {
const stats = await statsFor(
['下半身', '上半身', '首', '頭', '左足IK', '左つま先IK'],
'mmd-ik.gltf',
);
expect(stats.missingRequiredBones).toContain('leftUpperLeg');
expect(stats.missingRequiredBones).toContain('leftFoot');
expect(stats.drivable).toBe(false);
});
it('中文骨名也能映射(臀部/头/脖子/左大腿/左脚)', async () => {
const stats = await statsFor(
[
'臀部', '脊椎', '胸部', '脖子', '头',
'左大臂', '左小臂', '左手', '右大臂', '右小臂', '右手',
'左大腿', '左小腿', '左脚', '右大腿', '右小腿', '右脚',
],
'chinese-names.gltf',
);
expect(stats.missingRequiredBones).toEqual([]);
expect(stats.drivable).toBe(true);
});
});
/* ------------------------------- 6. 与客户端 humanoid_map.gd 的一致性 */
/** gd 文件在客户端仓库里;按「从 web-server 运行」为主,同时兼容从仓库根运行 */
+110
View File
@@ -0,0 +1,110 @@
import { describe, expect, it, vi } from 'vitest';
import { CatalogService } from '../src/catalog/catalog.service';
import { ModelFormat, PublishStatus, SourceType } from '../src/common/enums';
import type { CharacterModel } from '../src/entities/model.entity';
import { isUsableModel, toModelDto, unusableReason } from '../src/models/model.serializer';
/**
* v0.5.0「模型一律转 VRM」的可用性门槛。
*
* 规则(contracts/model-formats.md 1.1):所有上传模型都转 VRM;
* humanoid 不达标时回退交付 GLB —— 这种模型**可入库、可审核,但不可用**,
* **不进入 `catalog/export`**(用户明确选择"入库但标记不可用,不进已发布目录")。
*/
function model(overrides: Partial<CharacterModel> = {}): CharacterModel {
return {
id: 1,
name: 'model',
format: ModelFormat.Vrm,
vrmVersion: '1.0',
isPrimary: false,
fileAssetId: 1,
sourceAssetId: null,
thumbnailAssetId: null,
conversionNote: null,
stats: null,
sourceType: SourceType.Other,
sourceName: 'x',
sourceUrl: 'x',
license: 'x',
author: 'x',
status: PublishStatus.Published,
createdAt: new Date('2026-01-01T00:00:00Z'),
updatedAt: new Date('2026-01-01T00:00:00Z'),
...overrides,
} as CharacterModel;
}
describe('模型可用性(usable)', () => {
it('VRM → 可用,且没有不可用原因', () => {
const vrm = model({ format: ModelFormat.Vrm });
expect(isUsableModel(vrm)).toBe(true);
expect(unusableReason(vrm)).toBeNull();
expect(toModelDto(vrm, { fileUrl: '/f', thumbnailUrl: null }).usable).toBe(true);
});
it('GLB(humanoid 不达标)→ 不可用,原因带 humanoid 覆盖度', () => {
const glb = model({
format: ModelFormat.Glb,
vrmVersion: null,
stats: { humanoidMapped: 0, humanoidTotal: 22 } as Record<string, unknown>,
});
expect(isUsableModel(glb)).toBe(false);
expect(unusableReason(glb)).toBe('humanoid 不达标(0/22),未产出 VRM');
const dto = toModelDto(glb, { fileUrl: '/f', thumbnailUrl: null });
expect(dto.usable).toBe(false);
expect(dto.unusableReason).toContain('0/22');
});
it('GLB 且没有 stats → 给出通用原因(不抛错)', () => {
const glb = model({ format: ModelFormat.Glb, vrmVersion: null, stats: null });
expect(unusableReason(glb)).toContain('未产出 VRM');
});
});
describe('目录导出只含可用模型', () => {
function buildService(captured: { modelsWhere?: unknown }): CatalogService {
const songs = { find: vi.fn().mockResolvedValue([]) };
const motions = { find: vi.fn().mockResolvedValue([]) };
const models = {
find: vi.fn().mockImplementation((options: { where: unknown }) => {
captured.modelsWhere = options.where;
return Promise.resolve([model({ id: 7, format: ModelFormat.Vrm })]);
}),
};
const songsService = { toDtos: vi.fn().mockResolvedValue([]) };
const motionsService = { toDtos: vi.fn().mockResolvedValue([]) };
const modelsService = {
toDtos: vi.fn().mockImplementation((rows: CharacterModel[]) =>
rows.map((row) => toModelDto(row, { fileUrl: '/f', thumbnailUrl: null })),
),
resolveDefaultModelId: vi.fn().mockResolvedValue(7),
};
const config = { contractVersions: { 'rest-api': '0.5.0' } };
return new CatalogService(
songs as never,
motions as never,
models as never,
songsService as never,
motionsService as never,
modelsService as never,
config as never,
);
}
it('查询条件限定 status=published 且 format=vrm', async () => {
const captured: { modelsWhere?: unknown } = {};
const bundle = await buildService(captured).exportBundle();
expect(captured.modelsWhere).toEqual({ status: PublishStatus.Published, format: ModelFormat.Vrm });
expect(bundle.models.map((m) => m.id)).toEqual([7]);
expect(bundle.models.every((m) => m.usable)).toBe(true);
});
it('目录指纹同样只统计可用模型(否则客户端会因"不可见变化"反复刷新)', async () => {
const captured: { modelsWhere?: unknown } = {};
await buildService(captured).version();
expect(captured.modelsWhere).toEqual({ status: PublishStatus.Published, format: ModelFormat.Vrm });
});
});