Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39bfd390e3 | ||
|
|
eebccd55b4 | ||
|
|
ae8a68e98f | ||
|
|
8e8cc0475b |
@@ -101,7 +101,7 @@ opendance-web/
|
||||
│ ├── admin/ # React 管理端
|
||||
│ │ ├── src/components/ModelReviewPanel.tsx # 模型审核面板 + 骨骼详细界面
|
||||
│ │ └── src/lib/bone-tree.ts # 骨骼树过滤(搜索保留祖先链)
|
||||
│ ├── test/ # 单元测试 + 端到端冒烟(12 文件 / 193 项)
|
||||
│ ├── test/ # 单元测试 + 端到端冒烟(16 文件 / 225 项)
|
||||
│ │ # mmd-vmd 31 / model-archive 24 / model-inspector 25
|
||||
│ │ # / model-thumbnail 8 / admin-bone-filter 8
|
||||
│ │ # / preprocess 25 / init-env 16 / admin-port 16
|
||||
@@ -112,6 +112,7 @@ opendance-web/
|
||||
├── deploy/ # ★ 业务服务部署(不含 MySQL、不含反代)
|
||||
│ ├── init-env.sh # ★ 首次启动的.env 交互引导(install.sh 缺.env 时调用)
|
||||
│ ├── env-lib.sh # ★ deploy/.env 语法预检(被 install.sh / ctl.sh 引用)
|
||||
│ ├── assimp-lib.sh # ★ Assimp 定位与安装(install.sh / check-access.sh 引用)
|
||||
│ ├── install.sh # 一键部署(systemd / OpenRC / SysVinit / 后台进程)
|
||||
│ ├── uninstall.sh
|
||||
│ ├── ctl.sh # 无 init 系统时的进程控制
|
||||
@@ -195,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 的种子匹配
|
||||
@@ -282,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`。
|
||||
@@ -334,13 +346,22 @@ 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` -> **12 个文件 / 193 项通过**
|
||||
- 测试:`npx vitest run` -> **16 个文件 / 225 项通过**
|
||||
(`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)。
|
||||
|
||||
## 12. 首次启动的.env 引导(deploy/init-env.sh)、.env 预检与监听地址
|
||||
## 12. 首次启动的.env 引导(deploy/init-env.sh)、.env 预检、Assimp 与监听地址
|
||||
|
||||
- `deploy/assimp-lib.sh`: Assimp(外部命令行工具)的定位与安装。`install.sh` 按发行版
|
||||
自动安装(apt-get / dnf / yum / zypper / apk / pacman),装在非常规目录时把绝对路径写进
|
||||
`deploy/.env` 的 `ASSIMP_BIN`;装不上只告警不中止(`SKIP_ASSIMP_INSTALL=1` 跳过)。
|
||||
缺失只影响 `.pmx/.fbx` 转换与 FBX/glTF 动作预处理,`.glb/.vrm` 不受影响。
|
||||
- `models.stats` 必须是 **MEDIUMTEXT**(迁移 `AddModelStatsMediumText`):骨骼树按骨骼逐条
|
||||
展开,实测 643 骨骼的 PMX 分析结果 70,980 字节 > TEXT 上限 65,535,写入报 1406 并让上传
|
||||
500。服务层另有 `shrinkStatsForStorage` 兜底(只裁骨骼树,保留全部汇总字段)。
|
||||
- 压缩包文件名解码:Shift-JIS 试解后若含**私用区字符**同样视为解错并回退 GBK(WHATWG 的
|
||||
shift_jis 把未定义码位映射成 PUA 而非 U+FFFD,会让 `tex/髮.png` 丢字符、贴图对不上)。
|
||||
- `deploy/env-lib.sh`: `.env` 语法预检。`install.sh` / `ctl.sh` 用
|
||||
`set -a; . deploy/.env` 载入配置时 shell 会真的执行该文件,值含空格却未加引号
|
||||
会被切成「赋值 + 命令」(实测报 `line 53: Miku.pmx: command not found`,退出码 127)。
|
||||
|
||||
@@ -10,7 +10,39 @@ OpenDance Studio **阶段一**: Web 管理服务端(NestJS + TypeORM + 现有 My
|
||||
|
||||
## 状态
|
||||
|
||||
**阶段一已完成**: T-WEB-001 -> T-WEB-010 全部落地,当前版本 **v0.2.2**(契约 `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 修订:
|
||||
|
||||
1. **修复缩略图"白模"**:缩略图渲染器原先**刻意不解码贴图**,只用 `baseColorFactor` 上色;而 MMD(PMX 转换)模型的 baseColorFactor 基本都是白色,于是列表页与审核面板里的缩略图全是白色模型。现在渲染器内置极简 PNG 解码器(zlib + 反滤波,8 位非隔行,colorType 0/2/3/4/6)并按 `baseColorFactor x 贴图` 逐像素采样,同时按 `alphaMode`(OPAQUE / MASK / BLEND)处理透明度;解码失败或非 PNG 时回退纯色,绝不抛错;
|
||||
2. 缩略图取景收紧(FRAMING 1.6 -> 1.3),40px 列表缩略图里主体更清楚;
|
||||
3. 新增 6 项贴图/透明度/朝向测试(`test/model-thumbnail-texture.spec.ts`);
|
||||
4. **说明**:GLB 数据本身没问题——贴图逐字节内嵌(18/18)、39 个材质的贴图对应关系与 PMX 完全一致、UV 取到的就是皮肤/五官区域;白模只出在缩略图渲染器。
|
||||
|
||||
v0.2.3 修订:
|
||||
|
||||
1. **修复上传 PMX 返回 500**(`models.stats` 容量):分析结果里的骨骼树按骨骼逐条展开,实测一个 643 骨骼的 PMX(【奥黛塔】_by_原神.zip)就有 **70,980 字节**,而该列是 `TEXT`(上限 65,535),MySQL 严格模式直接拒绝写入(1406)导致 500。列迁移到 **MEDIUMTEXT**(`AddModelStatsMediumText`),并新增 `shrinkStatsForStorage` 兜底:即使库没迁移,也只截断骨骼树、保留面数/骨骼数/humanoid 覆盖/可驱动性,绝不让上传失败;
|
||||
2. **修复 GBK 压缩包丢贴图**:文件名解码先试 Shift-JIS,而 WHATWG 的 shift_jis 会把**未定义码位映射成私用区不可见字符**(不是 U+FFFD),于是像 `tex/髮.png`(GBK 字节 `F3 8C`)这样的名字被判为「解码成功」而永不回退 GBK,贴图名对不上就丢图。现在私用区也算解错信号;实测该模型贴图由 17/18 变为 **18/18 全部内嵌**;
|
||||
3. 新增 12 项测试(`test/model-stats-limit.spec.ts` 9 项 + 压缩包编码/目录条目 3 项)。
|
||||
|
||||
v0.2.2 修订:
|
||||
|
||||
@@ -53,15 +85,15 @@ v0.2.0 主要变更:
|
||||
3. 取得发布包并校验(地址用你们自己的制品库替换; 下面是本仓库的发布地址)
|
||||
|
||||
```bash
|
||||
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.2.2/opendance-web-v0.2.2.tar.gz
|
||||
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.2.2/SHA256SUMS
|
||||
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.3.0/opendance-web-v0.3.0.tar.gz
|
||||
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.3.0/SHA256SUMS
|
||||
sha256sum -c SHA256SUMS # 期望输出 "OK"
|
||||
```
|
||||
|
||||
4. 解压并生成配置(交互式引导,逐项问答,口令不回显)
|
||||
|
||||
```bash
|
||||
tar -xzf opendance-web-v0.2.2.tar.gz && cd opendance-web-v0.2.2
|
||||
tar -xzf opendance-web-v0.3.0.tar.gz && cd opendance-web-v0.3.0
|
||||
bash deploy/init-env.sh
|
||||
```
|
||||
|
||||
@@ -131,8 +163,8 @@ FLUSH PRIVILEGES;
|
||||
### 5. 部署步骤
|
||||
|
||||
```bash
|
||||
tar -xzf opendance-web-v0.2.2.tar.gz
|
||||
cd opendance-web-v0.2.2
|
||||
tar -xzf opendance-web-v0.3.0.tar.gz
|
||||
cd opendance-web-v0.3.0
|
||||
bash deploy/init-env.sh # 首次启动引导: 逐项问答生成 deploy/.env(见下)
|
||||
bash deploy/install.sh # 已以 root 登录, 不需要 sudo
|
||||
```
|
||||
@@ -273,6 +305,9 @@ 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` 会提前拦住并给出行号 |
|
||||
| 模型审核界面显示"未分析 / 无预览图" | 该模型是升级前入库的:调 `POST /api/models/<id>/reanalyze`,或批量跑 `node scripts/reanalyze-models.mjs --url http://127.0.0.1:3000` |
|
||||
|
||||
@@ -302,11 +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 # 193 项单元测试 / 12 个文件(VMD 31、模型压缩包 24、
|
||||
npm run test # 225 项单元测试 / 16 个文件(VMD 31、模型压缩包 27、
|
||||
# 模型检查器 25、缩略图 8、骨骼过滤 8、
|
||||
# 预处理 25、init-env 16、admin-port 16、
|
||||
# access-log 9、VRM 检查器 6、.env 预检 12、
|
||||
# Assimp 定位与安装 13)
|
||||
# Assimp 定位与安装 13、stats 容量与编码 12、
|
||||
# 缩略图贴图采样 6、MMD 材质对齐 9、模型可用性 5)
|
||||
npm run build # 生产构建
|
||||
npm run start:prod & # 启动
|
||||
npm run test:smoke # 57 项端到端冒烟(需要数据库可连通)
|
||||
@@ -329,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`) |
|
||||
@@ -427,10 +464,10 @@ node scripts/reanalyze-models.mjs --url http://127.0.0.1:3000
|
||||
| 能力 | 实现 |
|
||||
| --- | --- |
|
||||
| 分析 | `model-inspector.ts` 解析 GLB/VRM:面数 / 顶点 / 网格 / 材质 / 贴图 / 节点 / 形变目标 / 动画 / 蒙皮骨骼数 / 骨骼树 / humanoid 覆盖 / 可驱动性(缺哪些必需骨骼)/ warnings,写入 `models.stats`(迁移 `AddModelStats1789460000000`,新增 `models.stats TEXT`) |
|
||||
| 缩略图 | `model-thumbnail.ts` 用**纯 TS 软件光栅化**生成 PNG(读 GLB/glTF -> 应用节点层级与蒙皮 -> 包围盒自动构图 -> 透视投影 -> z-buffer 逐三角形平面着色 -> 手写 PNG 编码),**零原生依赖**(不需要 canvas / headless-gl / puppeteer)。默认 512x512,写入 `models.thumbnail_asset_id` / `thumbnailUrl`;失败或非 glTF 容器时留空,列表页退化为格式占位图 |
|
||||
| 缩略图 | `model-thumbnail.ts` 用**纯 TS 软件光栅化**生成 PNG(读 GLB/glTF -> 应用节点层级与蒙皮 -> 包围盒自动构图 -> 透视投影 -> z-buffer + 平面着色 + **逐像素采样 baseColorTexture**,内置 PNG 解码器 -> 手写 PNG 编码),**零原生依赖**(不需要 canvas / headless-gl / puppeteer);按 `alphaMode` 处理 OPAQUE / MASK / BLEND。默认 512x512,写入 `models.thumbnail_asset_id` / `thumbnailUrl`;失败或非 glTF 容器时留空,列表页退化为格式占位图 |
|
||||
| 预览 | 管理端 3D 预览放开到 `vrm/glb/gltf`(`.fbx` 仍提示「仅归档,请先转换为 GLB/VRM」);列表页显示 40px 小缩略图,审核面板显示 116px 缩略图 |
|
||||
|
||||
实测:512x512 PNG / 15,043 字节,目视确认为居中的 T-pose 角色图;真实 10MB VRM(83 关节、5307 顶点)单张耗时 60-121ms(中位 79ms)。
|
||||
实测:512x512 PNG / 15-42 KB(带贴图后变大),目视确认为居中的 T-pose 角色图且能看到肤色/眼睛/服装贴图;真实 10MB VRM(83 关节、5307 顶点)单张耗时 60-121ms(中位 79ms),27MB PMX 转换件约 200-400ms。
|
||||
|
||||
### 审核流程(模型)
|
||||
|
||||
|
||||
+82
-7
@@ -1,5 +1,5 @@
|
||||
================================================================
|
||||
OpenDance Studio -- Web 管理服务端 v0.2.2 使用说明
|
||||
OpenDance Studio -- Web 管理服务端 v0.3.0 使用说明
|
||||
================================================================
|
||||
|
||||
本服务端是 OpenDance Studio 三端中的第一端, 负责管理歌曲、VRM 模型与
|
||||
@@ -8,6 +8,62 @@ OpenDance Studio -- Web 管理服务端 v0.2.2 使用说明
|
||||
重要: 本服务端 不部署、不管理 MySQL。数据库为部署方提供的现有实例,
|
||||
连接信息通过 .env 注入。
|
||||
|
||||
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 基本都是白色, 于是列表页与
|
||||
审核面板里的缩略图全是白色模型。现在内置极简 PNG 解码器(zlib + 反滤波,
|
||||
8 位非隔行, colorType 0/2/3/4/6), 按 baseColorFactor x 贴图逐像素采样,
|
||||
并按 alphaMode(OPAQUE / MASK / BLEND)处理透明度; 解码失败回退纯色。
|
||||
2. 缩略图取景收紧(FRAMING 1.6 -> 1.3), 40px 列表缩略图里主体更清楚。
|
||||
3. 新增 6 项贴图/透明度测试(test/model-thumbnail-texture.spec.ts)。
|
||||
4. 说明: GLB 数据本身没问题 - 贴图逐字节内嵌(18/18)、39 个材质的贴图对应
|
||||
关系与 PMX 完全一致; 白模只出在缩略图渲染器。
|
||||
|
||||
v0.2.3 修订
|
||||
1. 修复上传 PMX 返回 500(models.stats 容量): 分析结果里的骨骼树按骨骼逐条
|
||||
展开, 实测一个 643 骨骼的 PMX(【奥黛塔】_by_原神.zip)就有 70,980 字节,
|
||||
而该列是 TEXT(上限 65,535), MySQL 严格模式直接拒绝写入(1406)导致 500。
|
||||
列迁移到 MEDIUMTEXT(AddModelStatsMediumText), 并新增
|
||||
shrinkStatsForStorage 兜底: 即使库没迁移, 也只截断骨骼树、保留面数/
|
||||
骨骼数/humanoid 覆盖/可驱动性, 绝不让上传失败。
|
||||
2. 修复 GBK 压缩包丢贴图: 文件名解码先试 Shift-JIS, 而 WHATWG 的 shift_jis
|
||||
会把未定义码位映射成私用区不可见字符(不是 U+FFFD), 于是像 tex/髮.png
|
||||
(GBK 字节 F3 8C)这样的名字被判为"解码成功"而永不回退 GBK, 贴图名对不上
|
||||
就丢图。现在私用区也算解错信号; 实测该模型贴图由 17/18 变为 18/18 全部内嵌。
|
||||
3. 新增 12 项测试(test/model-stats-limit.spec.ts 9 项 + 压缩包编码/目录条目 3 项)。
|
||||
|
||||
v0.2.2 修订
|
||||
1. 修复 Assimp 缺失时的报错与部署体验: 服务器没装 Assimp 时, 上传 .pmx/.fbx
|
||||
(或含它们的压缩包)只得到两条 导出失败(ENOENT): spawn assimp ENOENT,
|
||||
@@ -45,11 +101,11 @@ v0.2.1 修订
|
||||
2. 准备一个现有的 MySQL / MariaDB 实例, 并建好库与账号(见下方"前置要求")
|
||||
本项目不会创建数据库本身
|
||||
3. 取得发布包并校验(地址用你们自己的制品库替换)
|
||||
curl -LO https://<制品库地址>/opendance-web-v0.2.2.tar.gz
|
||||
curl -LO https://<制品库地址>/opendance-web-v0.3.0.tar.gz
|
||||
curl -LO https://<制品库地址>/SHA256SUMS
|
||||
sha256sum -c SHA256SUMS # 期望输出 "OK"
|
||||
4. 解压并生成配置(交互式引导, 逐项问答, 口令不回显)
|
||||
tar -xzf opendance-web-v0.2.2.tar.gz && cd opendance-web-v0.2.2
|
||||
tar -xzf opendance-web-v0.3.0.tar.gz && cd opendance-web-v0.3.0
|
||||
bash deploy/init-env.sh
|
||||
5. 安装(建用户与目录 -> 装依赖 -> 迁移 -> 注册系统服务 -> 等健康检查)
|
||||
bash deploy/install.sh
|
||||
@@ -107,8 +163,8 @@ v0.2.1 修订
|
||||
(本项目不会创建数据库本身, 也不需要 GRANT OPTION / FILE / SUPER 等管理权限)
|
||||
|
||||
部署步骤
|
||||
tar -xzf opendance-web-v0.2.2.tar.gz
|
||||
cd opendance-web-v0.2.2
|
||||
tar -xzf opendance-web-v0.3.0.tar.gz
|
||||
cd opendance-web-v0.3.0
|
||||
bash deploy/init-env.sh # 首次启动引导: 逐项问答生成 deploy/.env(见下)
|
||||
bash deploy/install.sh # 已以 root 登录, 不需要 sudo
|
||||
|
||||
@@ -239,6 +295,20 @@ 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
|
||||
- 导入模型返回 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")后重跑。
|
||||
@@ -269,11 +339,12 @@ deploy/.env 初始化引导(deploy/init-env.sh)
|
||||
cd web-server
|
||||
npm run contracts:check # 契约版本一致性
|
||||
npm run typecheck # TypeScript 严格检查
|
||||
npm run test # 193 项单元测试 / 12 个文件(VMD 31、模型压缩包 24、
|
||||
npm run test # 225 项单元测试 / 16 个文件(VMD 31、模型压缩包 24、
|
||||
# 模型检查器 25、缩略图 8、骨骼过滤 8、
|
||||
# 预处理 25、init-env 16、admin-port 16、
|
||||
# access-log 9、VRM 检查器 6、.env 预检 12、
|
||||
# Assimp 定位与安装 13)
|
||||
# Assimp 定位与安装 13、stats 容量与编码 12、缩略图贴图 6、
|
||||
# MMD 材质对齐 9、模型可用性 5)
|
||||
npm run build # 生产构建
|
||||
npm run start:prod & # 启动
|
||||
npm run test:smoke # 57 项端到端冒烟(需要数据库可连通)
|
||||
@@ -331,6 +402,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; 不设置时按源码种子
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
# 规则:任何字段级变更必须提升对应条目版本,并回到 opendance-web 修改后再向另两端建迁移任务。
|
||||
rest-api: 0.4.0
|
||||
websocket-keypoints: 0.1.0
|
||||
data-models: 0.4.0
|
||||
data-models: 0.5.0
|
||||
skeleton-topology: 0.1.0
|
||||
model-formats: 0.4.0
|
||||
model-formats: 0.5.0
|
||||
database: 0.3.0
|
||||
|
||||
@@ -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 | 读 | |
|
||||
|
||||
@@ -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**。
|
||||
|
||||
|
||||
+9
-5
@@ -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
@@ -1,5 +1,5 @@
|
||||
project: opendance-web-server
|
||||
version: 0.2.2
|
||||
version: 0.3.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.2.tar.gz
|
||||
artifact: opendance-web-v0.3.0.tar.gz
|
||||
packaging: Linux 业务服务(系统服务托管,双端口:软件 API + 管理端,不含 MySQL、不含反向代理、不使用 Docker)
|
||||
includes:
|
||||
- web-server/ # NestJS 源码 + 构建产物(含 BVH / VMD 内置解析、ZIP 读取与模型压缩包转换)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
# ============================================================
|
||||
# 打包发布产物:opendance-web-v0.2.2.tar.gz
|
||||
# 打包发布产物:opendance-web-v0.3.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.2}"
|
||||
VERSION="${1:-0.3.0}"
|
||||
NAME="opendance-web-v${VERSION}"
|
||||
OUT_DIR="$REPO_ROOT/dist-release"
|
||||
STAGE="$OUT_DIR/$NAME"
|
||||
|
||||
@@ -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 # 12 个文件 / 193 项通过
|
||||
npx vitest run # 16 个文件 / 225 项通过
|
||||
npm run test:smoke # 冒烟 [4] 段落
|
||||
```
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ draft ──submit──▶ pending ──approve──▶ published
|
||||
|
||||
```bash
|
||||
cd web-server
|
||||
npx vitest run # 12 个文件 / 193 项通过(含 admin-bone-filter 8 项、.env 预检 12 项、Assimp 13 项)
|
||||
npx vitest run # 16 个文件 / 225 项通过(含 admin-bone-filter 8 项、.env 预检 12 项、Assimp 13 项、缩略图贴图 6 项、MMD 材质对齐 9 项、模型可用性 5 项)
|
||||
npm run test:smoke
|
||||
```
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opendance-admin",
|
||||
"private": true,
|
||||
"version": "0.2.2",
|
||||
"version": "0.3.0",
|
||||
"type": "module",
|
||||
"description": "OpenDance Studio 管理端(React + TypeScript + Vite)",
|
||||
"scripts": {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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}`;
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
Vendored
+3
@@ -7,3 +7,6 @@ interface ImportMetaEnv {
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv;
|
||||
}
|
||||
|
||||
/** 构建期注入的应用版本号(来自 web-server/package.json) */
|
||||
declare const __APP_VERSION__: string;
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "opendance-web-server",
|
||||
"version": "0.2.2",
|
||||
"version": "0.3.0",
|
||||
"description": "OpenDance Studio Web 管理服务端(NestJS + TypeORM + 现有 MySQL 实例)",
|
||||
"license": "MIT",
|
||||
"private": true,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -46,8 +46,21 @@ function decoderFor(encoding: string): TextDecoder | null {
|
||||
return decoders.get(encoding) ?? null;
|
||||
}
|
||||
|
||||
/** 半角片假名:Shift-JIS 被误用时会出现,用来判断该不该换编码 */
|
||||
/**
|
||||
* 半角片假名:Shift-JIS 被误用时会出现,用来判断该不该换编码。
|
||||
*
|
||||
* 私用区(PUA)同样是「Shift-JIS 解错了」的信号:WHATWG 的 shift_jis 表把
|
||||
* **未定义的码位**映射到私用区,而不是 U+FFFD,于是解码结果看起来「成功」,
|
||||
* 却是看不见的乱码字。实测 GBK 的 `髮`(字节 F3 8C)就落在这里:
|
||||
* 先试 Shift-JIS 得到 `tex/\uE0xx.png`(不可见),永远不会回退到 GBK,
|
||||
* 贴图名对不上,模型入库后丢贴图。
|
||||
*/
|
||||
const HALF_WIDTH_KATAKANA = /[\uFF61-\uFF9F]/;
|
||||
const PRIVATE_USE_AREA = /[\uE000-\uF8FF]/;
|
||||
/** Shift-JIS 解码结果是否明显解错了(该换 GBK 再试) */
|
||||
function looksMisdecoded(text: string): boolean {
|
||||
return text.includes('\uFFFD') || HALF_WIDTH_KATAKANA.test(text) || PRIVATE_USE_AREA.test(text);
|
||||
}
|
||||
|
||||
/** 解压包内文件名:UTF-8 标志位优先,否则试 Shift-JIS(中文/日文压缩包常见) */
|
||||
function decodeEntryName(bytes: Buffer, utf8Flag: boolean): string {
|
||||
@@ -57,7 +70,7 @@ function decodeEntryName(bytes: Buffer, utf8Flag: boolean): string {
|
||||
const shiftJis = decoderFor('shift_jis');
|
||||
if (shiftJis) {
|
||||
const decoded = shiftJis.decode(bytes);
|
||||
if (!decoded.includes('\uFFFD') && !HALF_WIDTH_KATAKANA.test(decoded)) return decoded;
|
||||
if (!looksMisdecoded(decoded)) return decoded;
|
||||
}
|
||||
const gbk = decoderFor('gbk');
|
||||
if (gbk) {
|
||||
|
||||
@@ -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 ?? '',
|
||||
|
||||
@@ -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',
|
||||
'data-models': '0.5.0',
|
||||
'skeleton-topology': '0.1.0',
|
||||
'model-formats': '0.4.0',
|
||||
'model-formats': '0.5.0',
|
||||
database: '0.3.0',
|
||||
});
|
||||
|
||||
|
||||
@@ -52,8 +52,35 @@ export class CharacterModel {
|
||||
/**
|
||||
* 模型分析结果(面数 / 骨骼树 / humanoid 覆盖 / 可驱动性…),见 model-inspector.ts。
|
||||
* 存 JSON 文本:审核界面要展示,且骨骼树可能上千行,不适合拆列。
|
||||
*
|
||||
* 必须是 **MEDIUMTEXT**(16MB)而不是 TEXT(64KB):骨骼树按骨骼逐条展开,
|
||||
* 实测一个 643 骨骼的 PMX(【奥黛塔】)分析结果就有 70,980 字节,超过 TEXT 上限,
|
||||
* MySQL 严格模式下写入直接报 1406,上传接口 500。
|
||||
* 用 mediumtext + transformer 而不是 simple-json:simple-json 固定映射到 text,
|
||||
* 实体元数据会和数据库列型不一致(后续 migration:generate 会把列改回 text)。
|
||||
*/
|
||||
@Column({ name: 'stats', type: 'simple-json', nullable: true })
|
||||
@Column({
|
||||
name: 'stats',
|
||||
type: 'mediumtext',
|
||||
nullable: true,
|
||||
transformer: {
|
||||
to: (value: Record<string, unknown> | null): string | null =>
|
||||
value === null || value === undefined
|
||||
? null
|
||||
: typeof value === 'string'
|
||||
? value
|
||||
: JSON.stringify(value),
|
||||
from: (value: string | null): Record<string, unknown> | null => {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
try {
|
||||
return JSON.parse(value) as Record<string, unknown>;
|
||||
} catch {
|
||||
// 历史脏数据不应该让整个接口 500
|
||||
return { parseError: true, raw: value.slice(0, 200) };
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
stats!: Record<string, unknown> | null;
|
||||
|
||||
// ---- 来源五元组(必填)----
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||
|
||||
/**
|
||||
* `models.stats` 由 TEXT(64KB)扩到 MEDIUMTEXT(16MB)。
|
||||
*
|
||||
* 起因(真实故障):上传含 PMX 的压缩包(【奥黛塔】_by_原神.zip,643 根骨骼)
|
||||
* 时接口返回 500。模型转换本身成功,但分析结果里的骨骼树按骨骼逐条展开,
|
||||
* JSON 实测 70,980 字节 > TEXT 上限 65,535,MySQL / MariaDB 严格模式直接拒绝
|
||||
* 写入(ER_DATA_TOO_LONG / 1406),而写入这一步没有兜底。
|
||||
*
|
||||
* MMD / VRM 模型骨骼上千根很常见,MEDIUMTEXT 给到 16MB 足够;
|
||||
* 服务端另有 shrinkStatsForStorage 兜底,避免在未迁移的库上再次 500。
|
||||
*/
|
||||
export class AddModelStatsMediumText1789550000000 implements MigrationInterface {
|
||||
name = 'AddModelStatsMediumText1789550000000'
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`ALTER TABLE \`models\` MODIFY \`stats\` mediumtext NULL`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
// 回退可能截断超长数据:这里只改列型,不做内容裁剪
|
||||
await queryRunner.query(`ALTER TABLE \`models\` MODIFY \`stats\` text NULL`);
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
@@ -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 });
|
||||
|
||||
@@ -667,3 +667,70 @@ export async function inspectModelFile(absPath: string, fileSize?: number): Prom
|
||||
|
||||
return analyzeGltfDocument(gltf, glb ? 'glb' : 'gltf', size, warnings);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------- 存储兜底:裁剪超大的 stats */
|
||||
|
||||
/** MySQL / MariaDB 的 TEXT 上限(未迁移 MEDIUMTEXT 的老库仍是这个值) */
|
||||
export const MYSQL_TEXT_LIMIT = 65535;
|
||||
|
||||
/** 裁剪后至少保留的骨骼条目数:太少审核界面就看不出结构了 */
|
||||
const MIN_BONE_TREE_KEPT = 24;
|
||||
|
||||
/**
|
||||
* 把过大的 `ModelStats` 裁到能安全写进 TEXT 的大小(纯函数,永不抛异常)。
|
||||
*
|
||||
* 为什么需要:`models.stats` 里最占地方的是骨骼树,按骨骼逐条展开。
|
||||
* 实测一个 643 骨骼的 PMX 分析结果 70,980 字节 > TEXT 上限 65,535,
|
||||
* MySQL 严格模式会直接拒绝写入(1406)。迁移已把列扩到 MEDIUMTEXT,
|
||||
* 这里再兜一层:万一跑在没迁移的库上,也宁可少存骨骼明细,不能让上传 500。
|
||||
*
|
||||
* 保留策略:面数 / 骨骼数 / humanoid 覆盖 / 可驱动性 / warnings 一律保留,
|
||||
* 只裁骨骼树(父在前,从头截断即保留祖先链),并追加一条 warning 说明被裁过。
|
||||
*/
|
||||
export function shrinkStatsForStorage(
|
||||
stats: ModelStats,
|
||||
maxBytes: number = MYSQL_TEXT_LIMIT,
|
||||
): ModelStats {
|
||||
const fits = (candidate: ModelStats): boolean => {
|
||||
try {
|
||||
return JSON.stringify(candidate).length <= maxBytes;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if (fits(stats)) return stats;
|
||||
|
||||
const note = `骨骼树过大(原 ${stats.boneTree.length} 条),存储前已截断`;
|
||||
const withNote = (boneTree: BoneNode[]): ModelStats => ({
|
||||
...stats,
|
||||
boneTree,
|
||||
warnings: stats.warnings.includes(note) ? stats.warnings : [...stats.warnings, note],
|
||||
});
|
||||
|
||||
// 二分找能放下的最大前缀长度(骨骼树父在前,前缀即祖先链完整的子集)
|
||||
let low = Math.min(MIN_BONE_TREE_KEPT, stats.boneTree.length);
|
||||
let high = stats.boneTree.length;
|
||||
let best = withNote(stats.boneTree.slice(0, low));
|
||||
while (low <= high) {
|
||||
const mid = Math.floor((low + high) / 2);
|
||||
const candidate = withNote(stats.boneTree.slice(0, mid));
|
||||
if (fits(candidate)) {
|
||||
best = candidate;
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 极端情况:连最小骨骼树都放不下 -> 只留汇总字段
|
||||
if (!fits(best)) {
|
||||
const summary = withNote([]);
|
||||
if (fits(summary)) return summary;
|
||||
return {
|
||||
...summary,
|
||||
missingRequiredBones: summary.missingRequiredBones.slice(0, 16),
|
||||
warnings: [note],
|
||||
};
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { inflateSync } from 'node:zlib';
|
||||
import { dirname, resolve as resolvePath } from 'node:path';
|
||||
import { deflateSync } from 'node:zlib';
|
||||
|
||||
@@ -22,9 +23,12 @@ import { deflateSync } from 'node:zlib';
|
||||
* **退化为不蒙皮**,按节点世界矩阵画绑定姿态(bind pose)——多数 VRM 的绑定姿态
|
||||
* 就是可看的 T/A 姿态,比错误的蒙皮矩阵导致的"爆炸形状"安全得多。
|
||||
* - 按 glTF 规范,蒙皮网格节点自身的变换被忽略(顶点直接由关节矩阵驱动)。
|
||||
* 2. **不采样贴图**:`pbrMetallicRoughness.baseColorFactor` 作为纯色基色,
|
||||
* 即使存在 `baseColorTexture` 也不解码(避免再引入 PNG/JPEG 解码器),
|
||||
* 因此带贴图的模型缩略图会是纯色块,但轮廓与光影正确。
|
||||
* 2. **采样 baseColorTexture**:内置极简 PNG 解码器(zlib + 反滤波,8 位、非隔行、
|
||||
* colorType 0/2/3/4/6),按 `baseColorFactor x 贴图` 逐像素取色,并按
|
||||
* `alphaMode`(OPAQUE / MASK / BLEND)处理透明度。
|
||||
* 这一版之前**不采样贴图**:MMD 模型(PMX 转换而来)的 `baseColorFactor` 几乎
|
||||
* 都是白色,于是缩略图全是"白模"——用户报的正是这个。
|
||||
* 解码失败/非 PNG/隔行扫描时回退为 `baseColorFactor` 纯色,绝不抛错。
|
||||
* 3. **稀疏 accessor(sparse)不支持**:遇到就直接跳过该 primitive。
|
||||
* 4. **只画三角形(mode=4)**,其余图元(点/线/条带/扇形)跳过。
|
||||
* 5. 大模型(>17M 索引)不会出现,索引统一按 uint32 读取。
|
||||
@@ -70,7 +74,8 @@ const DEFAULT_BACKGROUND: [number, number, number] = [24, 26, 32];
|
||||
/** 垂直视场角(度) */
|
||||
const FOV_Y_DEG = 35;
|
||||
/** 相机距离系数:让模型占画面约 1/1.6,保证不裁剪 */
|
||||
const FRAMING = 1.6;
|
||||
// 1.6 -> 1.3:列表页只有 40px,主体太小就只剩一团像素
|
||||
const FRAMING = 1.3;
|
||||
/** 主光方向(世界空间,未归一化,用前会归一化) */
|
||||
const LIGHT_DIR: [number, number, number] = normalize3(0.4, 0.8, 0.6);
|
||||
/** 环境光强度 */
|
||||
@@ -244,8 +249,27 @@ interface GltfSkin {
|
||||
interface GltfMaterial {
|
||||
pbrMetallicRoughness?: {
|
||||
baseColorFactor?: number[];
|
||||
baseColorTexture?: unknown;
|
||||
baseColorTexture?: { index?: number; texCoord?: number };
|
||||
};
|
||||
alphaMode?: string;
|
||||
alphaCutoff?: number;
|
||||
doubleSided?: boolean;
|
||||
}
|
||||
|
||||
interface GltfTexture {
|
||||
source?: number;
|
||||
sampler?: number;
|
||||
}
|
||||
|
||||
interface GltfImage {
|
||||
bufferView?: number;
|
||||
mimeType?: string;
|
||||
uri?: string;
|
||||
}
|
||||
|
||||
interface GltfSampler {
|
||||
wrapS?: number;
|
||||
wrapT?: number;
|
||||
}
|
||||
|
||||
interface GltfScene {
|
||||
@@ -262,6 +286,9 @@ interface GltfDocument {
|
||||
bufferViews?: GltfBufferView[];
|
||||
buffers?: GltfBufferRef[];
|
||||
materials?: GltfMaterial[];
|
||||
textures?: GltfTexture[];
|
||||
images?: GltfImage[];
|
||||
samplers?: GltfSampler[];
|
||||
skins?: GltfSkin[];
|
||||
}
|
||||
|
||||
@@ -278,9 +305,26 @@ interface AccessorData {
|
||||
}
|
||||
|
||||
/** 收集好的三角形:positions 每 9 个数一个三角形,colors 每 3 个数一个三角形 */
|
||||
interface DecodedImage {
|
||||
width: number;
|
||||
height: number;
|
||||
/** RGBA,行优先,长度 = width*height*4 */
|
||||
rgba: Uint8Array;
|
||||
}
|
||||
|
||||
interface SceneGeometry {
|
||||
positions: Float32Array;
|
||||
colors: Float32Array;
|
||||
/** 每顶点 UV(2 个/顶点);没有 TEXCOORD_0 时为 null */
|
||||
uvs: Float32Array | null;
|
||||
/** 每顶点贴图槽位(索引进 textures);-1 表示该顶点无贴图 */
|
||||
texSlots: Int32Array | null;
|
||||
/** 每顶点 alpha 模式:0=OPAQUE 1=MASK 2=BLEND */
|
||||
alphaModes: Uint8Array | null;
|
||||
/** 每顶点 MASK 阈值 */
|
||||
cutoffs: Float32Array | null;
|
||||
/** 解码后的贴图(RGBA) */
|
||||
textures: DecodedImage[];
|
||||
triangleCount: number;
|
||||
}
|
||||
|
||||
@@ -667,6 +711,36 @@ function materialBaseColor(doc: GltfDocument, materialIndex: number | undefined)
|
||||
return [0.8, 0.8, 0.8];
|
||||
}
|
||||
|
||||
/** 取 bufferView 的原始字节(贴图解压用);越界返回 null */
|
||||
function readBufferViewBytes(
|
||||
doc: GltfDocument,
|
||||
buffers: Array<Buffer | null>,
|
||||
bufferViewIndex: number,
|
||||
): Buffer | null {
|
||||
const view = doc.bufferViews?.[bufferViewIndex];
|
||||
if (!view || typeof view.buffer !== 'number') return null;
|
||||
const buffer = buffers[view.buffer];
|
||||
if (!buffer) return null;
|
||||
const offset = view.byteOffset ?? 0;
|
||||
const length = view.byteLength ?? 0;
|
||||
if (offset < 0 || length <= 0 || offset + length > buffer.length) return null;
|
||||
return buffer.subarray(offset, offset + length);
|
||||
}
|
||||
|
||||
/** 解码 GLB 内嵌的 PNG 贴图;外部 uri / 非 PNG / 解码失败都返回 null(回退纯色) */
|
||||
function decodeEmbeddedImage(
|
||||
doc: GltfDocument,
|
||||
buffers: Array<Buffer | null>,
|
||||
imageIndex: number,
|
||||
): DecodedImage | null {
|
||||
const image = doc.images?.[imageIndex];
|
||||
if (!image || typeof image.bufferView !== 'number') return null;
|
||||
if (typeof image.mimeType === 'string' && !image.mimeType.toLowerCase().includes('png')) return null;
|
||||
const bytes = readBufferViewBytes(doc, buffers, image.bufferView);
|
||||
if (!bytes) return null;
|
||||
return decodePng(bytes);
|
||||
}
|
||||
|
||||
/** 遍历场景图收集世界空间三角形 */
|
||||
function collectTriangles(container: GltfContainer): SceneGeometry | null {
|
||||
const { doc, buffers } = container;
|
||||
@@ -676,8 +750,49 @@ function collectTriangles(container: GltfContainer): SceneGeometry | null {
|
||||
|
||||
const positions: number[] = [];
|
||||
const colors: number[] = [];
|
||||
const uvs: number[] = [];
|
||||
const texSlots: number[] = [];
|
||||
const alphaModes: number[] = [];
|
||||
const cutoffs: number[] = [];
|
||||
const textures: DecodedImage[] = [];
|
||||
const materialTextureCache = new Map<number, { slot: number; alphaMode: number; cutoff: number }>();
|
||||
const imageCache = new Map<number, DecodedImage | null>();
|
||||
const skinScratch = new Float64Array(16);
|
||||
|
||||
/**
|
||||
* 解析材质的 baseColorTexture:解码一次并登记槽位。
|
||||
* MMD 模型的 baseColorFactor 基本都是白色,颜色全在贴图里 —— 不解码就是"白模"。
|
||||
*/
|
||||
const resolveMaterialTexture = (
|
||||
materialIndex: number | undefined,
|
||||
): { slot: number; alphaMode: number; cutoff: number } => {
|
||||
const key = typeof materialIndex === 'number' ? materialIndex : -1;
|
||||
const cached = materialTextureCache.get(key);
|
||||
if (cached) return cached;
|
||||
const material = typeof materialIndex === 'number' ? doc.materials?.[materialIndex] : undefined;
|
||||
const alphaMode = material?.alphaMode === 'MASK' ? 1 : material?.alphaMode === 'BLEND' ? 2 : 0;
|
||||
const rawCutoff = typeof material?.alphaCutoff === 'number' ? material.alphaCutoff : 0.5;
|
||||
const cutoff = clamp(rawCutoff, 0, 1);
|
||||
let slot = -1;
|
||||
const textureIndex = material?.pbrMetallicRoughness?.baseColorTexture?.index;
|
||||
if (typeof textureIndex === 'number') {
|
||||
const imageIndex = doc.textures?.[textureIndex]?.source;
|
||||
if (typeof imageIndex === 'number') {
|
||||
if (!imageCache.has(imageIndex)) {
|
||||
imageCache.set(imageIndex, decodeEmbeddedImage(doc, buffers, imageIndex));
|
||||
}
|
||||
const image = imageCache.get(imageIndex) ?? null;
|
||||
if (image) {
|
||||
slot = textures.length;
|
||||
textures.push(image);
|
||||
}
|
||||
}
|
||||
}
|
||||
const resolved = { slot, alphaMode, cutoff };
|
||||
materialTextureCache.set(key, resolved);
|
||||
return resolved;
|
||||
};
|
||||
|
||||
const appendMesh = (nodeIndex: number): void => {
|
||||
const node = nodes[nodeIndex];
|
||||
if (!node || typeof node.mesh !== 'number') return;
|
||||
@@ -710,6 +825,10 @@ function collectTriangles(container: GltfContainer): SceneGeometry | null {
|
||||
|
||||
const vertexCount = positionData.count;
|
||||
const [cr, cg, cb] = materialBaseColor(doc, primitive.material);
|
||||
const materialTexture = resolveMaterialTexture(primitive.material);
|
||||
const uvData =
|
||||
materialTexture.slot >= 0 ? readAccessorFloats(doc, buffers, attributes.TEXCOORD_0, 2) : null;
|
||||
const usableUv = uvData && uvData.count === vertexCount ? uvData : null;
|
||||
|
||||
// 顶点只变换一次:蒙皮或节点世界矩阵
|
||||
const px = new Float64Array(vertexCount);
|
||||
@@ -758,6 +877,18 @@ function collectTriangles(container: GltfContainer): SceneGeometry | null {
|
||||
}
|
||||
positions.push(x0, y0, z0, x1, y1, z1, x2, y2, z2);
|
||||
colors.push(cr, cg, cb);
|
||||
if (usableUv) {
|
||||
uvs.push(
|
||||
usableUv.values[i0 * 2], usableUv.values[i0 * 2 + 1],
|
||||
usableUv.values[i1 * 2], usableUv.values[i1 * 2 + 1],
|
||||
usableUv.values[i2 * 2], usableUv.values[i2 * 2 + 1],
|
||||
);
|
||||
} else {
|
||||
uvs.push(0, 0, 0, 0, 0, 0);
|
||||
}
|
||||
texSlots.push(materialTexture.slot, materialTexture.slot, materialTexture.slot);
|
||||
alphaModes.push(materialTexture.alphaMode, materialTexture.alphaMode, materialTexture.alphaMode);
|
||||
cutoffs.push(materialTexture.cutoff, materialTexture.cutoff, materialTexture.cutoff);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -784,6 +915,11 @@ function collectTriangles(container: GltfContainer): SceneGeometry | null {
|
||||
return {
|
||||
positions: Float32Array.from(positions),
|
||||
colors: Float32Array.from(colors),
|
||||
uvs: Float32Array.from(uvs),
|
||||
texSlots: Int32Array.from(texSlots),
|
||||
alphaModes: Uint8Array.from(alphaModes),
|
||||
cutoffs: Float32Array.from(cutoffs),
|
||||
textures,
|
||||
triangleCount,
|
||||
};
|
||||
}
|
||||
@@ -831,13 +967,25 @@ function edge(ax: number, ay: number, bx: number, by: number, px: number, py: nu
|
||||
* 屏幕空间有符号面积为负的是正面(NDC 里 CCW 正面经 y 翻转后变成负),
|
||||
* 因此 cullBackFace 时丢弃 area >= 0 的三角形。
|
||||
*/
|
||||
/** 采样贴图(REPEAT 环绕;glTF/PNG 的 UV 原点在左上,v 不翻转) */
|
||||
function sampleTexture(image: DecodedImage, u: number, v: number, out: Float32Array): void {
|
||||
const wrap = (value: number): number => value - Math.floor(value);
|
||||
const x = Math.min(image.width - 1, Math.floor(wrap(u) * image.width));
|
||||
const y = Math.min(image.height - 1, Math.floor(wrap(v) * image.height));
|
||||
const o = (y * image.width + x) * 4;
|
||||
out[0] = image.rgba[o] / 255;
|
||||
out[1] = image.rgba[o + 1] / 255;
|
||||
out[2] = image.rgba[o + 2] / 255;
|
||||
out[3] = image.rgba[o + 3] / 255;
|
||||
}
|
||||
|
||||
function rasterizeTriangles(
|
||||
geometry: SceneGeometry,
|
||||
viewProj: Mat4,
|
||||
options: RasterOptions,
|
||||
): RasterOutput {
|
||||
const { size, background, cullBackFace } = options;
|
||||
const { positions, colors, triangleCount } = geometry;
|
||||
const { positions, colors, uvs, texSlots, alphaModes, cutoffs, textures, triangleCount } = geometry;
|
||||
|
||||
const pixels = Buffer.alloc(size * size * 3);
|
||||
for (let i = 0; i < size * size; i += 1) {
|
||||
@@ -909,9 +1057,23 @@ function rasterizeTriangles(
|
||||
const baseR = colors[t * 3];
|
||||
const baseG = colors[t * 3 + 1];
|
||||
const baseB = colors[t * 3 + 2];
|
||||
const r = clamp(Math.round(baseR * intensity * 255), 0, 255);
|
||||
const g = clamp(Math.round(baseG * intensity * 255), 0, 255);
|
||||
const b = clamp(Math.round(baseB * intensity * 255), 0, 255);
|
||||
|
||||
// 贴图与透明度(每三角形常量;顶点数组按 3 顶点/三角形展开)
|
||||
const slot = texSlots ? texSlots[t * 3] : -1;
|
||||
const image = slot >= 0 ? textures[slot] ?? null : null;
|
||||
const alphaMode = alphaModes ? alphaModes[t * 3] : 0;
|
||||
const cutoff = cutoffs ? cutoffs[t * 3] : 0.5;
|
||||
const u0 = uvs ? uvs[t * 6] : 0;
|
||||
const v0 = uvs ? uvs[t * 6 + 1] : 0;
|
||||
const u1 = uvs ? uvs[t * 6 + 2] : 0;
|
||||
const v1 = uvs ? uvs[t * 6 + 3] : 0;
|
||||
const u2 = uvs ? uvs[t * 6 + 4] : 0;
|
||||
const v2 = uvs ? uvs[t * 6 + 5] : 0;
|
||||
const texel = new Float32Array(4);
|
||||
// 透视校正用:1/w 在三个顶点上的值
|
||||
const iw0 = 1 / p0[3];
|
||||
const iw1 = 1 / p1[3];
|
||||
const iw2 = 1 / p2[3];
|
||||
|
||||
const invArea = 1 / area;
|
||||
for (let y = minY; y <= maxY; y += 1) {
|
||||
@@ -926,6 +1088,27 @@ function rasterizeTriangles(
|
||||
const d = w0 * p0[2] + w1 * p1[2] + w2 * p2[2];
|
||||
const index = rowBase + x;
|
||||
if (d < depth[index]) {
|
||||
let r = clamp(Math.round(baseR * intensity * 255), 0, 255);
|
||||
let g = clamp(Math.round(baseG * intensity * 255), 0, 255);
|
||||
let b = clamp(Math.round(baseB * intensity * 255), 0, 255);
|
||||
if (image) {
|
||||
const iw = w0 * iw0 + w1 * iw1 + w2 * iw2;
|
||||
const u = (w0 * iw0 * u0 + w1 * iw1 * u1 + w2 * iw2 * u2) / (iw || 1);
|
||||
const v = (w0 * iw0 * v0 + w1 * iw1 * v1 + w2 * iw2 * v2) / (iw || 1);
|
||||
sampleTexture(image, u, v, texel);
|
||||
if (alphaMode === 1 && texel[3] < cutoff) continue; // MASK:整像素丢弃
|
||||
const a = alphaMode === 0 ? 1 : texel[3];
|
||||
r = clamp(Math.round(baseR * texel[0] * intensity * 255), 0, 255);
|
||||
g = clamp(Math.round(baseG * texel[1] * intensity * 255), 0, 255);
|
||||
b = clamp(Math.round(baseB * texel[2] * intensity * 255), 0, 255);
|
||||
if (alphaMode === 2 && a < 1) {
|
||||
// BLEND:与背景/已画像素做 source-over(缩略图不做排序,够看即可)
|
||||
const q = index * 3;
|
||||
r = clamp(Math.round(r * a + pixels[q] * (1 - a)), 0, 255);
|
||||
g = clamp(Math.round(g * a + pixels[q + 1] * (1 - a)), 0, 255);
|
||||
b = clamp(Math.round(b * a + pixels[q + 2] * (1 - a)), 0, 255);
|
||||
}
|
||||
}
|
||||
depth[index] = d;
|
||||
const p = index * 3;
|
||||
pixels[p] = r;
|
||||
@@ -1045,6 +1228,133 @@ function buildViewProjection(geometry: SceneGeometry, size: number, yawDeg: numb
|
||||
return mat4Multiply(proj, view);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PNG 解码(缩略图要贴图才不是"白模";只做 8 位非隔行,够用且零原生依赖)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
/**
|
||||
* 极简 PNG 解码器:zlib 解压 + 逐行反滤波,输出 RGBA。
|
||||
* 不支持 16 位 / 隔行扫描 / 未知 colorType —— 返回 null 由调用方回退纯色。
|
||||
*/
|
||||
function decodePng(buffer: Buffer): DecodedImage | null {
|
||||
if (buffer.length < 8 + 25 || !buffer.subarray(0, 8).equals(PNG_SIGNATURE)) return null;
|
||||
let offset = 8;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let bitDepth = 0;
|
||||
let colorType = 0;
|
||||
let interlace = 0;
|
||||
let palette: Uint8Array | null = null;
|
||||
let transparency: Uint8Array | null = null;
|
||||
const idat: Buffer[] = [];
|
||||
|
||||
while (offset + 8 <= buffer.length) {
|
||||
const length = buffer.readUInt32BE(offset);
|
||||
const type = buffer.toString('ascii', offset + 4, offset + 8);
|
||||
const dataStart = offset + 8;
|
||||
if (dataStart + length + 4 > buffer.length) return null;
|
||||
const data = buffer.subarray(dataStart, dataStart + length);
|
||||
if (type === 'IHDR') {
|
||||
if (length < 13) return null;
|
||||
width = data.readUInt32BE(0);
|
||||
height = data.readUInt32BE(4);
|
||||
bitDepth = data[8];
|
||||
colorType = data[9];
|
||||
interlace = data[12];
|
||||
} else if (type === 'PLTE') {
|
||||
palette = new Uint8Array(data);
|
||||
} else if (type === 'tRNS') {
|
||||
transparency = new Uint8Array(data);
|
||||
} else if (type === 'IDAT') {
|
||||
idat.push(Buffer.from(data));
|
||||
} else if (type === 'IEND') {
|
||||
break;
|
||||
}
|
||||
offset = dataStart + length + 4;
|
||||
}
|
||||
|
||||
if (bitDepth !== 8 || interlace !== 0) return null;
|
||||
if (!(width > 0) || !(height > 0) || width * height > 64 * 1024 * 1024) return null;
|
||||
if (idat.length === 0) return null;
|
||||
|
||||
const channels =
|
||||
colorType === 0 ? 1 : colorType === 2 ? 3 : colorType === 3 ? 1 : colorType === 4 ? 2 : colorType === 6 ? 4 : 0;
|
||||
if (channels === 0) return null;
|
||||
if (colorType === 3 && !palette) return null;
|
||||
|
||||
let raw: Buffer;
|
||||
try {
|
||||
raw = inflateSync(Buffer.concat(idat));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const stride = width * channels;
|
||||
if (raw.length < (stride + 1) * height) return null;
|
||||
|
||||
const out = new Uint8Array(width * height * 4);
|
||||
const line = new Uint8Array(stride);
|
||||
const prev = new Uint8Array(stride);
|
||||
let rawPos = 0;
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
const filter = raw[rawPos];
|
||||
rawPos += 1;
|
||||
for (let i = 0; i < stride; i += 1) {
|
||||
const value = raw[rawPos + i];
|
||||
const left = i >= channels ? line[i - channels] : 0;
|
||||
const up = prev[i];
|
||||
const upLeft = i >= channels ? prev[i - channels] : 0;
|
||||
let restored: number;
|
||||
switch (filter) {
|
||||
case 0: restored = value; break;
|
||||
case 1: restored = value + left; break;
|
||||
case 2: restored = value + up; break;
|
||||
case 3: restored = value + ((left + up) >> 1); break;
|
||||
case 4: {
|
||||
const p = left + up - upLeft;
|
||||
const pa = Math.abs(p - left);
|
||||
const pb = Math.abs(p - up);
|
||||
const pc = Math.abs(p - upLeft);
|
||||
restored = value + (pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft);
|
||||
break;
|
||||
}
|
||||
default: return null;
|
||||
}
|
||||
line[i] = restored & 0xff;
|
||||
}
|
||||
rawPos += stride;
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const o = (y * width + x) * 4;
|
||||
if (colorType === 6) {
|
||||
out[o] = line[x * 4];
|
||||
out[o + 1] = line[x * 4 + 1];
|
||||
out[o + 2] = line[x * 4 + 2];
|
||||
out[o + 3] = line[x * 4 + 3];
|
||||
} else if (colorType === 2) {
|
||||
out[o] = line[x * 3];
|
||||
out[o + 1] = line[x * 3 + 1];
|
||||
out[o + 2] = line[x * 3 + 2];
|
||||
out[o + 3] = 255;
|
||||
} else if (colorType === 0) {
|
||||
const g = line[x];
|
||||
out[o] = g; out[o + 1] = g; out[o + 2] = g; out[o + 3] = 255;
|
||||
} else if (colorType === 4) {
|
||||
const g = line[x * 2];
|
||||
out[o] = g; out[o + 1] = g; out[o + 2] = g; out[o + 3] = line[x * 2 + 1];
|
||||
} else {
|
||||
const index = line[x];
|
||||
out[o] = palette![index * 3] ?? 0;
|
||||
out[o + 1] = palette![index * 3 + 1] ?? 0;
|
||||
out[o + 2] = palette![index * 3 + 2] ?? 0;
|
||||
out[o + 3] = transparency && index < transparency.length ? transparency[index] : 255;
|
||||
}
|
||||
}
|
||||
prev.set(line);
|
||||
}
|
||||
return { width, height, rgba: out };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PNG 编码(8 位 RGB、无隔行、filter=0;不引第三方库)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1133,6 +1443,8 @@ export async function renderModelThumbnail(
|
||||
) {
|
||||
throw new Error('缩略图背景色非法:需要 [r, g, b] 三个有限数字');
|
||||
}
|
||||
// 默认看**正面**:eye = 中心 + (sin yaw, .., cos yaw)*d,yaw=0 时相机在 +Z;
|
||||
// MMD(PMX)与 VRM 1.0 都是 +Z 朝前,因此 -30 是"正面偏 30 度"的常规 3/4 视角
|
||||
const yawDeg = options?.yawDeg ?? -30;
|
||||
const rawPitchDeg = options?.pitchDeg ?? 12;
|
||||
if (!Number.isFinite(yawDeg) || !Number.isFinite(rawPitchDeg)) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
convertModelFile,
|
||||
importModelFile,
|
||||
} from './model-convert';
|
||||
import { ModelStats, inspectModelFile } from './model-inspector';
|
||||
import { ModelStats, inspectModelFile, shrinkStatsForStorage } from './model-inspector';
|
||||
import { renderModelThumbnail } from './model-thumbnail';
|
||||
import { CharacterModel } from '../entities/model.entity';
|
||||
import { AppConfig } from '../config/configuration';
|
||||
@@ -38,6 +38,21 @@ import { QueryModelDto, UpdateModelDto } from './model.dto';
|
||||
import { ModelDto, toModelDto } from './model.serializer';
|
||||
import { inspectVrm } from './vrm-inspector';
|
||||
|
||||
/** 判断是否为「数据超长」类数据库错误(MySQL 1406 / MariaDB ER_DATA_TOO_LONG) */
|
||||
function isDataTooLongError(error: unknown): boolean {
|
||||
const err = error as {
|
||||
code?: string;
|
||||
errno?: number;
|
||||
driverError?: { code?: string; errno?: number };
|
||||
message?: string;
|
||||
};
|
||||
const code = err.driverError?.code ?? err.code;
|
||||
const errno = err.driverError?.errno ?? err.errno;
|
||||
if (errno === 1406) return true;
|
||||
if (typeof code === 'string' && /DATA_TOO_LONG/i.test(code)) return true;
|
||||
return typeof err.message === 'string' && /Data too long/i.test(err.message);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ModelsService {
|
||||
private readonly logger = new Logger(ModelsService.name);
|
||||
@@ -118,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 },
|
||||
};
|
||||
|
||||
@@ -202,7 +218,7 @@ export class ModelsService {
|
||||
// 上传一律待审核:模型必须过审核才可能被客户端消费
|
||||
status: PublishStatus.Pending,
|
||||
});
|
||||
const saved = await this.models.save(model);
|
||||
const saved = await this.saveWithStatsFallback(model);
|
||||
this.logger.log(
|
||||
`模型已入库待审:#${saved.id} ${name}(${imported.format},${imported.direct ? '直接导入' : '转换'})` +
|
||||
` 面数=${stats.triangles} 骨骼=${stats.bones} humanoid=${stats.humanoidMapped}/${stats.humanoidTotal}` +
|
||||
@@ -241,7 +257,7 @@ export class ModelsService {
|
||||
if (thumbnailAssetId !== null) model.thumbnailAssetId = thumbnailAssetId;
|
||||
if (stats.vrmVersion) model.vrmVersion = stats.vrmVersion;
|
||||
|
||||
const saved = await this.models.save(model);
|
||||
const saved = await this.saveWithStatsFallback(model);
|
||||
this.logger.log(
|
||||
`模型 #${id} 重新分析完成:面数=${stats.triangles} 骨骼=${stats.bones} ` +
|
||||
`humanoid=${stats.humanoidMapped}/${stats.humanoidTotal} 可驱动=${stats.drivable}` +
|
||||
@@ -251,6 +267,30 @@ export class ModelsService {
|
||||
return dto;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存模型;若因 `stats` 超长被数据库拒绝,裁剪后重试一次。
|
||||
*
|
||||
* 骨骼树上千根的大模型并不罕见:TEXT(64KB) 时代实测 643 骨骼的 PMX 就会
|
||||
* 触发 1406 报错,而这一步抛出去就是 500。列已迁到 MEDIUMTEXT,
|
||||
* 这里再兜一层,保证「分析结果太大」永远不会让上传失败。
|
||||
*/
|
||||
private async saveWithStatsFallback(model: CharacterModel): Promise<CharacterModel> {
|
||||
try {
|
||||
return await this.models.save(model);
|
||||
} catch (error) {
|
||||
if (!isDataTooLongError(error)) throw error;
|
||||
const original = model.stats as unknown as ModelStats | null;
|
||||
if (!original) throw error;
|
||||
const shrunk = shrinkStatsForStorage(original);
|
||||
this.logger.warn(
|
||||
`模型「${model.name}」分析结果超出数据库字段上限(${JSON.stringify(original).length} 字节),` +
|
||||
`已裁剪骨骼树至 ${shrunk.boneTree.length} 条后重试`,
|
||||
);
|
||||
model.stats = shrunk as unknown as Record<string, unknown>;
|
||||
return await this.models.save(model);
|
||||
}
|
||||
}
|
||||
|
||||
/** 分析模型;任何异常都降级为一条 warning,不阻断上传 */
|
||||
private async analyzeSafely(
|
||||
absolutePath: string,
|
||||
@@ -411,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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 规范骨。
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,11 @@ interface FakeEntry {
|
||||
encrypted?: boolean;
|
||||
/** 未知压缩方式 */
|
||||
badMethod?: number;
|
||||
/**
|
||||
* 直接指定文件名的原始字节,且**不置 UTF-8 标志位**(模拟 GBK / Shift-JIS 压缩包)。
|
||||
* 中文 MMD 压缩包很常见:有的条目是 UTF-8、有的是 GBK,且都没打标志位。
|
||||
*/
|
||||
rawName?: Buffer;
|
||||
}
|
||||
|
||||
/** 手写一个 ZIP(测试用;不依赖任何第三方库) */
|
||||
@@ -31,7 +36,9 @@ function buildZip(entries: FakeEntry[]): Buffer {
|
||||
let offset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const name = Buffer.from(entry.path, 'utf8');
|
||||
const name = entry.rawName ?? Buffer.from(entry.path, 'utf8');
|
||||
// 给了 rawName 就当作「未声明 UTF-8」的老压缩包
|
||||
const nameFlags = entry.rawName ? (entry.encrypted ? 0x0001 : 0) : (entry.encrypted ? 0x0001 : 0) | 0x0800;
|
||||
const method = entry.badMethod ?? entry.method ?? 8;
|
||||
const raw = entry.content;
|
||||
const data = method === 8 ? deflateRawSync(raw) : raw;
|
||||
@@ -40,7 +47,7 @@ function buildZip(entries: FakeEntry[]): Buffer {
|
||||
const local = Buffer.alloc(30 + name.length);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE((entry.encrypted ? 0x0001 : 0) | 0x0800, 6);
|
||||
local.writeUInt16LE(nameFlags, 6);
|
||||
local.writeUInt16LE(method, 8);
|
||||
local.writeUInt32LE(checksum, 14);
|
||||
local.writeUInt32LE(data.length, 18);
|
||||
@@ -53,7 +60,7 @@ function buildZip(entries: FakeEntry[]): Buffer {
|
||||
central.writeUInt32LE(0x02014b50, 0);
|
||||
central.writeUInt16LE(20, 4);
|
||||
central.writeUInt16LE(20, 6);
|
||||
central.writeUInt16LE((entry.encrypted ? 0x0001 : 0) | 0x0800, 8);
|
||||
central.writeUInt16LE(nameFlags, 8);
|
||||
central.writeUInt16LE(method, 10);
|
||||
central.writeUInt32LE(checksum, 16);
|
||||
central.writeUInt32LE(data.length, 20);
|
||||
@@ -220,6 +227,35 @@ describe('ZIP 读取器', () => {
|
||||
expect(findZipEntry(entries, 'HATSUNE MIKU.PMX')?.path).toBe('Hatsune Miku.pmx');
|
||||
});
|
||||
|
||||
it('GBK 压缩包:Shift-JIS 解出私用区乱码时回退 GBK(发/髮 这类字不再丢字符)', () => {
|
||||
// b'tex/\xf3\x8c.png' 是 GBK 的「tex/髮.png」;Shift-JIS 会把它解成一个
|
||||
// 私用区不可见字符(不是 U+FFFD),旧实现会直接采信,导致贴图名对不上而丢图。
|
||||
const zip = buildZip([
|
||||
{ path: 'raw', content: Buffer.from('PMX '.repeat(50)), rawName: Buffer.from([0x74, 0x65, 0x78, 0x2f, 0xf3, 0x8c, 0x2e, 0x70, 0x6e, 0x67]) },
|
||||
]);
|
||||
const entries = readZipEntries(zip);
|
||||
expect(entries.map((e) => e.path)).toEqual(['tex/髮.png']);
|
||||
});
|
||||
|
||||
it('Shift-JIS 名字仍然优先按 Shift-JIS 解(日文 MMD 压缩包)', () => {
|
||||
// b'\x83\x41\x83\x43.pmx' 是 Shift-JIS 的「アイ.pmx」(半角片假名判断的姊妹用例)
|
||||
const zip = buildZip([
|
||||
{ path: 'raw', content: Buffer.from('PMX '.repeat(50)), rawName: Buffer.from([0x83, 0x41, 0x83, 0x43, 0x2e, 0x70, 0x6d, 0x78]) },
|
||||
]);
|
||||
const entries = readZipEntries(zip);
|
||||
expect(entries[0].path).toBe('アイ.pmx');
|
||||
});
|
||||
|
||||
it('目录条目不会当成文件(避免解压时把目录当文件写)', () => {
|
||||
const zip = buildZip([
|
||||
{ path: 'spa/', content: Buffer.alloc(0), method: 0 },
|
||||
{ path: 'spa/a.png', content: Buffer.from('PNG') },
|
||||
{ path: '奥黛塔.pmx', content: Buffer.from('PMX '.repeat(50)) },
|
||||
]);
|
||||
const entries = readZipEntries(zip);
|
||||
expect(entries.map((e) => e.path)).toEqual(['spa/a.png', '奥黛塔.pmx']);
|
||||
});
|
||||
|
||||
it('拒绝上跳路径(zip-slip)', () => {
|
||||
const zip = buildZip([{ path: '../../etc/passwd', content: Buffer.from('x') }]);
|
||||
expect(() => readZipEntries(zip)).toThrow(/上跳路径/);
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { getMetadataArgsStorage } from 'typeorm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { CharacterModel } from '../src/entities/model.entity';
|
||||
import {
|
||||
MYSQL_TEXT_LIMIT,
|
||||
type BoneNode,
|
||||
type ModelStats,
|
||||
shrinkStatsForStorage,
|
||||
} from '../src/models/model-inspector';
|
||||
|
||||
/**
|
||||
* 骨骼树超出数据库字段上限导致的 500。
|
||||
*
|
||||
* 起因(真实故障):上传含 PMX 的压缩包(【奥黛塔】_by_原神.zip,643 根骨骼)
|
||||
* 返回 500。转换本身成功,但分析结果里骨骼树按骨骼逐条展开,JSON 实测
|
||||
* **70,980 字节** > `models.stats` 的 TEXT 上限 65,535,MySQL / MariaDB 严格模式
|
||||
* 直接拒绝写入(ER_DATA_TOO_LONG / 1406),而写入没有兜底。
|
||||
*
|
||||
* 这里锁三件事:
|
||||
* 1. 列必须是 MEDIUMTEXT(实体 + 迁移一致);
|
||||
* 2. 服务层对「数据超长」有裁剪重试兜底;
|
||||
* 3. 裁剪函数本身永不抛、且保留审核必需的汇总字段。
|
||||
*/
|
||||
|
||||
/** 造一个规模接近真实的骨骼树(【奥黛塔】实测 643 根、每根约 110 字节) */
|
||||
function buildBoneTree(count: number): BoneNode[] {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
index,
|
||||
name: `Bone_${String(index).padStart(4, '0')}_髪_腕捩_ねじ`,
|
||||
depth: Math.min(index % 40, 35),
|
||||
parentName: index === 0 ? null : `Bone_${String(Math.max(0, index - 1)).padStart(4, '0')}_髪_腕捩_ねじ`,
|
||||
childCount: index % 3,
|
||||
inSkin: index % 7 !== 0,
|
||||
humanoid: index < 7 ? ['hips', 'spine', 'chest', 'neck', 'head', 'leftShoulder', 'leftUpperArm'][index] : null,
|
||||
}));
|
||||
}
|
||||
|
||||
function buildStats(bones: number): ModelStats {
|
||||
return {
|
||||
container: 'glb',
|
||||
vrmVersion: null,
|
||||
fileSize: 23_700_000,
|
||||
meshes: 12,
|
||||
primitives: 18,
|
||||
vertices: 120_000,
|
||||
triangles: 93_350,
|
||||
materials: 9,
|
||||
textures: 17,
|
||||
images: 17,
|
||||
animations: 0,
|
||||
morphTargets: 24,
|
||||
nodes: 700,
|
||||
bones,
|
||||
skins: 1,
|
||||
humanoidMapped: 0,
|
||||
humanoidTotal: 22,
|
||||
missingRequiredBones: ['hips', 'spine', 'chest', 'neck', 'head', 'leftUpperArm'],
|
||||
drivable: false,
|
||||
maxBoneDepth: 35,
|
||||
boneTree: buildBoneTree(bones),
|
||||
warnings: [],
|
||||
};
|
||||
}
|
||||
|
||||
function findMigrationsDir(): string {
|
||||
const candidates = [
|
||||
resolve(process.cwd(), 'src', 'migrations'),
|
||||
resolve(process.cwd(), '..', 'src', 'migrations'),
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
const files = readdirSync(candidate).filter((f) => f.endsWith('.ts'));
|
||||
if (files.length > 0) return candidate;
|
||||
}
|
||||
throw new Error('找不到 src/migrations');
|
||||
}
|
||||
|
||||
describe('models.stats 字段容量', () => {
|
||||
it('643 根骨骼的分析结果确实超过 TEXT 上限(这就是 500 的原因)', () => {
|
||||
const json = JSON.stringify(buildStats(643));
|
||||
expect(json.length).toBeGreaterThan(MYSQL_TEXT_LIMIT);
|
||||
// 与真实故障量级一致(实测 70,980 字节)
|
||||
expect(json.length).toBeGreaterThan(65_000);
|
||||
expect(json.length).toBeLessThan(120_000);
|
||||
});
|
||||
|
||||
it('实体列型是 mediumtext,且能 JSON 往返(不再被 simple-json 钉死在 text)', () => {
|
||||
const column = getMetadataArgsStorage().columns.find(
|
||||
(item) => item.target === CharacterModel && item.propertyName === 'stats',
|
||||
);
|
||||
expect(column?.options.type).toBe('mediumtext');
|
||||
const transformer = column?.options.transformer as
|
||||
| { to?: (v: unknown) => unknown; from?: (v: unknown) => unknown }
|
||||
| undefined;
|
||||
expect(typeof transformer?.to).toBe('function');
|
||||
expect(typeof transformer?.from).toBe('function');
|
||||
const stats = buildStats(643);
|
||||
const stored = transformer!.to!(stats) as string;
|
||||
expect(typeof stored).toBe('string');
|
||||
expect(JSON.parse(stored).bones).toBe(643);
|
||||
expect((transformer!.from!(stored) as ModelStats).bones).toBe(643);
|
||||
// 脏数据不能让接口 500
|
||||
expect(transformer!.from!('{ 坏 JSON')).toEqual({ parseError: true, raw: '{ 坏 JSON' });
|
||||
});
|
||||
|
||||
it('存在把 stats 扩到 MEDIUMTEXT 的迁移(install.sh 会自动执行)', () => {
|
||||
const dir = findMigrationsDir();
|
||||
const file = readdirSync(dir).find((f) => /AddModelStatsMediumText.*\.ts$/.test(f));
|
||||
expect(file, '缺少 AddModelStatsMediumText 迁移').toBeTruthy();
|
||||
const sql = readFileSync(join(dir, file as string), 'utf8');
|
||||
// TS 源码里反引号是转义的,这里只断言关键字与方向
|
||||
expect(sql).toMatch(/MODIFY/i);
|
||||
expect(sql).toMatch(/mediumtext/i);
|
||||
expect(sql).toMatch(/ALTER TABLE/i);
|
||||
expect(sql).toMatch(/implements MigrationInterface/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shrinkStatsForStorage:写入前的兜底裁剪', () => {
|
||||
it('没超限时原样返回(不做无谓修改)', () => {
|
||||
const stats = buildStats(20);
|
||||
expect(shrinkStatsForStorage(stats)).toBe(stats);
|
||||
});
|
||||
|
||||
it('超限时裁剪骨骼树到能放下,并追加一条说明用的 warning', () => {
|
||||
const stats = buildStats(643);
|
||||
const shrunk = shrinkStatsForStorage(stats);
|
||||
expect(JSON.stringify(shrunk).length).toBeLessThanOrEqual(MYSQL_TEXT_LIMIT);
|
||||
expect(shrunk.boneTree.length).toBeLessThan(stats.boneTree.length);
|
||||
// 审核必需的汇总字段一个都不能少
|
||||
expect(shrunk.triangles).toBe(93_350);
|
||||
expect(shrunk.bones).toBe(643);
|
||||
expect(shrunk.humanoidMapped).toBe(0);
|
||||
expect(shrunk.humanoidTotal).toBe(22);
|
||||
expect(shrunk.drivable).toBe(false);
|
||||
expect(shrunk.missingRequiredBones).toEqual(stats.missingRequiredBones);
|
||||
expect(shrunk.warnings.join()).toContain('已截断');
|
||||
});
|
||||
|
||||
it('保留的骨骼仍是父在前的祖先链(审核界面按 depth 缩进不会错乱)', () => {
|
||||
const stats = buildStats(643);
|
||||
const shrunk = shrinkStatsForStorage(stats);
|
||||
const kept = shrunk.boneTree;
|
||||
expect(kept.length).toBeGreaterThan(0);
|
||||
for (let i = 1; i < kept.length; i += 1) {
|
||||
expect(kept[i].depth).toBeLessThanOrEqual(kept[i - 1].depth + 1);
|
||||
}
|
||||
});
|
||||
|
||||
it('极端情况(连最小骨骼树都放不下)也不会抛,仍返回可存储的结果', () => {
|
||||
const stats = buildStats(400);
|
||||
const shrunk = shrinkStatsForStorage(stats, 512);
|
||||
expect(JSON.stringify(shrunk).length).toBeLessThanOrEqual(1024);
|
||||
expect(shrunk.triangles).toBe(93_350);
|
||||
});
|
||||
});
|
||||
|
||||
describe('服务层兜底:数据超长时裁剪重试而不是 500', () => {
|
||||
const source = readFileSync(
|
||||
[
|
||||
resolve(process.cwd(), 'src', 'models', 'models.service.ts'),
|
||||
resolve(process.cwd(), '..', 'src', 'models', 'models.service.ts'),
|
||||
].find((p) => {
|
||||
try {
|
||||
readFileSync(p);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}) as string,
|
||||
'utf8',
|
||||
);
|
||||
|
||||
it('create 与 reanalyze 都走 saveWithStatsFallback', () => {
|
||||
const calls = source.match(/saveWithStatsFallback\(model\)/g) ?? [];
|
||||
expect(calls.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('兜底只用 1406 / DATA_TOO_LONG 触发,其它数据库错误照旧抛出', () => {
|
||||
expect(source).toContain('isDataTooLongError');
|
||||
expect(source).toMatch(/errno === 1406/);
|
||||
expect(source).toMatch(/DATA_TOO_LONG/);
|
||||
expect(source).toContain('if (!isDataTooLongError(error)) throw error;');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { inflateSync } from 'node:zlib';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { renderModelThumbnail } from '../src/models/model-thumbnail';
|
||||
|
||||
/**
|
||||
* 缩略图**贴图采样**测试。
|
||||
*
|
||||
* 背景(真实故障):缩略图渲染器原先刻意不解码 baseColorTexture,只用
|
||||
* `baseColorFactor` 上色;而 MMD(PMX 转换)模型的 baseColorFactor 基本全是白色,
|
||||
* 于是缩略图全是"白模"——列表页与审核面板看到的都是白色模型,用户报的正是这个。
|
||||
* 现在渲染器内置 PNG 解码并逐像素采样贴图,这里锁住行为。
|
||||
*/
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), 'opendance-thumb-tex-'));
|
||||
|
||||
function write(name: string, content: Buffer): string {
|
||||
const path = join(dir, name);
|
||||
writeFileSync(path, content);
|
||||
return path;
|
||||
}
|
||||
|
||||
/** 12 字节头 + JSON chunk + BIN chunk */
|
||||
function buildGlb(json: unknown, bin: Buffer): Buffer {
|
||||
const jsonRaw = Buffer.from(JSON.stringify(json), 'utf8');
|
||||
const jsonChunk = Buffer.concat([jsonRaw, Buffer.alloc((4 - (jsonRaw.length % 4)) % 4, 0x20)]);
|
||||
const binChunk = Buffer.concat([bin, Buffer.alloc((4 - (bin.length % 4)) % 4)]);
|
||||
const chunks: Buffer[] = [];
|
||||
const header = Buffer.alloc(12);
|
||||
header.write('glTF', 0, 'ascii');
|
||||
header.writeUInt32LE(2, 4);
|
||||
chunks.push(header);
|
||||
const jsonHeader = Buffer.alloc(8);
|
||||
jsonHeader.writeUInt32LE(jsonChunk.length, 0);
|
||||
jsonHeader.writeUInt32LE(0x4e4f534a, 4);
|
||||
chunks.push(jsonHeader, jsonChunk);
|
||||
const binHeader = Buffer.alloc(8);
|
||||
binHeader.writeUInt32LE(binChunk.length, 0);
|
||||
binHeader.writeUInt32LE(0x004e4942, 4);
|
||||
chunks.push(binHeader, binChunk);
|
||||
const out = Buffer.concat(chunks);
|
||||
out.writeUInt32LE(out.length, 8);
|
||||
return out;
|
||||
}
|
||||
|
||||
function float32Buffer(values: number[]): Buffer {
|
||||
const buffer = Buffer.alloc(values.length * 4);
|
||||
values.forEach((value, index) => buffer.writeFloatLE(value, index * 4));
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function uint16Buffer(values: number[]): Buffer {
|
||||
const buffer = Buffer.alloc(values.length * 2);
|
||||
values.forEach((value, index) => buffer.writeUInt16LE(value, index * 2));
|
||||
return buffer;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 贴图夹具 */
|
||||
|
||||
/** 2x2 纯红(colorType 6,带 alpha=255) */
|
||||
const RED_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAEUlEQVR4nGP4z8DwH4QZYAwAR8oH+WdZbrcAAAAASUVORK5CYII=',
|
||||
'base64',
|
||||
);
|
||||
/** 2x2 纯绿(colorType 2,无 alpha) */
|
||||
const GREEN_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAD0lEQVR4nGNg+M8AQhAKABvyA/1tVLjHAAAAAElFTkSuQmCC',
|
||||
'base64',
|
||||
);
|
||||
/** 2x2 全透明(RGBA 的 alpha=0) */
|
||||
const TRANSPARENT_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAEUlEQVR4nGP4z8DAAMIMMAYAKegD/QE6Y34AAAAASUVORK5CYII=',
|
||||
'base64',
|
||||
);
|
||||
|
||||
interface QuadOptions {
|
||||
texture?: Buffer;
|
||||
mimeType?: string;
|
||||
baseColorFactor?: number[];
|
||||
alphaMode?: string;
|
||||
}
|
||||
|
||||
/** 一个正对相机(+Z)的方形面片,UV 铺满贴图;baseColorFactor 默认纯白(MMD 的常见情况) */
|
||||
function texturedQuadGlb(options: QuadOptions = {}): Buffer {
|
||||
const positions = [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0];
|
||||
const uvs = [0, 1, 1, 1, 1, 0, 0, 0];
|
||||
const indices = [0, 1, 2, 0, 2, 3];
|
||||
const posBin = float32Buffer(positions);
|
||||
const uvBin = float32Buffer(uvs);
|
||||
const idxBin = uint16Buffer(indices);
|
||||
const image = options.texture ?? RED_PNG;
|
||||
const bin = Buffer.concat([posBin, uvBin, idxBin, image]);
|
||||
const imageOffset = posBin.length + uvBin.length + idxBin.length;
|
||||
|
||||
const json = {
|
||||
asset: { version: '2.0' },
|
||||
scene: 0,
|
||||
scenes: [{ nodes: [0] }],
|
||||
nodes: [{ mesh: 0 }],
|
||||
meshes: [{ primitives: [{ attributes: { POSITION: 0, TEXCOORD_0: 1 }, indices: 2, material: 0 }] }],
|
||||
materials: [
|
||||
{
|
||||
pbrMetallicRoughness: {
|
||||
baseColorFactor: options.baseColorFactor ?? [1, 1, 1, 1],
|
||||
baseColorTexture: { index: 0 },
|
||||
},
|
||||
...(options.alphaMode ? { alphaMode: options.alphaMode, alphaCutoff: 0.5 } : {}),
|
||||
},
|
||||
],
|
||||
textures: [{ source: 0 }],
|
||||
images: [{ bufferView: 3, mimeType: options.mimeType ?? 'image/png' }],
|
||||
accessors: [
|
||||
{ bufferView: 0, componentType: 5126, count: 4, type: 'VEC3' },
|
||||
{ bufferView: 1, componentType: 5126, count: 4, type: 'VEC2' },
|
||||
{ bufferView: 2, componentType: 5123, count: 6, type: 'SCALAR' },
|
||||
],
|
||||
bufferViews: [
|
||||
{ buffer: 0, byteOffset: 0, byteLength: posBin.length },
|
||||
{ buffer: 0, byteOffset: posBin.length, byteLength: uvBin.length },
|
||||
{ buffer: 0, byteOffset: posBin.length + uvBin.length, byteLength: idxBin.length },
|
||||
{ buffer: 0, byteOffset: imageOffset, byteLength: image.length },
|
||||
],
|
||||
buffers: [{ byteLength: bin.length }],
|
||||
};
|
||||
return buildGlb(json, bin);
|
||||
}
|
||||
|
||||
/** 解 PNG(我们自己写的编码器:8 位 RGB、filter=0),返回平均 RGB */
|
||||
function averageColor(png: Buffer): { r: number; g: number; b: number; nonBackground: number } {
|
||||
let offset = 8;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
const idat: Buffer[] = [];
|
||||
while (offset + 8 <= png.length) {
|
||||
const length = png.readUInt32BE(offset);
|
||||
const type = png.toString('ascii', offset + 4, offset + 8);
|
||||
const data = png.subarray(offset + 8, offset + 8 + length);
|
||||
if (type === 'IHDR') {
|
||||
width = data.readUInt32BE(0);
|
||||
height = data.readUInt32BE(4);
|
||||
expect(data[8]).toBe(8);
|
||||
expect(data[9]).toBe(2);
|
||||
expect(data[12]).toBe(0);
|
||||
} else if (type === 'IDAT') {
|
||||
idat.push(Buffer.from(data));
|
||||
} else if (type === 'IEND') {
|
||||
break;
|
||||
}
|
||||
offset += 12 + length;
|
||||
}
|
||||
const raw = inflateSync(Buffer.concat(idat));
|
||||
let r = 0;
|
||||
let g = 0;
|
||||
let b = 0;
|
||||
let count = 0;
|
||||
let nonBackground = 0;
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
const rowStart = y * (1 + width * 3);
|
||||
expect(raw[rowStart]).toBe(0); // filter=0
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const i = rowStart + 1 + x * 3;
|
||||
r += raw[i];
|
||||
g += raw[i + 1];
|
||||
b += raw[i + 2];
|
||||
count += 1;
|
||||
// 默认背景是 [24,26,32](深色);明显偏离即视为主体像素
|
||||
if (Math.abs(raw[i] - 24) > 12 || Math.abs(raw[i + 1] - 26) > 12 || Math.abs(raw[i + 2] - 32) > 12) {
|
||||
nonBackground += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return { r: r / count, g: g / count, b: b / count, nonBackground };
|
||||
}
|
||||
|
||||
async function render(glb: Buffer, name: string, extra: Record<string, unknown> = {}) {
|
||||
const result = await renderModelThumbnail(write(name, glb), { size: 128, ...extra });
|
||||
expect(result).not.toBeNull();
|
||||
return averageColor((result as { png: Buffer }).png);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 测试 */
|
||||
|
||||
describe('缩略图贴图采样', () => {
|
||||
it('baseColorFactor 全白时也按贴图上色(回归:不再输出"白模")', async () => {
|
||||
const color = await render(texturedQuadGlb(), 'red.glb');
|
||||
expect(color.nonBackground).toBeGreaterThan(0);
|
||||
// 贴图是纯红:主体像素整体应明显偏红
|
||||
expect(color.r).toBeGreaterThan(color.g + 20);
|
||||
expect(color.r).toBeGreaterThan(color.b + 20);
|
||||
});
|
||||
|
||||
it('colorType 2(无 alpha 通道)的 PNG 也能解码', async () => {
|
||||
const color = await render(texturedQuadGlb({ texture: GREEN_PNG }), 'green.glb');
|
||||
expect(color.g).toBeGreaterThan(color.r + 20);
|
||||
expect(color.g).toBeGreaterThan(color.b + 20);
|
||||
});
|
||||
|
||||
it('OPAQUE:忽略贴图 alpha(MMD 语义,alpha=0 也照样画出来)', async () => {
|
||||
const color = await render(
|
||||
texturedQuadGlb({ texture: TRANSPARENT_PNG, baseColorFactor: [0.9, 0.1, 0.1, 1] }),
|
||||
'opaque.glb',
|
||||
);
|
||||
expect(color.nonBackground).toBeGreaterThan(0);
|
||||
expect(color.r).toBeGreaterThan(color.g + 20);
|
||||
});
|
||||
|
||||
it('MASK:alpha 低于阈值的主体像素被丢弃(只剩背景)', async () => {
|
||||
const color = await render(
|
||||
texturedQuadGlb({ texture: TRANSPARENT_PNG, baseColorFactor: [0.9, 0.1, 0.1, 1], alphaMode: 'MASK' }),
|
||||
'mask.glb',
|
||||
);
|
||||
expect(color.nonBackground).toBe(0);
|
||||
});
|
||||
|
||||
it('贴图解码失败时回退 baseColorFactor 纯色,且不抛错', async () => {
|
||||
const broken = Buffer.from('这不是 PNG 数据', 'utf8');
|
||||
const color = await render(
|
||||
texturedQuadGlb({ texture: broken, baseColorFactor: [0.1, 0.1, 0.9, 1] }),
|
||||
'broken.glb',
|
||||
);
|
||||
expect(color.nonBackground).toBeGreaterThan(0);
|
||||
expect(color.b).toBeGreaterThan(color.r + 20);
|
||||
});
|
||||
|
||||
it('默认视角是正面(相机在 +Z):+Z 面颜色明显主导', async () => {
|
||||
// 面片正对 +Z,默认视角下必须看得见(若默认看背面,主体像素会接近 0)
|
||||
const color = await render(texturedQuadGlb(), 'front.glb');
|
||||
expect(color.nonBackground).toBeGreaterThan(128 * 128 * 0.05);
|
||||
});
|
||||
});
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user