feat(models): 模型压缩包自动转换 + 默认模型写进源码;首次启动 .env 引导;HOST 默认 0.0.0.0

需求 1:模型上传支持压缩包(MMD 模型包)
- common/zip-reader.ts:纯 TS 极简 ZIP 读取器(EOCD/中央目录、STORE+DEFLATE、
  ZIP64 大小字段、Shift-JIS/GBK 文件名回退、拒绝 zip-slip 与加密条目)
- models/model-convert.ts:解压 → 选主模型(指名字/最浅/最大)→ Assimp 导出 FBX
  → **assimp info 回读校验**(Assimp 对带蒙皮大骨架模型会写出损坏文件:
  实测 714 骨骼 PMX 导出退出码 11、产物回读报 FBX-DOM no Objects dictionary found)
  → 失败自动回退 GLB;两种都失败则 422
- models/glb-textures.ts:把 Assimp 写成外部 URI 的贴图内嵌进 GLB 的 BIN chunk,
  保证模型库里单文件即可加载(否则是白模)
- 溯源:压缩包原件存为 model-archive 资产;models 新增 source_asset_id /
  conversion_note(迁移 1789450000000-AddModelConversionFields,已在真实库上
  验证 up/down 可逆)
- 默认模型:转换成功且 autoDefault 不为 false → is_primary=1 + published,
  并把身份(名称/格式/产物 sha256)写进源码 src/config/default-model.ts;
  resolveDefaultModelId 增加 DEFAULT_MODEL_ID 与源码种子两步(按 sha256 匹配,
  换库仍有效),实测库中有 2 个 VRM 时默认模型仍解析为该 GLB
- scripts/import-default-model.mjs:运维 CLI(上传 zip 并写源码 / --write-source-only)
- 修复 multipart 中文文件名乱码(upload.util.decodeUploadName)
- DTO/契约新增 conversionNote、fileSha256;管理端 accept 增加 .zip 并展示转换来源

需求 2:首次启动 .env 引导
- deploy/init-env.sh:交互式逐项填写 8 个键(回车保留默认、口令不回显不加引号、
  端口校验、mysql2 连通性自检且口令只经环境变量传递、只改这 8 个键并保留模板注释、
  chmod 600、结尾打码摘要);--force/--check/-y/-i/--skip-db-check 等开关;
  非交互(-y、OPENDANCE_NONINTERACTIVE、stdin 关闭)绝不提问、读取带超时
- install.sh 缺 .env 时改为调用引导,失败才 die

需求 3:默认监听 0.0.0.0
- 代码默认值、两份 .env 模板、install.sh、init-env.sh 五处一致,并新增测试守护
  (未设置 HOST 时为 0.0.0.0;两份模板都写着 HOST=0.0.0.0)

契约:rest-api / data-models / model-formats → 0.3.0,database → 0.2.0(另两库已同步)

验证:125 项单测通过(7 文件);契约 6 项与 29 条路由一致;typecheck/build 通过;
真实包端到端 HTTP 201 / 0.89s / format=glb / isPrimary=true / published;
GLB 1,152,464 字节、1 mesh / 240 nodes / 1 skin(238 joints) / 2 张内嵌贴图;
迁移 revert→run 实测可逆且数据无损恢复
This commit is contained in:
2026-09-15 13:55:54 +08:00
parent bba5bcf59e
commit e4351c5062
34 changed files with 3204 additions and 65 deletions
+215
View File
@@ -0,0 +1,215 @@
import { execFile } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, extname, join } from 'node:path';
import { promisify } from 'node:util';
import { ModelFormat } from '../common/enums';
import { ZipEntry, readZipEntries } from '../common/zip-reader';
import { embedGlbImages } from './glb-textures';
const run = promisify(execFile);
/**
* 压缩包 → 可入库模型文件的转换。
*
* 典型场景:MMD 模型包(zip 内含 `xxx.pmx` + `textures/`)→ 解压 → 选主模型
* → 调 Assimp 导出 FBX;**Assimp 的 FBX 导出器对带蒙皮的大骨架模型会写坏文件**
* (实测 Miku PMX:导出退出码 11,产出的 FBX 回读报 `FBX-DOM no Objects dictionary found`),
* 因此导出后必须回读校验,失败则回退 GLB,并把过程写进 conversionNote。
*
* 转换后的 GLB 还会把 Assimp 写成外部 URI 的贴图内嵌进二进制块,
* 保证模型库里一个文件就能独立加载(否则是白模)。
*/
export interface ConvertOptions {
/** Assimp 可执行文件(默认 `assimp`,可用 ASSIMP_BIN 覆盖) */
assimpBin: string;
/** 单次转换超时(毫秒) */
timeoutMs?: number;
/** 优先尝试的格式 */
preferFormat?: 'fbx' | 'glb';
/** 优先选用的 PMX 文件名(大小写不敏感),例如 `Hatsune Miku.pmx` */
preferredPmx?: string;
}
export interface ConvertedModel {
/** 转换产物内容 */
buffer: Buffer;
/** 产物格式(fbx 或 glb) */
format: ModelFormat;
/** 实际使用的 pmx 相对路径 */
sourceModelPath: string;
/** 人类可读的转换说明,写入 models.conversion_note */
note: string;
/** 逐步尝试记录,便于排障 */
attempts: string[];
}
const DEFAULT_TIMEOUT_MS = 180_000;
/** 选择主模型:优先指名字,其次目录最浅,最后文件最大 */
export function pickModelFile(
entries: readonly ZipEntry[],
preferred?: string,
): ZipEntry | undefined {
const models = entries.filter((entry) => extname(entry.path).toLowerCase() === '.pmx');
if (models.length === 0) return undefined;
const wanted = preferred?.trim().toLowerCase();
if (wanted) {
const exact = models.find((entry) => entry.path.toLowerCase() === wanted);
if (exact) return exact;
const byBase = models.find(
(entry) => entry.path.split('/').pop()?.toLowerCase() === wanted,
);
if (byBase) return byBase;
}
return [...models].sort((a, b) => {
const depthA = a.path.split('/').length;
const depthB = b.path.split('/').length;
if (depthA !== depthB) return depthA - depthB;
return b.size - a.size;
})[0];
}
/** 解压到工作目录,同时保留内容供贴图内嵌使用 */
async function unpack(
entries: readonly ZipEntry[],
targetDir: string,
): Promise<Map<string, Buffer>> {
const contents = new Map<string, Buffer>();
for (const entry of entries) {
const data = entry.read();
contents.set(entry.path, data);
const destination = join(targetDir, entry.path);
await mkdir(dirname(destination), { recursive: true });
await writeFile(destination, data);
}
return contents;
}
/** 在解压结果里按 glTF 的 uri 找贴图(容错反斜杠与大小写) */
function makeResolver(contents: Map<string, Buffer>) {
const lowered = new Map<string, Buffer>();
for (const [path, data] of contents) lowered.set(path.replace(/\\/g, '/').toLowerCase(), data);
return (uri: string): Buffer | null => {
if (uri.startsWith('data:')) return null;
let decoded = uri;
try {
decoded = decodeURIComponent(uri);
} catch {
/* 保持原样 */
}
const normalized = decoded.replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase();
const direct = lowered.get(normalized);
if (direct) return direct;
const base = normalized.split('/').pop();
if (!base) return null;
for (const [path, data] of lowered) {
if (path.split('/').pop() === base) return data;
}
return null;
};
}
/** 用 Assimp 导出到指定格式,并回读校验(回读失败视为转换失败) */
async function exportAndValidate(
assimpBin: string,
modelPath: string,
outPath: string,
timeoutMs: number,
): Promise<{ ok: boolean; detail: string }> {
try {
await run(assimpBin, ['export', modelPath, outPath], { timeout: timeoutMs, maxBuffer: 8 << 20 });
} catch (error) {
const err = error as { code?: number | string; stderr?: string; message?: string };
const detail = err.stderr?.trim() || err.message || String(error);
return { ok: false, detail: `导出失败(${err.code ?? 'unknown'}):${detail.slice(0, 300)}` };
}
let size = 0;
try {
size = (await readFile(outPath)).length;
} catch {
return { ok: false, detail: '导出命令返回成功但没有产出文件' };
}
if (size === 0) return { ok: false, detail: '导出产物为空文件' };
// 关键校验:Assimp 的 FBX 导出器会"写出一个坏文件但退出码非 0",
// 必须用 info 回读确认,否则会把损坏文件入库。
try {
await run(assimpBin, ['info', outPath], { timeout: timeoutMs, maxBuffer: 8 << 20 });
} catch (error) {
const err = error as { stderr?: string; message?: string };
const detail = err.stderr?.trim() || err.message || String(error);
return { ok: false, detail: `产物无法回读(已判定损坏):${detail.slice(0, 300)}` };
}
return { ok: true, detail: `产物 ${size} 字节,回读校验通过` };
}
/** 压缩包 → 模型文件(FBX 优先,失败回退 GLB) */
export async function convertModelArchive(
archive: Buffer,
options: ConvertOptions,
): Promise<ConvertedModel> {
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const prefer = options.preferFormat ?? 'fbx';
const entries = readZipEntries(archive);
if (entries.length === 0) throw new Error('压缩包是空的');
const modelEntry = pickModelFile(entries, options.preferredPmx);
if (!modelEntry) {
throw new Error('压缩包里没有找到 .pmx 模型文件(当前只支持 MMD 的 PMX 模型包)');
}
const workDir = await mkdtemp(join(tmpdir(), 'opendance-model-'));
const attempts: string[] = [];
try {
const contents = await unpack(entries, workDir);
const modelPath = join(workDir, modelEntry.path);
const order: Array<'fbx' | 'glb'> =
prefer === 'glb' ? ['glb', 'fbx'] : ['fbx', 'glb'];
for (const target of order) {
const outPath = join(workDir, `converted.${target}`);
const result = await exportAndValidate(options.assimpBin, modelPath, outPath, timeoutMs);
attempts.push(`${target.toUpperCase()}:${result.detail}`);
if (!result.ok) continue;
let buffer: Buffer = await readFile(outPath);
let extra = '';
if (target === 'glb') {
// 贴图内嵌是"锦上添花":即便结构不符合预期也不能让整次转换失败
try {
const embedded = embedGlbImages(buffer, makeResolver(contents));
buffer = Buffer.from(embedded.glb);
if (embedded.embedded > 0) extra = `,已内嵌 ${embedded.embedded} 张贴图`;
if (embedded.unresolved.length > 0) {
extra += `(${embedded.unresolved.length} 张贴图未找到:${embedded.unresolved
.slice(0, 3)
.join('、')})`;
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
extra = `(贴图内嵌跳过:${message.slice(0, 120)})`;
}
}
const note = `${modelEntry.path} → ${target.toUpperCase()}${extra}`;
return {
buffer,
format: target === 'fbx' ? ModelFormat.Fbx : ModelFormat.Glb,
sourceModelPath: modelEntry.path,
note,
attempts,
};
}
throw new Error(
`模型转换失败:${attempts.join(';')}。` +
'请确认服务器已安装 Assimp(ASSIMP_BIN),或直接上传 .glb / .vrm 文件。',
);
} finally {
await rm(workDir, { recursive: true, force: true });
}
}