dsh-game-material-master 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/jsonio.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 新模块共用的 JSON 落盘助手。
3
+ *
4
+ * 三个功能模块(八方向图 / 图片生成 / 序列帧生成)各自独立存目录,
5
+ * 但「原子写 + 读文件 + 日志裁剪」这几件事是一样的,抽在这里避免重复。
6
+ */
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { dirname } from "node:path";
9
+ import { randomUUID } from "node:crypto";
10
+ export async function readJson(file) {
11
+ try {
12
+ return JSON.parse(await readFile(file, "utf8"));
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ /**
19
+ * 先写临时文件再 rename,避免写到一半崩溃留下半个 JSON。
20
+ *
21
+ * 临时文件名必须**每次唯一**:轮询器和用户操作可能同时写同一个 job.json,
22
+ * 共用一个 `.tmp` 名字时,先完成的 rename 会把临时文件移走,后一个就会
23
+ * ENOENT(实测踩过)。
24
+ */
25
+ export async function writeJsonAtomic(file, value) {
26
+ await mkdir(dirname(file), { recursive: true });
27
+ const tmp = `${file}.${randomUUID().slice(0, 8)}.tmp`;
28
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf8");
29
+ await rename(tmp, file);
30
+ }
31
+ export function appendJobLog(log, level, message, limit = 200) {
32
+ log.push({ at: Date.now(), level, message });
33
+ if (log.length > limit)
34
+ log.splice(0, log.length - limit);
35
+ }
36
+ export function messageOf(error) {
37
+ return error instanceof Error ? error.message : String(error);
38
+ }
package/lib/links.js ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * 会话 → 界面的深链接(deep link)。
3
+ *
4
+ * 模型在回复里贴给用户一条 Markdown 超链接,用户点一下就把 Web GUI 切到
5
+ * 「游戏素材大师」工作台,并直接落到对应的模块 / 项目 / 阶段上验收。
6
+ *
7
+ * 链接形态(故意做成普通 http(s) URL,理由见下):
8
+ *
9
+ * http://127.0.0.1:43120/?dsh-gmm=1&module=sprite&project=p1234&stage=videos
10
+ *
11
+ * 为什么必须是 http(s):
12
+ * 会话正文的 Markdown 渲染器对链接做了协议白名单(只放行 http/https/mailto,
13
+ * 见 dsh-client-ui-primitives 的 sanitizeUrl),自定义 scheme 会被丢掉、
14
+ * 连 <a> 都不生成,模型写了也点不动。
15
+ *
16
+ * 为什么带 origin:
17
+ * 浏览器半区在 apply 时把自己真实的 `location.origin` 报给宿主(reportClientOrigin),
18
+ * 宿主据此拼出可点链接。宿主自己并不知道对外 origin(可能被反代改写过)。
19
+ * 没收到过上报时退化成 http://localhost —— 即使 origin 不对也没关系:
20
+ * 浏览器半区装了一个捕获阶段的点击拦截器,只按 **路径与查询参数** 匹配,
21
+ * 命中就 preventDefault 并原地切面板,根本不会发生跳转。
22
+ *
23
+ * 兜底:用户若用中键 / Ctrl+点击 强制新开标签页,链接会真的被浏览器打开,
24
+ * 应用在 `/?dsh-gmm=…` 上正常启动,浏览器半区读取查询参数完成同样的切换。
25
+ * 两条路径共用同一份 `OpenIntent`,所以行为一致。
26
+ */
27
+ /** 深链接的查询参数名。浏览器半区(src/client.ts)里有一份同名常量,改动要同步。 */
28
+ export const OPEN_QUERY_KEY = "dsh-gmm";
29
+ /** 工作台在 `main` 槽里的 key,也是侧栏 `sidebar.panellist` 的 id。 */
30
+ export const PANEL_KEY = "gameStudio";
31
+ /** 四个模块的 key。 */
32
+ export const STUDIO_MODULES = ["sprite", "image", "sequence", "rig"];
33
+ /** 八方向图的四个阶段。 */
34
+ export const SPRITE_STAGES = ["images", "videos", "frames", "sheet"];
35
+ let clientOrigin = "";
36
+ /** 浏览器半区上报真实 origin。只接受 http(s),其它一律忽略。 */
37
+ export function rememberClientOrigin(origin) {
38
+ if (typeof origin !== "string")
39
+ return false;
40
+ let parsed;
41
+ try {
42
+ parsed = new URL(origin);
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
48
+ return false;
49
+ clientOrigin = parsed.origin;
50
+ return true;
51
+ }
52
+ /** 已上报的 origin;没有就返回空串。 */
53
+ export function clientOriginOf() {
54
+ return clientOrigin;
55
+ }
56
+ /**
57
+ * 拼链接用的 origin。
58
+ *
59
+ * 没收到上报时给 `http://localhost`:这个值只影响「链接看起来像什么」,
60
+ * 点击仍然由浏览器半区的拦截器按路径匹配处理,所以错也无害。
61
+ */
62
+ export function originForLinks() {
63
+ return clientOrigin === "" ? "http://localhost" : clientOrigin;
64
+ }
65
+ /** 只保留有意义的字段,保证同一次意图生成同一条链接(便于断言与去重)。 */
66
+ export function normalizeIntent(intent) {
67
+ const out = {};
68
+ if (intent === undefined)
69
+ return out;
70
+ if (intent.module !== undefined && STUDIO_MODULES.includes(intent.module)) {
71
+ out.module = intent.module;
72
+ }
73
+ if (typeof intent.projectId === "string" && intent.projectId !== "")
74
+ out.projectId = intent.projectId;
75
+ if (typeof intent.jobId === "string" && intent.jobId !== "")
76
+ out.jobId = intent.jobId;
77
+ if (typeof intent.stage === "string" && intent.stage !== "")
78
+ out.stage = intent.stage;
79
+ if (typeof intent.direction === "string" && intent.direction !== "")
80
+ out.direction = intent.direction;
81
+ return out;
82
+ }
83
+ /** 意图 → 查询串(不含 `?`)。 */
84
+ export function intentQuery(intent) {
85
+ const normalized = normalizeIntent(intent);
86
+ const params = new URLSearchParams();
87
+ params.set(OPEN_QUERY_KEY, "1");
88
+ for (const key of ["module", "project", "job", "stage", "direction"]) {
89
+ const value = key === "project" ? normalized.projectId : key === "job" ? normalized.jobId : normalized[key];
90
+ if (value !== undefined)
91
+ params.set(key, value);
92
+ }
93
+ return params.toString();
94
+ }
95
+ /** 拼出可点击的绝对链接。 */
96
+ export function buildOpenLink(intent, origin = originForLinks()) {
97
+ return `${origin}/?${intentQuery(intent)}`;
98
+ }
99
+ /**
100
+ * 解析查询串回意图。宿主侧只用于自检与测试——浏览器半区另有一份等价实现
101
+ * (client.ts 是经典脚本,不能 import),两边靠 scripts/verify-tools.mjs 的
102
+ * 文本契约钉住同名参数。
103
+ */
104
+ export function parseIntentQuery(query) {
105
+ const params = new URLSearchParams(query.startsWith("?") ? query.slice(1) : query);
106
+ if (params.get(OPEN_QUERY_KEY) === null)
107
+ return undefined;
108
+ const intent = {};
109
+ const module = params.get("module");
110
+ if (module !== null && STUDIO_MODULES.includes(module))
111
+ intent.module = module;
112
+ const projectId = params.get("project");
113
+ if (projectId !== null)
114
+ intent.projectId = projectId;
115
+ const jobId = params.get("job");
116
+ if (jobId !== null)
117
+ intent.jobId = jobId;
118
+ const stage = params.get("stage");
119
+ if (stage !== null)
120
+ intent.stage = stage;
121
+ const direction = params.get("direction");
122
+ if (direction !== null)
123
+ intent.direction = direction;
124
+ return normalizeIntent(intent);
125
+ }
package/lib/media.js ADDED
@@ -0,0 +1,235 @@
1
+ /**
2
+ * ffmpeg / ffprobe 媒体层。
3
+ *
4
+ * 这里刻意只做「解码成 rawvideo rgba」和「探测时长」两类事:
5
+ * 抠绿与合成都发生在 JS 里(见 chroma.ts),因此不需要任何图像库,
6
+ * 也不需要中间 PNG 往返。
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ import { readFile, writeFile } from "node:fs/promises";
10
+ export class MediaError extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = "MediaError";
14
+ }
15
+ }
16
+ export function ffmpegPath() {
17
+ return process.env.FFMPEG_PATH?.trim() || "ffmpeg";
18
+ }
19
+ export function ffprobePath() {
20
+ return process.env.FFPROBE_PATH?.trim() || "ffprobe";
21
+ }
22
+ /** 跑一次 ffmpeg/ffprobe,stdout 收成 Buffer,stderr 收成字符串。 */
23
+ function run(bin, args, timeoutMs = 300000) {
24
+ return new Promise((resolve, reject) => {
25
+ let child;
26
+ try {
27
+ child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
28
+ }
29
+ catch (error) {
30
+ reject(new MediaError(`无法启动 ${bin}:${error instanceof Error ? error.message : String(error)}`));
31
+ return;
32
+ }
33
+ const out = [];
34
+ let err = "";
35
+ let settled = false;
36
+ const timer = setTimeout(() => {
37
+ if (settled)
38
+ return;
39
+ settled = true;
40
+ child.kill("SIGKILL");
41
+ reject(new MediaError(`${bin} 执行超时(${Math.round(timeoutMs / 1000)} 秒)`));
42
+ }, timeoutMs);
43
+ child.stdout.on("data", (chunk) => out.push(chunk));
44
+ child.stderr.on("data", (chunk) => {
45
+ err += chunk.toString("utf8");
46
+ if (err.length > 20000)
47
+ err = err.slice(-20000);
48
+ });
49
+ child.on("error", (error) => {
50
+ if (settled)
51
+ return;
52
+ settled = true;
53
+ clearTimeout(timer);
54
+ if (error.code === "ENOENT") {
55
+ reject(new MediaError(`找不到 ${bin}。请先安装 ffmpeg(macOS: brew install ffmpeg),或用 FFMPEG_PATH / FFPROBE_PATH 环境变量指定绝对路径。`));
56
+ return;
57
+ }
58
+ reject(new MediaError(`${bin} 启动失败:${error.message}`));
59
+ });
60
+ child.on("close", (code) => {
61
+ if (settled)
62
+ return;
63
+ settled = true;
64
+ clearTimeout(timer);
65
+ if (code !== 0) {
66
+ reject(new MediaError(`${bin} 退出码 ${code}:${err.trim().split("\n").slice(-6).join(" | ") || "无输出"}`));
67
+ return;
68
+ }
69
+ resolve({ stdout: Buffer.concat(out), stderr: err });
70
+ });
71
+ });
72
+ }
73
+ /** 探测媒体时长(秒)。 */
74
+ export async function probeDuration(file) {
75
+ const { stdout } = await run(ffprobePath(), ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file], 60000);
76
+ const seconds = Number.parseFloat(stdout.toString("utf8").trim());
77
+ if (!Number.isFinite(seconds) || seconds <= 0) {
78
+ throw new MediaError(`无法读取视频时长:${file}`);
79
+ }
80
+ return seconds;
81
+ }
82
+ /** 读取图片/视频的像素尺寸(取第一条视频流)。 */
83
+ export async function probeSize(file) {
84
+ const { stdout } = await run(ffprobePath(), ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", file], 60000);
85
+ const [w, h] = stdout.toString("utf8").trim().split("x").map((v) => Number.parseInt(v, 10));
86
+ if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) {
87
+ throw new MediaError(`无法读取尺寸:${file}`);
88
+ }
89
+ return { width: w, height: h };
90
+ }
91
+ function buildVideoFilter(options, duration, width, height) {
92
+ const chain = [];
93
+ const inset = Math.max(0, Math.min(0.2, options.cropInset));
94
+ if (inset > 0) {
95
+ chain.push(`crop=iw*${(1 - 2 * inset).toFixed(4)}:ih*${(1 - 2 * inset).toFixed(4)}`);
96
+ }
97
+ chain.push(`scale=${width}:${height}:flags=lanczos`);
98
+ // fps 滤镜按「时长 / 帧数」取样,正好实现「按时长平均提取 N 张」。
99
+ chain.push(`fps=${options.frameCount}/${duration.toFixed(6)}`);
100
+ chain.push("format=rgba");
101
+ return chain.join(",");
102
+ }
103
+ /** 按长边上限与原始比例算出工作尺寸;宽高都取偶数,规避编码器的奇数尺寸问题。 */
104
+ export function workingSize(sourceWidth, sourceHeight, longEdge) {
105
+ const longest = Math.max(sourceWidth, sourceHeight);
106
+ const scale = longest > longEdge ? longEdge / longest : 1;
107
+ const even = (value) => Math.max(2, Math.round((value * scale) / 2) * 2);
108
+ return { width: even(sourceWidth), height: even(sourceHeight) };
109
+ }
110
+ /**
111
+ * 从视频里按时长平均抽取 frameCount 帧,直接输出成 rawvideo RGBA。
112
+ * 结果按顺序返回,每帧 `width * height * 4` 字节。
113
+ */
114
+ export async function extractFrames(options) {
115
+ const duration = await probeDuration(options.video);
116
+ const source = await probeSize(options.video);
117
+ const size = workingSize(source.width, source.height, Math.max(64, options.longEdge));
118
+ const { stdout } = await run(ffmpegPath(), [
119
+ "-hide_banner",
120
+ "-loglevel", "error",
121
+ "-i", options.video,
122
+ "-vf", buildVideoFilter(options, duration, size.width, size.height),
123
+ "-frames:v", String(options.frameCount),
124
+ "-f", "rawvideo",
125
+ "-pix_fmt", "rgba",
126
+ "-"
127
+ ], options.timeoutMs ?? 300000);
128
+ const frameBytes = size.width * size.height * 4;
129
+ const frames = [];
130
+ for (let i = 0; i < options.frameCount; i++) {
131
+ const start = i * frameBytes;
132
+ if (start + frameBytes > stdout.length)
133
+ break;
134
+ frames.push(Buffer.from(stdout.subarray(start, start + frameBytes)));
135
+ }
136
+ if (frames.length === 0) {
137
+ throw new MediaError(`从视频里没有抽到任何帧:${options.video}`);
138
+ }
139
+ return { frames, width: size.width, height: size.height, duration };
140
+ }
141
+ /**
142
+ * 把一张静态图解码成 RGBA。
143
+ * 抠像只需要像素,不需要 PNG 解码器,所以统一交给 ffmpeg。
144
+ * `maxEdge > 0` 时长边会被限制到该值(等比、取偶数)。
145
+ */
146
+ export async function decodeToRgba(file, maxEdge = 0) {
147
+ const source = await probeSize(file);
148
+ const size = maxEdge > 0 ? workingSize(source.width, source.height, maxEdge) : workingSize(source.width, source.height, Math.max(source.width, source.height));
149
+ const { stdout } = await run(ffmpegPath(), [
150
+ "-hide_banner", "-loglevel", "error",
151
+ "-i", file,
152
+ "-vf", `scale=${size.width}:${size.height}:flags=lanczos,format=rgba`,
153
+ "-frames:v", "1",
154
+ "-f", "rawvideo",
155
+ "-pix_fmt", "rgba",
156
+ "-"
157
+ ], 120000);
158
+ const expected = size.width * size.height * 4;
159
+ if (stdout.length < expected)
160
+ throw new MediaError(`解码后字节数不足:期望 ${expected},实际 ${stdout.length}`);
161
+ return { rgba: Buffer.from(stdout.subarray(0, expected)), width: size.width, height: size.height };
162
+ }
163
+ /** 参考视频要转成 data URI 传给 MiniMax,请求体上限 64MB,所以先卡一道大小。 */
164
+ export async function fileSize(file) {
165
+ const { stdout } = await run(ffprobePath(), ["-v", "error", "-show_entries", "format=size", "-of", "default=noprint_wrappers=1:nokey=1", file], 30000);
166
+ const n = Number.parseInt(stdout.toString("utf8").trim(), 10);
167
+ return Number.isFinite(n) ? n : 0;
168
+ }
169
+ /**
170
+ * 把一张图转成 JPEG data URI,给 MiniMax 当首帧图用。
171
+ * 同时落一份 JPEG 到 `jpegOut`,方便排查「模型到底看到了什么」。
172
+ */
173
+ export async function toJpegDataUri(source, jpegOut, maxEdge = 1280, quality = 3) {
174
+ await run(ffmpegPath(), [
175
+ "-hide_banner",
176
+ "-loglevel", "error",
177
+ "-y",
178
+ "-i", source,
179
+ "-vf", `scale='min(${maxEdge},iw)':-2:flags=lanczos`,
180
+ "-q:v", String(quality),
181
+ "-f", "image2",
182
+ jpegOut
183
+ ], 120000);
184
+ const bytes = await readFile(jpegOut);
185
+ return `data:image/jpeg;base64,${bytes.toString("base64")}`;
186
+ }
187
+ /** 用 ffmpeg 生成一张等比缩放的 PNG 预览图(用于大幅整图的缩略预览)。 */
188
+ export async function makeThumbnail(source, dest, maxEdge = 768) {
189
+ await run(ffmpegPath(), [
190
+ "-hide_banner",
191
+ "-loglevel", "error",
192
+ "-y",
193
+ "-i", source,
194
+ "-vf", `scale='min(${maxEdge},iw)':'min(${maxEdge},ih)':force_original_aspect_ratio=decrease:flags=lanczos`,
195
+ "-pix_fmt", "rgba",
196
+ dest
197
+ ], 120000);
198
+ }
199
+ /** 读取文件并组装成 data URI(Ark 参考图用)。 */
200
+ export async function toDataUri(file, mime) {
201
+ const bytes = await readFile(file);
202
+ return `data:${mime};base64,${bytes.toString("base64")}`;
203
+ }
204
+ /** 按扩展名猜 mime。 */
205
+ export function mimeOf(file) {
206
+ const lower = file.toLowerCase();
207
+ if (lower.endsWith(".png"))
208
+ return "image/png";
209
+ if (lower.endsWith(".jpg") || lower.endsWith(".jpeg"))
210
+ return "image/jpeg";
211
+ if (lower.endsWith(".webp"))
212
+ return "image/webp";
213
+ if (lower.endsWith(".gif"))
214
+ return "image/gif";
215
+ if (lower.endsWith(".bmp"))
216
+ return "image/bmp";
217
+ if (lower.endsWith(".mp4"))
218
+ return "video/mp4";
219
+ return "application/octet-stream";
220
+ }
221
+ /** 写文件的小工具(保持原子替换语义)。 */
222
+ export async function writeBinary(file, bytes) {
223
+ await writeFile(file, bytes);
224
+ }
225
+ /** ffmpeg 是否可用;不可用时给出可读原因。 */
226
+ export async function checkFfmpeg() {
227
+ try {
228
+ const { stdout } = await run(ffmpegPath(), ["-hide_banner", "-version"], 20000);
229
+ const first = stdout.toString("utf8").split("\n")[0]?.trim() ?? "";
230
+ return { ok: true, version: first };
231
+ }
232
+ catch (error) {
233
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
234
+ }
235
+ }