7 Commits
Author SHA1 Message Date
opendance ae8a68e98f fix(thumbnail): 缩略图采样 baseColorTexture,修复 MMD 模型显示为白模
现象(用户反馈):导入 PMX 转换出的 GLB 后,列表页/审核面板里的模型是白模,
脸部颜色信息全部丢失。

定位过程(本地装真 Assimp 6.0.4 + 该模型完整复现):
1. 转换本身正常:23.7MB GLB、643 骨骼、93,350 面;
2. 18 张贴图逐字节与压缩包原图一致;用一个权威 PMX 解析器比对后确认
   39 个材质 -> 贴图的对应关系与 PMX 完全一致(不是映射错);
3. UV 采样也正确:脸部材质取到的就是皮肤色 (246,221,216);
4. 真正的问题在**我们自己的缩略图渲染器**:它刻意不解码 baseColorTexture,
   只用 baseColorFactor 上色(见文件头取舍说明);而 MMD 模型的
   baseColorFactor 基本都是白色 -> 缩略图必然全白。管理端 3D 预览有贴图,
   只有列表/审核的缩略图是白的。

修复:
1. model-thumbnail.ts 内置极简 PNG 解码器(zlib inflate + 逐行反滤波,
   8 位非隔行,colorType 0/2/3/4/6),按 baseColorFactor x 贴图逐像素采样,
   透视校正 UV;解码失败/非 PNG/隔行扫描回退纯色,绝不抛错;
2. 按 alphaMode 处理透明度:OPAQUE 忽略贴图 alpha(MMD 语义)、
   MASK 按 alphaCutoff 丢弃、BLEND 做 source-over;
3. 取景收紧 FRAMING 1.6 -> 1.3,40px 列表缩略图主体更清楚;
4. 新增 test/model-thumbnail-texture.spec.ts 6 项(含白模回归:
   baseColorFactor 全白 + 红贴图必须输出偏红,以及 MASK/OPAQUE/坏图回退);
5. 版本 0.2.4,README(.md/.txt)/DSH.md 补修订说明与 FAQ(含重新生成缩略图
   的 reanalyze-models.mjs --force 命令)。
2026-09-16 04:02:35 +08:00
opendance 8e8cc0475b fix(models): 修复上传 PMX 返回 500(models.stats 超 TEXT 上限)与 GBK 丢贴图
现象(真实故障):导入示例文件/【奥黛塔】_by_原神.zip 返回 500 Internal server error。

根因一(500):
  该 PMX 643 根骨骼、93,350 面,转换本身成功(GLB 23.7MB),但分析结果里的
  骨骼树按骨骼逐条展开,JSON 实测 70,980 字节,而 models.stats 是 TEXT
  (上限 65,535)。MySQL/MariaDB 严格模式直接拒绝写入(ER_DATA_TOO_LONG /
  1406),而这一步没有兜底 -> 未捕获 -> 500。

根因二(丢贴图):
  tex/髮.png 的 GBK 字节是 F3 8C。文件名解码先试 Shift-JIS,而 WHATWG 的
  shift_jis 把未定义码位映射成私用区不可见字符(不是 U+FFFD),于是被判为
  「解码成功」,永不回退 GBK;贴图名对不上,该模型 18 张贴图只内嵌了 17 张。

修复:
1. models.stats -> MEDIUMTEXT(实体 mediumtext + transformer,保留 JSON 语义;
   不用 simple-json 以免元数据与库列型不一致),新增迁移
   AddModelStatsMediumText1789550000000;
2. 新增 shrinkStatsForStorage() 兜底:即使库未迁移,也只截断骨骼树
   (父在前,保留祖先链),面数/骨骼数/humanoid 覆盖/可驱动性/warnings 全部保留;
   服务层 saveWithStatsFallback() 仅在 1406/DATA_TOO_LONG 时裁剪重试一次,
   其它数据库错误照旧抛出;
3. 压缩包文件名解码把「私用区字符」也算作解错信号,回退 GBK;实测该模型
   贴图由 17/18 变为 18/18 全部内嵌;
4. 新增 12 项测试(test/model-stats-limit.spec.ts 9 项 + 压缩包编码/目录条目 3 项);
5. 版本 0.2.3,README(.md/.txt)/DSH.md 补修订说明、500 的 FAQ 与 stats 容量约束。
2026-09-16 03:30:12 +08:00
opendance afed67e175 fix(deploy): apt 安装 Assimp 不再写死 libassimp6
Debian 11 / Ubuntu 22.04 的库包是 libassimp5,Debian 12+ 才是 libassimp6;
写死库名会让 apt 报 'no installation candidate',自动安装直接失败。
改为只装 assimp-utils(它按发行版依赖对应的库版本)。
2026-09-16 02:56:50 +08:00
opendance da03777995 fix(models): Assimp 缺失时给出可操作报错,部署脚本自动安装
现象:服务器未安装 Assimp,上传 PMX 压缩包只得到
  GLB 直出:导出失败(ENOENT):spawn assimp ENOENT
  glTF 直出:导出失败(ENOENT):spawn assimp ENOENT
用户看不出缺什么、怎么装,也不知道只传 glb/vrm 其实不需要它。

修复:
1. 新增 src/common/assimp.ts:按 ASSIMP_BIN -> PATH -> /usr/bin、/usr/local/bin
   等常见目录定位可执行文件(只认文件,不认同名目录),转换前先预检;
   找不到就一次性给出各发行版安装命令、查过的路径与替代办法,
   不再打两条 ENOENT。动作预处理(FBX/glTF -> BVH)复用同一文案。
2. 新增 deploy/assimp-lib.sh:install.sh 按发行版自动安装
   (apt-get / dnf / yum / zypper / apk / pacman),装在非常规目录时把绝对
   路径写入 deploy/.env 的 ASSIMP_BIN;装不上只告警不中止,可用
   SKIP_ASSIMP_INSTALL=1 跳过。check-access.sh 自检增加 Assimp 一行。
3. /health 增加 assimp.path;管理端「概览 -> 服务健康」显示 Assimp 状态,
   不可用时给出安装提示。
4. 新增 test/assimp-locate.spec.ts 13 项;强化「assimp 不存在」用例断言安装命令。
   测试规模 12 文件 / 193 项。
5. 版本 0.2.2,README(.md/.txt)/DSH.md 同步(前置要求、FAQ、环境变量说明)。
2026-09-16 02:55:32 +08:00
opendance e9de740d66 chore(release): 打包脚本默认版本改为 0.2.1 2026-09-15 22:27:16 +08:00
opendance ea58520fc2 fix(deploy): .env 中带空格的值未加引号导致 install.sh 以 127 失败
现象:
  ./deploy/.env: line 53: Miku.pmx: command not found
  [install] 第 53 行执行失败(退出码 127)

根因:deploy/.env.example 的 MODEL_CONVERT_PMX=Hatsune Miku.pmx 值含空格
却没加引号,install.sh 用 `set -a; . deploy/.env` 载入时被切成
「赋值 + 命令」,Miku.pmx 被当成命令执行。

修复:
1. 模板改为 MODEL_CONVERT_PMX="Hatsune Miku.pmx"(占位符值同样加引号);
2. 新增 deploy/env-lib.sh:.env 语法预检,install.sh / ctl.sh 在 source
   之前检查,报错给出「哪一行 / 原文 / 改法」, 与反引号建议单引号;
3. install.sh 的 ERR trap 补上出错文件名(lineno 属于被 source 的 .env,
   只报行号无法定位);
4. 新增 test/env-file.spec.ts 12 项回归测试,锁住「模板可被 shell 原样载入」;
5. 版本升到 0.2.1,README(.md/.txt)/DSH.md 补 .env 写法约定、FAQ 与测试数量。
2026-09-15 22:26:58 +08:00
zijunchiang d6376ec5a5 更新 README.md 2026-09-15 22:17:49 +08:00
32 changed files with 1986 additions and 82 deletions
+20 -3
View File
@@ -101,7 +101,7 @@ opendance-web/
│ ├── admin/ # React 管理端
│ │ ├── src/components/ModelReviewPanel.tsx # 模型审核面板 + 骨骼详细界面
│ │ └── src/lib/bone-tree.ts # 骨骼树过滤(搜索保留祖先链)
│ ├── test/ # 单元测试 + 端到端冒烟(10 文件 / 168 项)
│ ├── test/ # 单元测试 + 端到端冒烟(14 文件 / 211 项)
│ │ # mmd-vmd 31 / model-archive 24 / model-inspector 25
│ │ # / model-thumbnail 8 / admin-bone-filter 8
│ │ # / preprocess 25 / init-env 16 / admin-port 16
@@ -111,6 +111,8 @@ opendance-web/
│ # / import-default-model.mjs(默认模型导入 / 补写源码)
├── 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 系统时的进程控制
@@ -333,12 +335,27 @@ 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` -> **10 个文件 / 168 项通过**
- 测试:`npx vitest run` -> **14 个文件 / 211 项通过**
(`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)与监听地址
## 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)。
两个脚本在 source 之前调用预检,输出「哪一行、原文、改法」;
模板中带空格的值统一写成 `MODEL_CONVERT_PMX="Hatsune Miku.pmx"`。
- `deploy/init-env.sh`:交互式逐项询问 `DB_HOST / DB_PORT / DB_USER / DB_PASS /
DB_NAME / PORT / ADMIN_PORT / HOST`,回车保留默认;口令 `read -rs` 不回显、
+58 -14
View File
@@ -10,7 +10,35 @@ OpenDance Studio **阶段一**: Web 管理服务端(NestJS + TypeORM + 现有 My
## 状态
**阶段一已完成**: T-WEB-001 -> T-WEB-010 全部落地,当前版本 **v0.2.0**(契约 `rest-api / data-models / model-formats 0.4.0`、`database 0.3.0`)。
**阶段一已完成**: T-WEB-001 -> T-WEB-010 全部落地,当前版本 **v0.2.4**(契约 `rest-api / data-models / model-formats 0.4.0`、`database 0.3.0`)。
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 修订:
1. **修复 Assimp 缺失时的报错与部署体验**:服务器没装 Assimp 时,上传 .pmx/.fbx(或含它们的压缩包)只得到两条 `导出失败(ENOENT): spawn assimp ENOENT`,看不出缺什么、怎么装;
2. 转换前先**定位 Assimp 可执行文件**(`src/common/assimp.ts`):按 `ASSIMP_BIN` -> PATH -> `/usr/bin`、`/usr/local/bin` 等常见目录查找,找不到就一次性给出各发行版安装命令、查过的路径与**替代办法**(只传 .glb/.vrm 不需要它),不再打两条 ENOENT;
3. `install.sh` 新增 **Assimp 检查与自动安装**(`deploy/assimp-lib.sh`):按发行版调用 apt-get / dnf / yum / zypper / apk / pacman;装在非常规目录时自动把绝对路径写进 `deploy/.env` 的 `ASSIMP_BIN`;装不上只告警不中止(可用 `SKIP_ASSIMP_INSTALL=1` 跳过);
4. `deploy/check-access.sh` 自检增加 Assimp 一行;管理端「概览 -> 服务健康」显示 Assimp 状态,不可用时给出提示;
5. 新增 13 项测试(`test/assimp-locate.spec.ts`),覆盖定位、错误文案、快速失败与部署脚本的安装逻辑。
v0.2.1 修订:
1. **修复部署失败**:`deploy/.env.example` 里 `MODEL_CONVERT_PMX=Hatsune Miku.pmx` 的值含空格却没加引号,`install.sh` 用 `set -a; . deploy/.env` 载入时把 `Miku.pmx` 当命令执行,报 `command not found`(退出码 127);模板改为带引号写法;
2. **新增 `.env` 语法预检**(`deploy/env-lib.sh`):`install.sh` 与 `ctl.sh` 在 source 之前先检查,直接给出哪一行、原文、改法,不再出现看不懂的 127 报错;
3. 安装失败提示带上出错文件名(`.env` 被 source 时行号属于 `.env`,只报行号无法定位);
4. 新增 12 项回归测试(`test/env-file.spec.ts`),锁住「模板可被 shell 原样载入」这条线。
v0.2.0 主要变更:
@@ -35,18 +63,18 @@ v0.2.0 主要变更:
2. 准备一个现有的 MySQL / MariaDB 实例,并建好库与账号(见下方[前置要求](#前置要求))
本项目**不会创建数据库本身**
3. 取得发布包并校验(地址用你们自己的制品库替换)
3. 取得发布包并校验(地址用你们自己的制品库替换; 下面是本仓库的发布地址)
```bash
curl -LO https://<制品库地址>/opendance-web-v0.2.0.tar.gz
curl -LO https://<制品库地址>/SHA256SUMS
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.2.4/opendance-web-v0.2.4.tar.gz
curl -LO https://gitea.kasugano.cn/zijunchiang/opendance-web/releases/download/v0.2.4/SHA256SUMS
sha256sum -c SHA256SUMS # 期望输出 "OK"
```
4. 解压并生成配置(交互式引导,逐项问答,口令不回显)
```bash
tar -xzf opendance-web-v0.2.0.tar.gz && cd opendance-web-v0.2.0
tar -xzf opendance-web-v0.2.4.tar.gz && cd opendance-web-v0.2.4
bash deploy/init-env.sh
```
@@ -96,6 +124,9 @@ Node 业务服务由系统服务托管,**同时监听两个端口**,职责分开
- Linux 服务器,有 **root** 权限(不需要 sudo,直接以 root 执行即可)
- **Node.js 22** 或更高版本
- 进程管理:`systemd` / `OpenRC` / `SysVinit` 均可;三者都没有也能装(自动降级为 `nohup` 后台进程 + PID 文件 + crontab `@reboot` 开机自启)
- Assimp 命令行工具(**可选但推荐**):`.pmx/.fbx` 模型转换与 FBX/glTF 动作预处理需要它;
`install.sh` 会自动尝试安装(apt-get / dnf / yum / zypper / apk / pacman),装不上只告警不中止。
只上传 `.glb/.vrm` 模型与 `.bvh/.vmd` 动作则完全不需要
- 反向代理:由另外的服务提供,本项目不要求、也不安装
- 一个可连通的现有 MySQL / MariaDB 实例,并已创建数据库与账号:
@@ -113,8 +144,8 @@ FLUSH PRIVILEGES;
### 5. 部署步骤
```bash
tar -xzf opendance-web-v0.2.0.tar.gz
cd opendance-web-v0.2.0
tar -xzf opendance-web-v0.2.4.tar.gz
cd opendance-web-v0.2.4
bash deploy/init-env.sh # 首次启动引导: 逐项问答生成 deploy/.env(见下)
bash deploy/install.sh # 已以 root 登录, 不需要 sudo
```
@@ -254,7 +285,10 @@ bash /opt/opendance/deploy/ctl.sh status | restart | logs
| 健康检查返回 503 | 服务起来了但连不上数据库:核对 `deploy/.env` 的 `DB_HOST/DB_PORT/DB_USER/DB_PASS/DB_NAME`,以及数据库账号是否允许从本机 IP 连接(`GRANT ... TO 'user'@'%'` 或具体主机) |
| 服务本机 curl 通、外部访问不了 | `bash deploy/check-access.sh` 一次定位:打印 `HOST`/`PORT`、实际监听地址、对外 IP 自测、80/443 有无反代、防火墙放行情况,并给出修复命令 |
| 管理页面打开是 404 | 说明访问的是软件 API 端口(默认 3000);管理页面在管理端端口(默认 3001) |
| 上传 `.zip` 模型包报 422 且提示 Assimp 不可用 | PMX/FBX 转换依赖 Assimp:`apt-get install -y assimp-utils libassimp6`;只上传 `.glb` / `.vrm` 则不需要它 |
| 上传 `.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` 则不需要它 |
| 列表/审核里的缩略图是"白模"(纯白模型) | 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` |
## 本地开发
@@ -283,10 +317,12 @@ npm run dev # http://localhost:5173(/api 与 /health 代理到 3000)
cd web-server
npm run contracts:check # 契约版本一致性
npm run typecheck # TypeScript 严格检查
npm run test # 168 项单元测试 / 10 个文件(VMD 31、模型压缩包 24、
npm run test # 211 项单元测试 / 14 个文件(VMD 31、模型压缩包 27、
# 模型检查器 25、缩略图 8、骨骼过滤 8、
# 预处理 25、init-env 16、admin-port 16、
# access-log 9、VRM 检查器 6)
# access-log 9、VRM 检查器 6、.env 预检 12、
# Assimp 定位与安装 13、stats 容量与编码 12、
# 缩略图贴图采样 6)
npm run build # 生产构建
npm run start:prod & # 启动
npm run test:smoke # 57 项端到端冒烟(需要数据库可连通)
@@ -308,15 +344,23 @@ cd ../admin && npm run build # 管理端构建
| `ADMIN_DIR` | `../admin`(即 `/opt/opendance/admin`) | 管理端静态站点目录 |
| `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 可执行文件。FBX/glTF 动作预处理需要;上传 `.zip` 模型包、或 `.pmx/.fbx` 单文件模型时必须能调用到,否则转换失败(422) |
| `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_PMX` | `Hatsune Miku.pmx` | 压缩包内优先选用的 PMX 文件名(大小写不敏感);找不到时按「格式优先级 -> 目录最浅 -> 文件最大」挑选 |
| `MODEL_CONVERT_PMX` | `"Hatsune Miku.pmx"` | 压缩包内优先选用的 PMX 文件名(大小写不敏感);找不到时按「格式优先级 -> 目录最浅 -> 文件最大」挑选 |
| `MODEL_CONVERT_TIMEOUT_MS` | `180000` | 单次转换超时(毫秒) |
| `DEFAULT_MODEL_ID` | - | 可选:显式指定默认模型 id;不设置时按源码种子 `src/config/default-model.ts` 匹配,再回落到 VRM 优先规则 |
| `CONTRACTS_DIR` | - | 可选:契约目录,设置后 `/health` 反映实时契约版本(原生部署默认指向 `/opt/opendance/contracts`) |
端口配置非法(非 1..65535 整数)时,生产环境启动会直接中止;`ADMIN_PORT` 设为与 `PORT` 相同只打印提示,不中止。
**`.env` 写法约定**:`install.sh` / `ctl.sh` 用 `set -a; . deploy/.env` 载入配置,shell 会**真的执行**这个文件,因此
- 普通值不加引号:`PORT=3000`、`DB_HOST=127.0.0.1`;
- 值里含**空格或 shell 元字符**(`& | ; $ \` < > ( )` 等)时**必须加引号**,例如 `MODEL_CONVERT_PMX="Hatsune Miku.pmx"`;
- 双引号内不要用 `$(...)` 或反引号(会被真的执行),需要字面量时用单引号:`KEY='a b'`。
两个脚本在 source 之前都会先跑 `deploy/env-lib.sh` 的语法预检,不安全写法会直接指出行号、原文与改法。
## 主要 API
| 方法 | 路径 | 说明 |
@@ -399,10 +443,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。
### 审核流程(模型)
+90 -15
View File
@@ -1,5 +1,5 @@
================================================================
OpenDance Studio -- Web 管理服务端 v0.2.0 使用说明
OpenDance Studio -- Web 管理服务端 v0.2.4 使用说明
================================================================
本服务端是 OpenDance Studio 三端中的第一端, 负责管理歌曲、VRM 模型与
@@ -8,6 +8,55 @@ OpenDance Studio -- Web 管理服务端 v0.2.0 使用说明
重要: 本服务端 不部署、不管理 MySQL。数据库为部署方提供的现有实例,
连接信息通过 .env 注入。
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,
看不出缺什么、怎么装。
2. 转换前先定位 Assimp(src/common/assimp.ts): 按 ASSIMP_BIN -> PATH ->
/usr/bin、/usr/local/bin 等常见目录查找, 找不到就一次性给出各发行版安装
命令、查过的路径与替代办法(只传 .glb/.vrm 不需要它), 不再打两条 ENOENT。
3. install.sh 新增 Assimp 检查与自动安装(deploy/assimp-lib.sh): 按发行版调用
apt-get / dnf / yum / zypper / apk / pacman; 装在非常规目录时自动把绝对
路径写进 deploy/.env 的 ASSIMP_BIN; 装不上只告警不中止(可用
SKIP_ASSIMP_INSTALL=1 跳过)。
4. deploy/check-access.sh 自检增加 Assimp 一行; 管理端「概览 -> 服务健康」
显示 Assimp 状态, 不可用时给出提示。
5. 新增 13 项测试(test/assimp-locate.spec.ts)。
v0.2.1 修订
1. 修复部署失败: 模板里的 MODEL_CONVERT_PMX=Hatsune Miku.pmx 值含空格却
没加引号, install.sh 用 `set -a; . deploy/.env` 载入时把 Miku.pmx 当命令
执行, 报 command not found(退出码 127); 模板已改为带引号写法。
2. 新增 .env 语法预检(deploy/env-lib.sh): install.sh 与 ctl.sh 在 source 之前
先检查, 直接给出哪一行、原文与改法, 不再出现看不懂的 127。
3. 失败提示带上出错文件名(.env 被 source 时行号属于 .env)。
4. 新增 12 项回归测试(web-server/test/env-file.spec.ts)。
约定: 值里含空格或 shell 元字符时必须加引号(双引号内不要用 $( ) 或反引号)。
--
一、部署到 Linux 服务器(业务服务, 不含反向代理)
--
@@ -20,11 +69,11 @@ OpenDance Studio -- Web 管理服务端 v0.2.0 使用说明
2. 准备一个现有的 MySQL / MariaDB 实例, 并建好库与账号(见下方"前置要求")
本项目不会创建数据库本身
3. 取得发布包并校验(地址用你们自己的制品库替换)
curl -LO https://<制品库地址>/opendance-web-v0.2.0.tar.gz
curl -LO https://<制品库地址>/opendance-web-v0.2.4.tar.gz
curl -LO https://<制品库地址>/SHA256SUMS
sha256sum -c SHA256SUMS # 期望输出 "OK"
4. 解压并生成配置(交互式引导, 逐项问答, 口令不回显)
tar -xzf opendance-web-v0.2.0.tar.gz && cd opendance-web-v0.2.0
tar -xzf opendance-web-v0.2.4.tar.gz && cd opendance-web-v0.2.4
bash deploy/init-env.sh
5. 安装(建用户与目录 -> 装依赖 -> 迁移 -> 注册系统服务 -> 等健康检查)
bash deploy/install.sh
@@ -66,6 +115,9 @@ OpenDance Studio -- Web 管理服务端 v0.2.0 使用说明
- Node.js 22 或更高版本
- 进程管理: systemd / OpenRC / SysVinit 均可; 三者都没有也能装
(自动降级为 nohup 后台进程 + PID 文件 + crontab @reboot 开机自启)
- Assimp 命令行工具(可选但推荐): .pmx/.fbx 模型转换与 FBX/glTF 动作预处理
需要它; install.sh 会自动尝试安装(apt-get / dnf / yum / zypper / apk /
pacman), 装不上只告警不中止。只上传 .glb/.vrm 模型与 .bvh/.vmd 动作则不需要
- 反向代理: 由另外的服务提供, 本项目不要求、也不安装
- 一个可连通的现有 MySQL / MariaDB 实例, 并已创建数据库与账号:
@@ -79,8 +131,8 @@ OpenDance Studio -- Web 管理服务端 v0.2.0 使用说明
(本项目不会创建数据库本身, 也不需要 GRANT OPTION / FILE / SUPER 等管理权限)
部署步骤
tar -xzf opendance-web-v0.2.0.tar.gz
cd opendance-web-v0.2.0
tar -xzf opendance-web-v0.2.4.tar.gz
cd opendance-web-v0.2.4
bash deploy/init-env.sh # 首次启动引导: 逐项问答生成 deploy/.env(见下)
bash deploy/install.sh # 已以 root 登录, 不需要 sudo
@@ -206,10 +258,24 @@ deploy/.env 初始化引导(deploy/init-env.sh)
对外 IP 自测、80/443 有无反代、防火墙放行情况, 并给出修复命令。
- 管理页面打开是 404
说明访问的是软件 API 端口(默认 3000); 管理页面在管理端端口(默认 3001)。
- 上传 .zip 模型包报 422 且提示 Assimp 不可用
PMX/FBX 转换依赖 Assimp: apt-get install -y assimp-utils libassimp6;
只上传 .glb / .vrm 则不需要它。
- 模型审核界面显示"未分析 / 无预览图"
- 上传 .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 则不需要它。
- 列表/审核里的缩略图是"白模"(纯白模型)
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")后重跑。
- 模型审核界面显示"未分析 / 无预览图"
该模型是升级前入库的: 调 POST /api/models/<id>/reanalyze, 或批量跑
node scripts/reanalyze-models.mjs --url http://127.0.0.1:3000。
@@ -236,10 +302,11 @@ deploy/.env 初始化引导(deploy/init-env.sh)
cd web-server
npm run contracts:check # 契约版本一致性
npm run typecheck # TypeScript 严格检查
npm run test # 168 项单元测试 / 10 个文件(VMD 31、模型压缩包 24、
npm run test # 211 项单元测试 / 14 个文件(VMD 31、模型压缩包 24、
# 模型检查器 25、缩略图 8、骨骼过滤 8、
# 预处理 25、init-env 16、admin-port 16、
# access-log 9、VRM 检查器 6)
# access-log 9、VRM 检查器 6、.env 预检 12、
# Assimp 定位与安装 13、stats 容量与编码 12、缩略图贴图 6)
npm run build # 生产构建
npm run start:prod & # 启动
npm run test:smoke # 57 项端到端冒烟(需要数据库可连通)
@@ -270,6 +337,13 @@ deploy/.env 初始化引导(deploy/init-env.sh)
ADMIN_HOST 管理端监听地址(可选, 默认跟随 HOST;HOST 未设置时同样
回落 0.0.0.0)。需要接口对外、管理端只对本机时设为
127.0.0.1
.env 写法约定: install.sh / ctl.sh 用 `set -a; . deploy/.env` 载入配置, shell 会
真的执行这个文件, 因此普通值不加引号(PORT=3000), 值里含空格或 shell 元字符
(& | ; $ ` < > ( ) 等)时必须加引号, 例如 MODEL_CONVERT_PMX="Hatsune Miku.pmx";
双引号内不要用 $( ) 或反引号(会被真的执行), 需要字面量时用单引号 KEY='a b'。
两个脚本在 source 之前都会先跑 deploy/env-lib.sh 的语法预检, 不安全写法会直接
指出行号、原文与改法。
端口配置非法(非 1..65535 整数)时, 生产环境启动会直接中止;
ADMIN_PORT 设为与 PORT 相同只打印提示, 不中止。
ADMIN_DIR 管理端静态站点目录(默认 ../admin, 即 /opt/opendance/admin)
@@ -278,15 +352,16 @@ deploy/.env 初始化引导(deploy/init-env.sh)
* 反向代理层的同名限制必须不小于此值, 否则大模型上传
会在代理层被拒(nginx client_max_body_size /
IIS requestLimits), 详见 deploy/proxy/README.md
ASSIMP_BIN 可选: Assimp 可执行文件, FBX/glTF 动作预处理需要;
上传 .zip 模型包、或 .pmx/.fbx 单文件模型时必须能调用到,
否则转换失败(422)
ASSIMP_BIN Assimp 可执行文件(install.sh 会自动安装并把解析出的绝对
路径写入此项)。.pmx/.fbx 模型转换与 FBX/glTF 动作预处理
需要; 缺失时上传会失败并给出安装命令, 只上传 .glb/.vrm 与
.bvh/.vmd 动作不受影响
MODEL_CONVERT_FORMAT 需要转换的模型(PMX/FBX)的交付格式:
glb(默认, 两个客户端都原生加载)| vrm
vrm = 在 GLB 之上补 VRMC_vrm 扩展(humanoid 骨骼 / 表情语义),
humanoid 骨骼映射不全时自动回退交付 GLB 并写进 conversion_note。
产物一律用 `assimp info` 回读校验
MODEL_CONVERT_PMX 压缩包内优先选用的 PMX 文件名(默认 Hatsune Miku.pmx,
MODEL_CONVERT_PMX 压缩包内优先选用的 PMX 文件名(默认 "Hatsune Miku.pmx",
大小写不敏感); 找不到时按「格式优先级 -> 目录最浅 ->
文件最大」挑选
MODEL_CONVERT_TIMEOUT_MS
+5 -3
View File
@@ -24,10 +24,10 @@ HOST=0.0.0.0
ADMIN_DIR=/opt/opendance/admin
# ---- 现有 MySQL / MariaDB 实例(本项目不安装、不管理数据库)----
DB_HOST=<existing-mysql-host>
DB_HOST='<existing-mysql-host>'
DB_PORT=3306
DB_USER=opendance_app
DB_PASS=<数据库口令>
DB_PASS='<数据库口令>'
DB_NAME=opendance
# 生产环境必须为 false,表结构一律走 TypeORM migration
DB_SYNCHRONIZE=false
@@ -50,7 +50,9 @@ ASSIMP_BIN=assimp
# humanoid 骨骼名映射不全时会自动回退交付 GLB 并写进 conversion_note
MODEL_CONVERT_FORMAT=glb
# 压缩包里优先选用的 PMX 文件名(大小写不敏感);找不到时按"格式优先级 -> 目录最浅 -> 文件最大"挑
MODEL_CONVERT_PMX=Hatsune Miku.pmx
# 值里含空格或 shell 元字符时必须用引号包起来(install.sh 会用
# `set -a; . deploy/.env` 真的执行本文件;不加引号会把 "Miku.pmx" 当命令)
MODEL_CONVERT_PMX="Hatsune Miku.pmx"
# 单次转换超时(毫秒)
MODEL_CONVERT_TIMEOUT_MS=180000
+70
View File
@@ -0,0 +1,70 @@
#!/bin/bash
# ============================================================
# OpenDance Studio Web API —— 外部依赖 Assimp 的定位与安装
#
# 本文件被 install.sh 引用(不要单独执行)。
#
# Assimp 是**外部**命令行工具(BSD-3-Clause),不在 Node 依赖里。
# 它只影响两件事:
# * 上传 .pmx / .fbx(或含它们的压缩包)时的服务端转换;
# * FBX / glTF 动作的预处理。
# 直接上传 .glb / .vrm 模型,或 .bvh / .vmd / 关键点 JSON 动作,都不需要它。
# 因此这里「装不上」不叫失败,但必须给出结论与可复制的安装命令。
# ============================================================
# 当前发行版对应的安装命令(用于提示)
# 注意:只装 assimp-utils(它会按发行版自动带上对应版本的 libassimp5/6),
# 不写死库名 —— Debian 11 / Ubuntu 22.04 是 libassimp5,Debian 12+ 才是 libassimp6。
opendance_assimp_install_cmd() {
if command -v apt-get >/dev/null 2>&1; then
printf 'apt-get update && apt-get install -y assimp-utils'
elif command -v dnf >/dev/null 2>&1; then
printf 'dnf install -y assimp'
elif command -v yum >/dev/null 2>&1; then
printf 'yum install -y assimp'
elif command -v zypper >/dev/null 2>&1; then
printf 'zypper --non-interactive install assimp'
elif command -v apk >/dev/null 2>&1; then
printf 'apk add --no-cache assimp'
elif command -v pacman >/dev/null 2>&1; then
printf 'pacman -S --noconfirm assimp'
else
printf '用发行版包管理器安装 assimp 命令行工具'
fi
}
# 真正执行安装(静默细节,成功返回 0)
opendance_assimp_install() {
if command -v apt-get >/dev/null 2>&1; then
DEBIAN_FRONTEND=noninteractive apt-get update -qq &&
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq assimp-utils
elif command -v dnf >/dev/null 2>&1; then dnf install -y -q assimp
elif command -v yum >/dev/null 2>&1; then yum install -y -q assimp
elif command -v zypper >/dev/null 2>&1; then zypper --non-interactive install assimp
elif command -v apk >/dev/null 2>&1; then apk add --no-cache assimp
elif command -v pacman >/dev/null 2>&1; then pacman -S --noconfirm assimp
else return 1
fi
}
# 解析 Assimp 的实际路径:ASSIMP_BIN -> PATH -> 常见系统目录
# 找到时把绝对路径打印到 stdout 并返回 0;否则返回 1(stdout 为空)
opendance_assimp_resolve() {
local bin="${ASSIMP_BIN:-assimp}" dir candidate
# 必须同时是**文件**且可执行:只判 -x 会把目录(例如 ASSIMP_BIN=/usr/bin/)当成可执行文件
if [ -f "$bin" ] && [ -x "$bin" ]; then printf '%s' "$bin"; return 0; fi
if command -v "$bin" >/dev/null 2>&1; then command -v "$bin"; return 0; fi
for dir in /usr/bin /usr/local/bin /usr/sbin /usr/local/sbin /snap/bin; do
candidate="$dir/${bin##*/}" # 用参数展开代替 basename: PATH 极窄时 basename 可能不可用
if [ -f "$candidate" ] && [ -x "$candidate" ]; then printf '%s' "$candidate"; return 0; fi
done
return 1
}
# 该目录是否已在服务的默认 PATH 中(否 -> 需要把绝对路径写进 .env)
opendance_assimp_needs_env_path() {
case "$(dirname "${1:-}")" in
/bin|/usr/bin|/usr/local/bin|/sbin|/usr/sbin) return 1 ;;
*) return 0 ;;
esac
}
+25
View File
@@ -16,6 +16,7 @@ APP_DIR="${1:-/opt/opendance}"
PORT=""
HOST_CFG=""
PROBLEMS=0
ASSIMP_MISSING=0
c_red() { printf '\033[31m%s\033[0m\n' "$*"; }
c_grn() { printf '\033[32m%s\033[0m\n' "$*"; }
@@ -216,9 +217,33 @@ if [ "$FW_FOUND" -eq 0 ]; then
info "注意:云服务器还需检查控制台的「安全组 / 网络 ACL」是否放行 $PORT"
fi
# ---------- 6.5 可选依赖 Assimp ----------
title "可选依赖 Assimp(.pmx/.fbx 模型转换、FBX/glTF 动作预处理)"
if [ -f "$(dirname "$0")/assimp-lib.sh" ]; then
# shellcheck source=deploy/assimp-lib.sh
. "$(dirname "$0")/assimp-lib.sh"
ASSIMP_PATH="$(opendance_assimp_resolve || true)"
if [ -n "$ASSIMP_PATH" ]; then
ok "Assimp 可用:$ASSIMP_PATH($("$ASSIMP_PATH" version 2>/dev/null | head -1))"
else
warn "未安装 Assimp:上传 .pmx / .fbx(或含它们的压缩包)会报转换失败"
info "安装:$(opendance_assimp_install_cmd)"
info "只上传 .glb / .vrm 模型与 .bvh / .vmd 动作则不受影响"
ASSIMP_MISSING=1
fi
else
warn "未找到 deploy/assimp-lib.sh,跳过 Assimp 检查"
fi
# ---------- 7. 结论 ----------
title "结论"
if [ "${ASSIMP_MISSING:-0}" = "1" ]; then
c_yel " 提示:未安装 Assimp,.pmx / .fbx 模型转换与 FBX / glTF 动作预处理不可用(与访问无关)。"
echo " 安装:$(opendance_assimp_install_cmd 2>/dev/null || echo '用发行版包管理器安装 assimp')"
echo
fi
if [ "$PROBLEMS" -eq 0 ]; then
c_grn " 未发现本机侧问题。"
echo " 若仍访问不了,按顺序排查:"
+8 -1
View File
@@ -13,6 +13,7 @@
# ============================================================
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" 2>/dev/null && pwd)"
APP_DIR="${APP_DIR:-/opt/opendance}"
SERVICE_USER="${SERVICE_USER:-opendance}"
LOG_FILE="${LOG_FILE:-/var/log/opendance-api.log}"
@@ -95,8 +96,14 @@ start() {
return 0
fi
# 载入部署环境变量
# 载入部署环境变量(先做语法预检:.env 会被 shell 真的执行)
if [ -f "$APP_DIR/deploy/.env" ]; then
if [ -f "$SCRIPT_DIR/env-lib.sh" ]; then
# shellcheck source=deploy/env-lib.sh
. "$SCRIPT_DIR/env-lib.sh"
opendance_validate_env_file "$APP_DIR/deploy/.env" \
|| die "$APP_DIR/deploy/.env 语法预检未通过(见上):给对应行的值加上引号后重试。"
fi
set -a; . "$APP_DIR/deploy/.env"; set +a
else
die "缺少 $APP_DIR/deploy/.env"
+126
View File
@@ -0,0 +1,126 @@
#!/bin/bash
# ============================================================
# OpenDance Studio Web API —— deploy/.env 语法预检
#
# 本文件被 install.sh 与 ctl.sh 引用(不要单独执行)。
#
# 为什么需要:
# 两个脚本都用 `set -a; . deploy/.env` 载入配置,shell 会**真的执行**
# 这个文件。若某个值含空格或 shell 元字符却没加引号,这一行会被切成
# 「赋值 + 命令」,报错形如:
# ./deploy/.env: line 53: Miku.pmx: command not found
# 退出码 127,而且提示里看不出是哪个文件、哪一行、该怎么改。
# 载入前先做一次静态检查,给出带行号与修复建议的中文提示。
#
# 约定(与 init-env.sh 一致):
# 普通值不加引号(如 PORT=3000);值里含空格或 shell 元字符时用引号包起来,
# 例如 MODEL_CONVERT_PMX="Hatsune Miku.pmx"。双引号内不要用 $(...) 或反引号
# —— 它们在载入时会被真正执行。单引号是字面量,最安全。
# ============================================================
# 裸值(未加引号)是否可以被 `set -a; . file` 安全载入
# 赋值语句里的裸值不会做通配展开,所以 * ? [ ] { } ! % + , - . : / @ = 都安全;
# 真正会破坏解析的是:空白、& | ; $ ` < > ( ) \ 以及引号本身、行首的 ~
opendance_env_value_is_safe_unquoted() {
local v="${1:-}"
[ -z "$v" ] && return 0
case "$v" in
*[[:space:]]*|*'&'*|*'|'*|*';'*|*'$'*|*'`'*|*'<'*|*'>'*|*'('*|*')'*|*'\'*|*'"'*|*"'"*) return 1 ;;
'~'*) return 1 ;;
esac
return 0
}
# 值本身是否是安全的写法(空值 / 加引号 / 裸值但字符安全)
# 允许「引号 + 行尾注释」的写法,例如 DB_HOST="127.0.0.1" # 本机
opendance_env_value_is_safe() {
local v="${1:-}" inner="" rest=""
case "$v" in
'') return 0 ;;
\"*)
case "$v" in *\"*) ;; *) return 1 ;; esac # 结束引号必须在
inner="${v#\"}"; inner="${inner%%\"*}" # 引号内的内容
case "$inner" in *'$('*|*'`'*) return 1 ;; esac # 双引号内会真的执行
rest="${v#\"}"; rest="${rest#*\"}" # 结束引号之后的内容
case "$rest" in
''|[[:space:]]|[[:space:]]*|[[:space:]]*'#'*) return 0 ;;
*) return 1 ;;
esac ;;
\'*)
case "$v" in *\'*) ;; *) return 1 ;; esac
rest="${v#\'}"; rest="${rest#*\'}"
case "$rest" in
''|[[:space:]]|[[:space:]]*|[[:space:]]*'#'*) return 0 ;;
*) return 1 ;;
esac ;;
*) opendance_env_value_is_safe_unquoted "$v" ;;
esac
}
# 校验一个 .env 文件:opendance_validate_env_file <文件路径>
# 通过返回 0;发现不安全写法返回 1(问题行与其改法已打印到 stderr)
opendance_validate_env_file() {
local file="${1:-}" lineno=0 bad=0 line key value reason inner
if [ ! -f "$file" ]; then
printf '[env] 找不到配置文件:%s\n' "$file" >&2
return 1
fi
while IFS= read -r line || [ -n "$line" ]; do
lineno=$((lineno + 1))
line="${line%$'\r'}" # 兼容 CRLF
case "$line" in ''|'#'*) continue ;; esac
reason=""
case "$line" in
[A-Za-z_]*=*) ;;
*) reason="不是「键=值」形式(载入时会被当成命令执行)" ;;
esac
if [ -z "$reason" ]; then
key="${line%%=*}"
value="${line#*=}"
case "$key" in
*[!A-Za-z0-9_]*) reason="键名含非法字符" ;;
esac
fi
if [ -z "$reason" ] && ! opendance_env_value_is_safe "$value"; then
case "$value" in
\"*)
inner="${value#\"}"
case "$inner" in
*\"*) reason="引号写法不安全:引号后有其它内容,或引号内用了 \$( ) / 反引号(载入时会真的执行)" ;;
*) reason="双引号未闭合" ;;
esac ;;
\'*)
inner="${value#\'}"
case "$inner" in
*\'*) reason="单引号后还有其它内容,请把整个值放进引号" ;;
*) reason="单引号未闭合" ;;
esac ;;
*) reason="值含空格或 shell 元字符,却未加引号" ;;
esac
fi
if [ -n "$reason" ]; then
bad=$((bad + 1))
printf '\033[1;31m[env]\033[0m %s 第 %d 行写法不安全:%s\n' "$file" "$lineno" "$reason" >&2
printf ' %d | %s\n' "$lineno" "$line" >&2
case "$line" in
*'='*)
key="${line%%=*}"; value="${line#*=}"
case "$value" in
\"*|\'*)
printf ' 提示: 引号请成对、且把整个值包住; 单引号是字面量, 最安全。\n' >&2 ;;
*"'"*)
printf ' 提示: 值里同时有单引号与特殊字符, 请手工调整 - 单引号内不能再出现单引号。\n' >&2 ;;
*'$'*|*'`'*)
printf " 改法: %s='%s' 注意: 双引号里的 \$( ) 与反引号会被真的执行, 单引号才是字面量。\n" "$key" "$value" >&2 ;;
*)
printf ' 改法: %s="%s"\n' "$key" "$value" >&2 ;;
esac ;;
esac
fi
done < "$file"
if [ "$bad" -gt 0 ]; then
printf '\033[1;31m[env]\033[0m %s 语法预检未通过:%d 行需要加引号(见上)。\n' "$file" "$bad" >&2
return 1
fi
return 0
}
+45 -1
View File
@@ -21,11 +21,20 @@
# ============================================================
set -euo pipefail
# 失败时打印出错行号,避免只看到半截输出
trap 'printf "\033[1;31m[install]\033[0m 第 %d 行执行失败(退出码 %d)\n" "$LINENO" "$?" >&2' ERR
trap 'printf "\033[1;31m[install]\033[0m %s 第 %d 行执行失败(退出码 %d)\n" "${BASH_SOURCE[0]}" "$LINENO" "$?" >&2' ERR
SRC_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$SRC_DIR"
# .env 语法预检(deploy/env-lib.sh):.env 是被 shell 真正 source 的文件,
# 未加引号且含空格的值会被当成命令执行,报错形如
# ./deploy/.env: line 53: Miku.pmx: command not found
# 载入前先查一遍,给出带行号与改法的中文提示。
# shellcheck source=deploy/env-lib.sh
. "$SRC_DIR/deploy/env-lib.sh"
# shellcheck source=deploy/assimp-lib.sh
. "$SRC_DIR/deploy/assimp-lib.sh"
APP_DIR="${APP_DIR:-/opt/opendance}"
SERVICE_USER="${SERVICE_USER:-opendance}"
STORAGE_DIR="${STORAGE_DIR:-/var/lib/opendance/storage}"
@@ -125,6 +134,8 @@ if [ ! -f deploy/.env ]; then
fi
fi
opendance_validate_env_file "./deploy/.env" || die "deploy/.env 语法预检未通过(见上):按提示给对应行的值加上引号后重新执行。"
set -a
# shellcheck disable=SC1091
. ./deploy/.env
@@ -165,6 +176,38 @@ log "运行用户:$SERVICE_USER"
log "上传目录:$STORAGE_DIR"
log "目标数据库:${DB_HOST}:${DB_PORT:-3306}/${DB_NAME}(现有实例,本脚本不会创建或管理数据库)"
# ---------- 0.5 可选外部依赖:Assimp ----------
# 逻辑与文案在 deploy/assimp-lib.sh(可单独测试):Assimp 是外部命令行工具
# (BSD-3-Clause),不在 Node 依赖里,只影响 .pmx/.fbx 模型转换与 FBX/glTF
# 动作预处理;装不上不中止安装,但必须当场给出结论与可复制的安装命令。
log "检查 Assimp(可选依赖:.pmx/.fbx 模型转换、FBX/glTF 动作预处理需要)"
ASSIMP_PATH="$(opendance_assimp_resolve || true)"
if [ -z "$ASSIMP_PATH" ] && [ "${SKIP_ASSIMP_INSTALL:-0}" != "1" ]; then
log "未找到 Assimp,尝试用系统包管理器安装:$(opendance_assimp_install_cmd)"
if opendance_assimp_install >/dev/null 2>&1; then
ASSIMP_PATH="$(opendance_assimp_resolve || true)"
else
warn "自动安装 Assimp 失败(离线环境或该发行版没有对应软件包)"
fi
fi
if [ -n "$ASSIMP_PATH" ]; then
log "Assimp:$ASSIMP_PATH($("$ASSIMP_PATH" version 2>/dev/null | head -1))"
if opendance_assimp_needs_env_path "$ASSIMP_PATH"; then
log "该目录不在服务默认 PATH 中,把 ASSIMP_BIN=\"$ASSIMP_PATH\" 写入 deploy/.env"
if grep -qE '^[[:space:]]*#?[[:space:]]*ASSIMP_BIN=' deploy/.env; then
sed -i "0,/^[[:space:]]*#\?[[:space:]]*ASSIMP_BIN=.*/s||ASSIMP_BIN=\"$ASSIMP_PATH\"|" deploy/.env
else
printf '\nASSIMP_BIN="%s"\n' "$ASSIMP_PATH" >> deploy/.env
fi
fi
else
warn "未找到 Assimp:上传 .pmx / .fbx(或含它们的压缩包)会转换失败,FBX / glTF 动作也无法预处理。"
warn " 手动安装:$(opendance_assimp_install_cmd)"
warn " 只上传 .glb / .vrm 模型与 .bvh / .vmd / 关键点 JSON 动作则不受影响。"
warn " 已装好但不在 PATH?在 deploy/.env 里设置 ASSIMP_BIN 为绝对路径后重跑本脚本。"
warn " 也可用 SKIP_ASSIMP_INSTALL=1 跳过自动安装。"
fi
# ---------- 1. 系统用户与目录 ----------
if ! id -u "$SERVICE_USER" >/dev/null 2>&1; then
log "创建系统用户 $SERVICE_USER"
@@ -320,6 +363,7 @@ fi
# ---------- 3. 数据库迁移 ----------
log "执行 TypeORM 迁移(不使用 DB_SYNCHRONIZE)"
opendance_validate_env_file "$APP_DIR/deploy/.env" || die "$APP_DIR/deploy/.env 语法预检未通过(见上)"
set -a; . "$APP_DIR/deploy/.env"; set +a
cd "$APP_DIR/web-server"
as_service_user env \
+2 -2
View File
@@ -1,5 +1,5 @@
project: opendance-web-server
version: 0.2.0
version: 0.2.4
repository: opendance-web
default_branch: main
contracts_version: 0.4.0
@@ -60,7 +60,7 @@ tasks:
status: done
deliverable:
artifact: opendance-web-v0.2.0.tar.gz
artifact: opendance-web-v0.2.4.tar.gz
packaging: Linux 业务服务(系统服务托管,双端口:软件 API + 管理端,不含 MySQL、不含反向代理、不使用 Docker)
includes:
- web-server/ # NestJS 源码 + 构建产物(含 BVH / VMD 内置解析、ZIP 读取与模型压缩包转换)
+6 -2
View File
@@ -1,11 +1,13 @@
#!/bin/bash
# ============================================================
# 打包发布产物:opendance-web-v0.1.0.tar.gz
# 打包发布产物:opendance-web-v0.2.4.tar.gz
#
# 产物结构(Linux 业务服务部署,不使用 Docker、不部署反向代理):
# web-server/ NestJS 源码 + 构建产物
# admin/ React 管理端构建产物
# deploy/ install.sh / ctl.sh / uninstall.sh / .env.example
# env-lib.sh (.env 语法预检) / assimp-lib.sh (Assimp 定位安装)
# init-env.sh (.env 引导)
# systemd|openrc|initd / proxy(反代说明文档,仅文档不部署)
# contracts/ 当前版本契约快照
# THIRD_PARTY.md 开源项目声明
@@ -19,7 +21,7 @@ set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"
VERSION="${1:-0.2.0}"
VERSION="${1:-0.2.4}"
NAME="opendance-web-v${VERSION}"
OUT_DIR="$REPO_ROOT/dist-release"
STAGE="$OUT_DIR/$NAME"
@@ -130,6 +132,8 @@ for required in \
"opendance-web-v${VERSION}/web-server/dist/models/vrm-writer.js" \
"opendance-web-v${VERSION}/web-server/dist/models/gltf-packer.js" \
"opendance-web-v${VERSION}/deploy/init-env.sh" \
"opendance-web-v${VERSION}/deploy/env-lib.sh" \
"opendance-web-v${VERSION}/deploy/assimp-lib.sh" \
"opendance-web-v${VERSION}/deploy/proxy/README.md" \
"opendance-web-v${VERSION}/deploy/proxy/nginx.conf.example" \
"opendance-web-v${VERSION}/deploy/proxy/web.config.example" \
+1 -1
View File
@@ -160,7 +160,7 @@ node scripts/import-default-model.mjs --write-source-only --model-id 22 --dry-ru
```bash
cd web-server
npx vitest run # 10 个文件 / 168 项通过
npx vitest run # 14 个文件 / 211 项通过
npm run test:smoke # 冒烟 [4] 段落
```
+1 -1
View File
@@ -86,7 +86,7 @@ draft ──submit──▶ pending ──approve──▶ published
```bash
cd web-server
npx vitest run # 10 个文件 / 168 项通过(含 admin-bone-filter 8 项)
npx vitest run # 14 个文件 / 211 项通过(含 admin-bone-filter 8 项、.env 预检 12 项、Assimp 13 项、缩略图贴图 6 项)
npm run test:smoke
```
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opendance-admin",
"private": true,
"version": "0.2.0",
"version": "0.2.4",
"type": "module",
"description": "OpenDance Studio 管理端(React + TypeScript + Vite)",
"scripts": {
+9
View File
@@ -273,12 +273,21 @@ export interface HealthDatabase {
migrationsPending?: number;
}
export interface HealthAssimp {
available: boolean;
/** 解析到的 Assimp 可执行文件路径 */
path?: string;
version?: string;
error?: string;
}
export interface Health {
status: 'ok' | 'degraded';
uptimeSec: number;
version: string;
contractVersion: Record<string, string>;
database: HealthDatabase;
assimp?: HealthAssimp;
}
/* ------------------------------------------------------------ 错误响应 */
+18
View File
@@ -196,10 +196,28 @@ export function DashboardPage() {
<span className="muted">迁移待执行</span>
<code>{healthValue.database?.migrationsPending ?? 0}</code>
</div>
<div className="kv">
<span className="muted">assimp</span>
<code>
{healthValue.assimp?.available
? (healthValue.assimp.version ?? 'available')
: '未安装'}
</code>
</div>
</div>
) : (
<ErrorBox message={health.error ?? '无法获取健康状态'} onRetry={state.reload} />
)}
{health.ok && healthValue && !healthValue.assimp?.available ? (
<div className="banner banner-warn" role="status">
<strong>Assimp 不可用</strong>
<span>
上传 .pmx / .fbx 模型(或含 PMX/FBX 的压缩包)会转换失败;FBX / glTF 动作预处理同样
需要它。在服务器上安装后无需重启服务:<code>apt-get install -y assimp-utils</code>
(RHEL 系为 <code>dnf install -y assimp</code>)。只上传 .glb / .vrm 则不受影响。
</span>
</div>
) : null}
</div>
</section>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "opendance-web-server",
"version": "0.2.0",
"version": "0.2.4",
"description": "OpenDance Studio Web 管理服务端(NestJS + TypeORM + 现有 MySQL 实例)",
"license": "MIT",
"private": true,
+133
View File
@@ -0,0 +1,133 @@
/**
* Assimp 可执行文件的定位、安装提示与可用性探测。
*
* 背景:PMX / FBX 模型转换与 FBX / glTF 动作预处理都依赖**外部** Assimp
* 命令行工具(BSD-3-Clause,不在 Node 依赖里)。装漏了只有在用户上传完
* 一整个压缩包之后才会暴露,而且原始报错只有 `spawn assimp ENOENT`。
* 这里把「找二进制」与「怎么装」集中到一处,供转换管线、动作预处理、
* /health 与部署自检共用。
*/
import { execFile } from 'node:child_process';
import { existsSync, statSync } from 'node:fs';
import { delimiter, join } from 'node:path';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
/**
* 除 PATH 之外再查找的常见目录。
* 生产上服务由系统服务托管,PATH 可能很窄(甚至只有 /usr/bin),
* 而用户把 Assimp 装在 /usr/local/bin 也很常见。
*/
export const ASSIMP_FALLBACK_DIRS = [
'/usr/bin',
'/usr/local/bin',
'/usr/sbin',
'/usr/local/sbin',
'/snap/bin',
];
export interface AssimpLocation {
/** 解析到的可执行文件路径(未找到时原样返回传入的 bin) */
path: string;
found: boolean;
/** 依次查找过的候选路径(用于错误信息) */
searched: string[];
}
/**
* 定位 Assimp 可执行文件:显式路径 -> PATH -> 常见系统目录。
* 只做文件系统检查,不执行它(探测可用性见 detectAssimpBin)。
*/
export function resolveAssimpBinary(bin: string): AssimpLocation {
const candidates: string[] = [];
if (bin.includes('/') || bin.includes('\\')) {
candidates.push(bin);
} else {
for (const dir of (process.env.PATH ?? '').split(delimiter)) {
if (dir) candidates.push(join(dir, bin));
}
for (const dir of ASSIMP_FALLBACK_DIRS) candidates.push(join(dir, bin));
}
const searched = [...new Set(candidates)];
for (const candidate of searched) {
try {
// 必须是文件:只判 existsSync 会把同名目录(例如 ASSIMP_BIN=/usr/bin)当成二进制
if (existsSync(candidate) && statSync(candidate).isFile()) {
return { path: candidate, found: true, searched };
}
} catch {
/* 权限等问题一律视为该候选不可用,继续找下一个 */
}
}
return { path: bin, found: false, searched };
}
/** 各发行版的安装命令(部署脚本与错误信息共用同一份文案) */
export const ASSIMP_INSTALL_COMMANDS: ReadonlyArray<{ distro: string; command: string }> = [
{ distro: 'Debian / Ubuntu', command: 'apt-get update && apt-get install -y assimp-utils' },
{ distro: 'RHEL / CentOS / Rocky / Fedora', command: 'dnf install -y assimp' },
{ distro: 'Alpine', command: 'apk add --no-cache assimp' },
{ distro: 'Arch', command: 'pacman -S --noconfirm assimp' },
];
export function assimpInstallHint(indent = ' '): string {
return ASSIMP_INSTALL_COMMANDS.map((item) => `${indent}${item.distro}: ${item.command}`).join('\n');
}
/** 找不到 Assimp 时的完整可读错误(含查过的路径、安装命令与替代办法) */
export function assimpMissingMessage(bin: string, searched: string[] = []): string {
const tried =
searched.length > 0
? `\n已查找 ${searched.length} 处: ${searched.slice(0, 5).join(', ')}${searched.length > 5 ? ' ...' : ''}`
: '';
return (
`未找到 Assimp 可执行文件 "${bin}"。PMX / FBX 模型转换与 FBX / glTF 动作预处理都需要它` +
'(外部命令行工具, 不在 Node 依赖内)。' +
tried +
'\n安装方式:\n' +
assimpInstallHint() +
'\n装好后可用 `assimp version` 验证; 若它不在服务进程的 PATH 里, ' +
'请在 deploy/.env 中把 ASSIMP_BIN 设为绝对路径并重启服务。' +
'\n只上传 .glb / .vrm 模型(或 .bvh / .vmd / 关键点 JSON 动作)则不需要 Assimp。'
);
}
export interface AssimpProbe {
available: boolean;
/** 解析到的路径(未找到时为原值) */
path: string;
version?: string;
error?: string;
searched: string[];
}
/**
* 探测 Assimp 是否真的可用(执行 `assimp version`)。
* 用于 /health、部署自检,以及转换前的预检。
*/
export async function detectAssimpBin(bin: string): Promise<AssimpProbe> {
const location = resolveAssimpBinary(bin);
if (!location.found) {
return {
available: false,
path: location.path,
error: `未安装 (${bin})`,
searched: location.searched,
};
}
try {
const { stdout } = await execFileAsync(location.path, ['version'], { timeout: 10_000 });
const version =
stdout.split(/\r?\n/).find((line) => line.toLowerCase().includes('assimp')) ?? stdout.trim();
return { available: true, path: location.path, version: version.trim(), searched: location.searched };
} catch (error) {
const err = error as NodeJS.ErrnoException;
return {
available: false,
path: location.path,
error: err.code === 'ENOENT' ? `未安装 (${bin})` : (err.message ?? '未知错误'),
searched: location.searched,
};
}
}
+15 -2
View File
@@ -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) {
+28 -1
View File
@@ -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;
// ---- 来源五元组(必填)----
@@ -24,6 +24,8 @@ export interface HealthReport {
};
assimp: {
available: boolean;
/** 解析到的 Assimp 可执行文件路径(未找到时为配置值) */
path?: string;
version?: string;
error?: string;
};
@@ -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`);
}
}
+8
View File
@@ -7,6 +7,7 @@ import { promisify } from 'node:util';
import { ModelFormat } from '../common/enums';
import { ZipEntry, readZipEntries } from '../common/zip-reader';
import { embedGlbImages } from './glb-textures';
import { assimpMissingMessage, resolveAssimpBinary } from '../common/assimp';
import { packGltfToGlb } from './gltf-packer';
import { VrmWrapMeta, detectGlbKind, wrapGlbAsVrm } from './vrm-writer';
@@ -250,6 +251,13 @@ async function runAssimpPipeline(
): Promise<{ buffer: Buffer; format: ModelFormat; note: string; attempts: string[] }> {
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const prefer = options.preferFormat ?? 'glb';
// 预检:Assimp 缺失时直接给出「怎么装 + 查过哪些路径」,而不是两条 spawn ENOENT。
// 只做文件系统检查(不执行),避免给假二进制(测试桩)增加额外要求。
const location = resolveAssimpBinary(options.assimpBin);
if (!location.found) {
throw new Error(`模型转换失败:${assimpMissingMessage(options.assimpBin, location.searched)}`);
}
{
const workDir = dirname(modelPath);
const attempts: string[] = [];
+67
View File
@@ -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;
}
+321 -9
View File
@@ -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)) {
+42 -3
View File
@@ -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);
@@ -202,7 +217,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 +256,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 +266,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,
+5 -17
View File
@@ -4,6 +4,8 @@ import { existsSync } from 'node:fs';
import { basename, extname, join } from 'node:path';
import { promisify } from 'node:util';
import { assimpMissingMessage, resolveAssimpBinary } from '../common/assimp';
const execFileAsync = promisify(execFile);
export const ASSIMP_CONVERT_TIMEOUT_MS = 120_000;
@@ -31,10 +33,8 @@ export async function convertToBvhWithAssimp(
} catch (error) {
const err = error as NodeJS.ErrnoException & { stderr?: string };
if (err.code === 'ENOENT') {
throw new BadRequestException(
`未找到 Assimp 可执行文件「${assimpBin}」。FBX / glTF 动作预处理需要 Assimp(BSD-3-Clause),` +
'请安装后设置 ASSIMP_BIN 环境变量;BVH 动作无需 Assimp。',
);
const location = resolveAssimpBinary(assimpBin);
throw new BadRequestException(assimpMissingMessage(assimpBin, location.searched));
}
const detail = (err.stderr ?? err.message ?? '').toString().trim().slice(0, 500);
throw new BadRequestException(`Assimp 转换失败:${detail || '未知错误'}`);
@@ -47,16 +47,4 @@ export async function convertToBvhWithAssimp(
}
/** 探测 Assimp 是否可用(用于 /health 与部署自检) */
export async function detectAssimp(assimpBin: string): Promise<{ available: boolean; version?: string; error?: string }> {
try {
const { stdout } = await execFileAsync(assimpBin, ['version'], { timeout: 10_000 });
const version = stdout.split(/\r?\n/).find((line) => line.toLowerCase().includes('assimp')) ?? stdout.trim();
return { available: true, version: version.trim() };
} catch (error) {
const err = error as NodeJS.ErrnoException;
return {
available: false,
error: err.code === 'ENOENT' ? `未安装(${assimpBin})` : (err.message ?? '未知错误'),
};
}
}
export { detectAssimpBin as detectAssimp } from '../common/assimp';
+200
View File
@@ -0,0 +1,200 @@
import { spawnSync } from 'node:child_process';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
import {
ASSIMP_FALLBACK_DIRS,
assimpInstallHint,
assimpMissingMessage,
detectAssimpBin,
resolveAssimpBinary,
} from '../src/common/assimp';
import { convertModelFile } from '../src/models/model-convert';
/**
* Assimp 缺失时的可诊断性。
*
* 背景(真实故障):服务器没装 Assimp,上传 PMX 压缩包只得到
* GLB 直出:导出失败(ENOENT):spawn assimp ENOENT
* glTF 直出:导出失败(ENOENT):spawn assimp ENOENT
* 用户看不出「缺什么、怎么装」。现在:
* * 转换前先定位二进制,找不到就一次性给出安装命令与查过的路径;
* * 定位逻辑覆盖 PATH 之外的常见目录(服务由 systemd 托管时 PATH 可能很窄)。
*/
let workRoot = '';
let fakeBin = '';
function findDeployLib(): string {
const candidates = [
resolve(process.cwd(), '..', 'deploy', 'assimp-lib.sh'),
resolve(process.cwd(), 'deploy', 'assimp-lib.sh'),
resolve(process.cwd(), '..', '..', 'deploy', 'assimp-lib.sh'),
];
for (const candidate of candidates) {
if (existsSync(candidate)) return candidate;
}
throw new Error(`找不到 deploy/assimp-lib.sh,候选路径:\n${candidates.join('\n')}`);
}
const ASSIMP_LIB = findDeployLib();
/** 写一个最小的假 assimp:只实现 `version` */
function writeFakeAssimp(path: string, versionLine = 'Assimp version 6.0.4'): string {
mkdirSync(join(path, '..'), { recursive: true });
writeFileSync(path, `#!/bin/bash\n[ "\${1:-}" = "version" ] && echo "${versionLine}"\nexit 0\n`);
chmodSync(path, 0o755);
return path;
}
beforeAll(() => {
workRoot = mkdtempSync(join(tmpdir(), 'opendance-assimp-test-'));
fakeBin = writeFakeAssimp(join(workRoot, 'bin', 'assimp'));
});
afterAll(() => {
rmSync(workRoot, { recursive: true, force: true });
});
const savedPath = process.env.PATH;
afterEach(() => {
process.env.PATH = savedPath;
});
describe('Assimp 定位(resolveAssimpBinary)', () => {
it('能在 PATH 中找到可执行文件', () => {
process.env.PATH = `${join(workRoot, 'bin')}:/usr/bin:/bin`;
const result = resolveAssimpBinary('assimp');
expect(result.found).toBe(true);
expect(result.path).toBe(fakeBin);
});
it('显式绝对路径优先,不存在时 found=false 并给出查找记录', () => {
const missing = join(workRoot, 'no-such-assimp');
const result = resolveAssimpBinary(missing);
expect(result.found).toBe(false);
expect(result.searched).toContain(missing);
const present = resolveAssimpBinary(fakeBin);
expect(present.found).toBe(true);
expect(present.path).toBe(fakeBin);
});
it('PATH 里没有时仍会查常见系统目录(systemd 服务 PATH 可能很窄)', () => {
process.env.PATH = '/nonexistent-dir-only';
const result = resolveAssimpBinary('assimp');
// 结果取决于本机是否装了真实 assimp:两种都必须把常见目录查过
for (const dir of ASSIMP_FALLBACK_DIRS) {
expect(result.searched).toContain(join(dir, 'assimp'));
}
if (!result.found) expect(result.path).toBe('assimp');
});
});
describe('Assimp 缺失时的错误信息', () => {
it('包含二进制名、各发行版安装命令、替代办法与查过的路径', () => {
const message = assimpMissingMessage('assimp', ['/usr/bin/assimp', '/usr/local/bin/assimp']);
expect(message).toContain('assimp');
expect(message).toContain('apt-get install -y assimp-utils');
expect(message).toContain('dnf install -y assimp');
expect(message).toContain('/usr/bin/assimp');
expect(message).toContain('ASSIMP_BIN');
expect(message).toContain('.glb / .vrm');
});
it('安装提示各发行版一条命令', () => {
const hint = assimpInstallHint();
for (const distro of ['Debian / Ubuntu', 'Alpine', 'Arch']) {
expect(hint).toContain(distro);
}
});
});
describe('Assimp 可用性探测(detectAssimpBin)', () => {
it('能执行时返回版本与路径', async () => {
const probe = await detectAssimpBin(fakeBin);
expect(probe.available).toBe(true);
expect(probe.path).toBe(fakeBin);
expect(probe.version).toContain('6.0.4');
});
it('找不到时 available=false 且 error 说明未安装', async () => {
const probe = await detectAssimpBin(join(workRoot, 'no-such-assimp'));
expect(probe.available).toBe(false);
expect(probe.error).toContain('未安装');
expect(probe.searched.length).toBeGreaterThan(0);
});
});
describe('转换管线:Assimp 缺失时快速失败并给出可操作信息', () => {
it('convertModelFile 抛出的错误包含安装命令,且不再出现两次 spawn ENOENT', async () => {
let message = '';
try {
await convertModelFile(Buffer.from('PMX dummy'), 'Hatsune Miku.pmx', {
assimpBin: join(workRoot, 'no-such-assimp'),
timeoutMs: 5_000,
});
throw new Error('应当抛出异常');
} catch (error) {
message = error instanceof Error ? error.message : String(error);
}
expect(message).toContain('模型转换失败');
expect(message).toContain('apt-get install -y assimp-utils');
expect(message).toContain('ASSIMP_BIN');
expect(message).not.toContain('ENOENT');
});
});
describe('deploy/assimp-lib.sh:部署脚本共用的安装逻辑', () => {
function runLib(script: string, path?: string) {
// 覆盖 PATH 的用例里必须用绝对路径调 bash,否则连 bash 都找不到
return spawnSync('/bin/bash', ['-c', `. "$1"; ${script}`, '_', ASSIMP_LIB], {
encoding: 'utf8',
timeout: 15000,
env: { ...process.env, ...(path ? { PATH: path } : {}) },
});
}
it('opendance_assimp_resolve 能在 PATH 中找到二进制', () => {
const result = runLib('opendance_assimp_resolve', `${join(workRoot, 'bin')}:/usr/bin:/bin`);
expect(result.stdout.trim()).toBe(fakeBin);
expect(result.status).toBe(0);
});
it('opendance_assimp_resolve 在找不到时返回非 0 且无输出', () => {
const result = runLib('opendance_assimp_resolve || echo MISSING', '/nonexistent-dir-only');
// 本机若真的装了 assimp(/usr/bin),则跳过这条断言的严格性
if (!existsSync('/usr/bin/assimp') && !existsSync('/usr/local/bin/assimp')) {
expect(result.stdout.trim()).toBe('MISSING');
}
expect(result.status).toBe(0);
});
it('opendance_assimp_install_cmd 按包管理器给出对应命令', () => {
const aptDir = join(workRoot, 'apt');
mkdirSync(aptDir, { recursive: true });
writeFileSync(join(aptDir, 'apt-get'), '#!/bin/bash\nexit 0\n');
chmodSync(join(aptDir, 'apt-get'), 0o755);
const result = runLib('opendance_assimp_install_cmd', `${aptDir}:/usr/bin:/bin`);
expect(result.stdout).toContain('apt-get install -y assimp-utils');
});
it('opendance_assimp_install 调用包管理器安装 assimp-utils(离线失败也不抛)', () => {
const aptDir = join(workRoot, 'apt');
const log = join(aptDir, 'calls.log');
rmSync(log, { force: true });
writeFileSync(join(aptDir, 'apt-get'), `#!/bin/bash\necho "apt-get $*" >> "${log}"\nexit 0\n`);
chmodSync(join(aptDir, 'apt-get'), 0o755);
const result = runLib('opendance_assimp_install', `${aptDir}:/usr/bin:/bin`);
expect(result.status).toBe(0);
const calls = existsSync(log) ? readFileSync(log, 'utf8') : '';
expect(calls).toContain('apt-get install -y -qq assimp-utils');
});
it('非常规目录需要写 ASSIMP_BIN,标准目录不需要', () => {
expect(runLib(`opendance_assimp_needs_env_path ${join(workRoot, 'bin', 'assimp')} && echo YES`).stdout).toContain('YES');
expect(runLib('opendance_assimp_needs_env_path /usr/bin/assimp || echo NO').stdout).toContain('NO');
});
});
+189
View File
@@ -0,0 +1,189 @@
import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
/**
* deploy/.env 的「可被 shell 安全载入」保证。
*
* 背景(真实故障):install.sh 用 `set -a; . deploy/.env` 载入配置,而模板里
* MODEL_CONVERT_PMX=Hatsune Miku.pmx
* 的值含空格却没加引号,这一行被切成「赋值 + 命令」,安装直接失败:
* ./deploy/.env: line 53: Miku.pmx: command not found
* [install] 第 53 行执行失败(退出码 127)
*
* 因此这里锁两条线:
* 1. deploy/.env.example 必须能被 `set -a; .` 原样载入(回归用例);
* 2. deploy/env-lib.sh 的预检能在载入前拦住不安全写法,并给出行号与改法。
*/
function findDeployFile(name: string): string {
const candidates = [
resolve(process.cwd(), '..', 'deploy', name), // 从 web-server/ 运行(vitest 默认)
resolve(process.cwd(), 'deploy', name), // 从仓库根运行
resolve(process.cwd(), '..', '..', 'deploy', name),
];
for (const candidate of candidates) {
if (existsSync(candidate)) return candidate;
}
throw new Error(`找不到 deploy/${name},候选路径:\n${candidates.join('\n')}`);
}
const EXAMPLE = findDeployFile('.env.example');
const ENV_LIB = findDeployFile('env-lib.sh');
const INSTALL_SH = findDeployFile('install.sh');
const CTL_SH = findDeployFile('ctl.sh');
const dirs: string[] = [];
function makeDir(): string {
const dir = mkdtempSync(join(tmpdir(), 'opendance-env-'));
dirs.push(dir);
return dir;
}
afterEach(() => {
while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true });
});
/** 用真实 shell 载入一个 .env(与 install.sh 的做法一致) */
function sourceEnv(file: string) {
return spawnSync(
'bash',
[
'-c',
'set -a; . "$1"; set +a; printf "%s\\n" "${MODEL_CONVERT_PMX:-}" "${DB_HOST:-}" "${DB_PASS:-}" "${UPLOAD_MAX_BYTES:-}"',
'_',
file,
],
{ encoding: 'utf8', timeout: 15000 },
);
}
/** 调用 deploy/env-lib.sh 的预检函数 */
function validate(file: string) {
return spawnSync('bash', ['-c', '. "$1"; opendance_validate_env_file "$2"', '_', ENV_LIB, file], {
encoding: 'utf8',
timeout: 15000,
});
}
function writeEnv(content: string): string {
const file = join(makeDir(), '.env');
writeFileSync(file, content);
return file;
}
describe('deploy/.env.example:必须能被 shell 原样载入', () => {
it('`set -a; . .env.example` 成功, 且带空格的值读回完整 (回归: 修复前此处退出码 127)', () => {
const result = sourceEnv(EXAMPLE);
expect(result.stderr).not.toContain('command not found');
expect(result.status).toBe(0);
const [pmx, host, pass, uploadMax] = result.stdout.trimEnd().split('\n');
expect(pmx).toBe('Hatsune Miku.pmx');
expect(host).toBe('<existing-mysql-host>');
expect(pass).toBe('<数据库口令>');
expect(uploadMax).toBe('536870912');
});
it('模板整体通过语法预检', () => {
const result = validate(EXAMPLE);
expect(result.status).toBe(0);
expect(result.stderr).toBe('');
});
it('模板里每个赋值行都通过预检(逐行定位,便于以后加字段时发现问题)', () => {
const lines = readFileSync(EXAMPLE, 'utf8').split('\n');
const assigns = lines.filter((l) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(l));
expect(assigns.length).toBeGreaterThan(10); // 模板字段数量下限,防止误删
for (const line of assigns) {
expect(validate(writeEnv(`${line}\n`)).status, `模板行应通过预检:${line}`).toBe(0);
}
});
});
describe('deploy/env-lib.sh:载入前的语法预检', () => {
it('拦住「值含空格却未加引号」,并给出行号、原文与改法(本次故障的原始写法)', () => {
const result = validate(writeEnv('NODE_ENV=production\nMODEL_CONVERT_PMX=Hatsune Miku.pmx\n'));
expect(result.status).toBe(1);
expect(result.stderr).toContain('第 2 行');
expect(result.stderr).toContain('MODEL_CONVERT_PMX=Hatsune Miku.pmx');
expect(result.stderr).toContain('MODEL_CONVERT_PMX="Hatsune Miku.pmx"');
});
it('拦住 shell 元字符,且对 $( ) 建议单引号(双引号仍会执行)', () => {
const result = validate(writeEnv('A=x&y\nB=$(id)\n'));
expect(result.status).toBe(1);
expect(result.stderr).toContain('第 1 行');
expect(result.stderr).toContain('第 2 行');
expect(result.stderr).toContain("B='$(id)'");
});
it('拦住未闭合引号', () => {
const result = validate(writeEnv('A="unclosed\n'));
expect(result.status).toBe(1);
expect(result.stderr).toContain('双引号未闭合');
});
it('不误伤合法写法:* % 口令、IPv4、路径、空值、单引号、引号 + 行尾注释', () => {
const result = validate(
writeEnv(
[
'DB_PASS=S3cr3t*Pwd%1',
'DB_HOST=127.0.0.1',
'DB_PORT=3306',
'STORAGE_DIR=/var/lib/opendance/storage',
'EMPTY=',
"WITH_SPACE='a b c'",
'QUOTED_COMMENT="x y" # 行尾注释',
'MODEL_CONVERT_PMX="Hatsune Miku.pmx"',
'# 注释与空行也必须放过',
'',
].join('\n'),
),
);
expect(result.stderr).toBe('');
expect(result.status).toBe(0);
});
it('拦住非「键=值」的行号并指出原因', () => {
const result = validate(writeEnv('A=1\n这一行不是赋值\n'));
expect(result.status).toBe(1);
expect(result.stderr).toContain('第 2 行');
expect(result.stderr).toContain('不是「键=值」形式');
});
it('文件不存在时返回 1(而不是静默通过)', () => {
const result = validate(join(makeDir(), 'missing.env'));
expect(result.status).toBe(1);
expect(result.stderr).toContain('找不到配置文件');
});
});
describe('载入顺序:install.sh / ctl.sh 必须先预检再 source', () => {
it('install.sh 在 `. ./deploy/.env` 之前调用预检', () => {
const text = readFileSync(INSTALL_SH, 'utf8');
const check = text.indexOf('opendance_validate_env_file "./deploy/.env"');
const source = text.indexOf('. ./deploy/.env');
expect(check).toBeGreaterThan(-1);
expect(source).toBeGreaterThan(-1);
expect(check).toBeLessThan(source);
// .env 被 source 时 LINENO 指向 .env 的行号,报错必须带上文件名才定位得到
expect(text).toContain('${BASH_SOURCE[0]}');
});
it('install.sh 在迁移前再次预检安装目录里的 .env', () => {
const text = readFileSync(INSTALL_SH, 'utf8');
expect(text).toContain('opendance_validate_env_file "$APP_DIR/deploy/.env"');
});
it('ctl.sh 载入 .env 前调用预检,且引用同目录的 env-lib.sh', () => {
const text = readFileSync(CTL_SH, 'utf8');
expect(text).toContain('"$SCRIPT_DIR/env-lib.sh"');
const check = text.indexOf('opendance_validate_env_file "$APP_DIR/deploy/.env"');
const source = text.indexOf('. "$APP_DIR/deploy/.env"');
expect(check).toBeGreaterThan(-1);
expect(source).toBeGreaterThan(-1);
expect(check).toBeLessThan(source);
});
});
+46 -5
View File
@@ -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(/上跳路径/);
@@ -423,13 +459,18 @@ describe('压缩包导入与转换(用假 Assimp 做对照)', () => {
);
});
it('assimp 不存在时给出可读错误', async () => {
it('assimp 不存在时给出可读错误(含安装命令与替代办法,而不是 spawn ENOENT)', async () => {
const promise = convertModelArchive(pmxArchive(), {
assimpBin: join(workRoot, 'no-such-assimp'),
timeoutMs: 5_000,
});
await expect(promise).rejects.toThrow(/模型转换失败/);
await expect(
convertModelArchive(pmxArchive(), {
assimpBin: join(workRoot, 'no-such-assimp'),
timeoutMs: 5_000,
}),
).rejects.toThrow(/模型转换失败/);
).rejects.toThrow(/apt-get install -y assimp-utils[\s\S]*\.glb \/ \.vrm/);
});
});
+187
View File
@@ -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);
});
});