dsh-game-material-master 0.7.0 → 0.9.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/index.js CHANGED
@@ -20,23 +20,31 @@ import { DEFAULT_ROW_ORDER, DIRECTION_KEYS, TURN_DIRECTION_DEFAULT, TURN_FRAME_C
20
20
  import { checkFfmpeg } from "./media.js";
21
21
  import { testArk } from "./ark.js";
22
22
  import { customImageBlocker, imageModelOf, imageProviderBlocker, imageProviderSummary, isCustomProvider, testCustomImage } from "./imageprovider.js";
23
+ import { detectComfyBindings, fetchComfyObjectInfo, formatBinding, normalizeComfyBaseUrl, normalizeComfyCookies, parseComfyWorkflow, testComfy } from "./comfy.js";
23
24
  import { COMP_SHARE_BASE_URL, COMP_SHARE_MODEL_ID, capabilityOf, isCompshareModel, normalizeDuration, normalizeResolution, pathPrefixOf, testMiniMax } from "./minimax.js";
24
- import { applyTurnPicks, clearVideos, disposePipeline, ensurePoller, exportImages, importLocalVideo, listJobs, pollVideosOnce, resetFramePicks, resetTurnPicks, setFramePick, setFramePicks, setImageMode, setTurnPick, setTurnPicks, startAllImages, startCompose, startFramePick, startExtract, startImage, startRekey, startTurnFrames, startTurnVideo, startVideos } from "./pipeline.js";
25
- import { assetPath, createProject, deleteProject, listProjects, log, patchProject, projectDir, projectExists, readProject, } from "./store.js";
25
+ import { activatePipeline, applyTurnPicks, clearVideos, disposePipeline, ensurePoller, exportImages, importLocalVideo, listJobs, pollVideosOnce, resetFramePicks, resetTurnPicks, setFramePick, setFramePicks, setImageMode, setTurnPick, setTurnPicks, startAllImages, startCompose, startFramePick, startExtract, startImage, startRekey, startTurnFrames, startTurnVideo, startVideos } from "./pipeline.js";
26
+ import { assetPath, createProject, deleteProject, listProjects, log, patchProject, projectDir, projectExists, readProject, resetDerivedFromSource, } from "./store.js";
26
27
  import * as imagegen from "./imagegen.js";
27
28
  import * as seqgen from "./seqgen.js";
28
29
  import * as riggen from "./riggen.js";
29
30
  import * as tilegen from "./tilegen.js";
30
31
  import * as mapgen from "./mapgen.js";
32
+ import * as musicgen from "./musicgen.js";
33
+ import * as sfxgen from "./sfxgen.js";
34
+ import { musicGuidePayload } from "./musicguide.js";
35
+ import { musicScoreGuidePayload } from "./musicscoreguide.js";
36
+ import { clearScoreDepsCache, detectScoreDeps } from "./musicscore.js";
37
+ import { musicBlocker, musicEngineSummary, testMusicConnection } from "./musicapi.js";
38
+ import { SFX_FORMATS, SFX_LIMITS, SFX_SAMPLE_RATES, sfxBlocker, testSfxConnection } from "./sfxapi.js";
31
39
  import { MANIFEST, METHODS, SERVICE_NAME } from "./wire.js";
32
- import { rememberClientOrigin } from "./links.js";
40
+ import { assetBasePath, originForLinks, rememberClientOrigin } from "./links.js";
33
41
  import { registerStudioTools } from "./tools.js";
34
42
  /**
35
43
  * 游戏素材大师 —— 宿主半区。
36
44
  *
37
- * 一个 Typert 远程服务("gameStudio")承载五个功能模块的控制面:
45
+ * 一个 Typert 远程服务("gameStudio")承载八个功能模块的控制面:
38
46
  * ① 八方向图生成 ② 图片生成 ③ 序列帧生成 ④ 骨骼动画生成 ⑤ 地图地块生成
39
- * 五者共用同一套配置(API Key / 模型 / 抠像默认值),但各自独立存项目。
47
+ * 八者共用同一套配置(各平台的 API Key / 模型 / 抠像默认值),但各自独立存项目 / 任务。
40
48
  *
41
49
  * 另外用 `ctx.webServer` 注册一条 prefix 路由,把各模块的产物直接发给浏览器。
42
50
  */
@@ -171,6 +179,22 @@ const MIME_TYPES = {
171
179
  ".bmp": "image/bmp",
172
180
  ".mp4": "video/mp4",
173
181
  ".webm": "video/webm",
182
+ // 音乐模块(模块七):音频 / 工具产物。少了这些,浏览器会把音频当 octet-stream,
183
+ // <audio> 的拖动进度与时长都可能异常。
184
+ ".mp3": "audio/mpeg",
185
+ ".wav": "audio/wav",
186
+ ".m4a": "audio/mp4",
187
+ ".aac": "audio/aac",
188
+ ".flac": "audio/flac",
189
+ ".ogg": "audio/ogg",
190
+ ".opus": "audio/ogg",
191
+ ".mid": "audio/midi",
192
+ ".midi": "audio/midi",
193
+ ".py": "text/x-python; charset=utf-8",
194
+ ".pdf": "application/pdf",
195
+ ".xml": "application/xml; charset=utf-8",
196
+ ".musicxml": "application/vnd.recordare.musicxml+xml; charset=utf-8",
197
+ ".lrc": "text/plain; charset=utf-8",
174
198
  ".json": "application/json; charset=utf-8",
175
199
  // 模块六的导出包:`.zip` 少了这一条会掉进 octet-stream —— 浏览器照样存得下来,
176
200
  // 但少了这个类型,某些浏览器/壳会把「另存为」的默认扩展名写错。
@@ -275,6 +299,30 @@ export class GameStudioGateway extends TypertRemoteService {
275
299
  // 分辨率档位与时长区间都跟着模型走,界面据此渲染控件;优云智算版更宽。
276
300
  minimaxCapabilities: capabilityOf(config.minimaxModel),
277
301
  minimaxCapabilitiesByModel: Object.fromEntries(MINIMAX_MODEL_PRESETS.map((preset) => [preset.id, capabilityOf(preset.id)])),
302
+ /** 音乐生成编辑(模块七):引擎/模型预设、Key 阻塞原因、文档地址。 */
303
+ musicEngines: musicEngineSummary(),
304
+ musicBlocker: musicBlocker(config) ?? null,
305
+ /** 音效生成(模块八,火山引擎 Seed-Audio):格式/采样率/限制与 Key 阻塞原因。 */
306
+ sfxBlocker: sfxBlocker(config) ?? null,
307
+ sfxFormats: SFX_FORMATS.map((format) => ({
308
+ id: format,
309
+ label: format === "mp3"
310
+ ? "MP3(体积小,适合预览 / 网页)"
311
+ : format === "wav"
312
+ ? "WAV(无损,游戏引擎常用)"
313
+ : "Ogg Opus(体积更小)"
314
+ })),
315
+ sfxSampleRates: [...SFX_SAMPLE_RATES],
316
+ sfxLimits: { ...SFX_LIMITS },
317
+ sfxModelPresets: [
318
+ { id: "seed-audio-1.0", label: "seed-audio-1.0(默认 · 音效 / 环境音 / 角色配音)" }
319
+ ],
320
+ sfxDocsUrl: "https://docs.volcengine.com/docs/DoubaoVoice/audio-generation-http",
321
+ sfxConsoleUrl: "https://console.volcengine.com/speech/new/setting/apikeys",
322
+ /** 谱曲模式依赖(Python / scoremill / FluidSynth / SoundFont / ffmpeg)。 */
323
+ musicScoreStatus: await detectScoreDeps(config),
324
+ musicDocsUrl: "https://api.yourmusic.fun/docs",
325
+ musicConsoleUrl: "https://api.yourmusic.fun/dashboard",
278
326
  directions: DIRECTION_KEYS.map((key) => {
279
327
  const direction = directionOf(key);
280
328
  return { key, label: direction?.label ?? key, refs: direction?.refs ?? [] };
@@ -319,6 +367,34 @@ export class GameStudioGateway extends TypertRemoteService {
319
367
  "minimaxResolution",
320
368
  "minimaxPromptOptimizer",
321
369
  "minimaxTimeoutMs",
370
+ // 本地 ComfyUI 后端(videogen.ts 按 comfyVideo 分派)。
371
+ "comfyVideo",
372
+ "comfyBaseUrl",
373
+ "comfyWorkflow",
374
+ "comfyPromptTarget",
375
+ "comfyFirstFrameTarget",
376
+ "comfyWidth",
377
+ "comfyHeight",
378
+ "comfySeconds",
379
+ "comfySeed",
380
+ "comfyTimeoutMs",
381
+ // 音乐生成编辑(模块七)。Key 不进这里(见下面单独处理)。
382
+ "musicProvider",
383
+ "musicBaseUrl",
384
+ "musicModel",
385
+ "musicTimeoutMs",
386
+ "musicPollTimeoutMs",
387
+ // 谱曲模式依赖路径(空 = 自动探测)。
388
+ "musicPythonPath",
389
+ "musicFluidsynthPath",
390
+ "musicSoundfontPath",
391
+ // 音效生成(模块八)。Key 同样不进这里(见下面单独处理)。
392
+ "sfxProvider",
393
+ "sfxBaseUrl",
394
+ "sfxModel",
395
+ "sfxFormat",
396
+ "sfxSampleRate",
397
+ "sfxTimeoutMs",
322
398
  "cellWidth",
323
399
  "cellHeight",
324
400
  "frameCount",
@@ -350,14 +426,32 @@ export class GameStudioGateway extends TypertRemoteService {
350
426
  patch.minimaxApiKey = input.minimaxApiKey.trim();
351
427
  if (typeof input.customApiKey === "string")
352
428
  patch.customApiKey = input.customApiKey.trim();
429
+ // 音乐模块的 Key 与其它凭据同一套约定:不带 = 保持原值,带串 = 覆盖。
430
+ if (typeof input.musicApiKey === "string")
431
+ patch.musicApiKey = input.musicApiKey.trim();
432
+ // 音效模块的 Key 是**语音控制台**的 API Key(X-Api-Key),与方舟 Key 不同源。
433
+ if (typeof input.sfxApiKey === "string")
434
+ patch.sfxApiKey = input.sfxApiKey.trim();
353
435
  if (input.clearArkApiKey === true)
354
436
  patch.arkApiKey = "";
355
437
  if (input.clearMinimaxApiKey === true)
356
438
  patch.minimaxApiKey = "";
357
439
  if (input.clearCustomApiKey === true)
358
440
  patch.customApiKey = "";
441
+ if (input.clearMusicApiKey === true)
442
+ patch.musicApiKey = "";
443
+ if (input.clearSfxApiKey === true)
444
+ patch.sfxApiKey = "";
445
+ // ComfyUI 的 Cookie 也是凭据,与 API Key 同一套约定:不带 = 保持原值,带串 = 覆盖,
446
+ // clearComfyCookies = 清空。它**不进** directKeys——那里是原样透传,Cookie 要先归一化。
447
+ if (typeof input.comfyCookies === "string")
448
+ patch.comfyCookies = normalizeComfyCookies(input.comfyCookies);
449
+ if (input.clearComfyCookies === true)
450
+ patch.comfyCookies = "";
359
451
  const saved = await saveConfig(patch);
360
452
  this.ffmpegCache = undefined;
453
+ // 谱曲依赖路径可能变了;下一次 getConfig / testMusicScore 重新探测。
454
+ clearScoreDepsCache();
361
455
  return this.decorateConfig(saved);
362
456
  }
363
457
  async testArk() {
@@ -385,15 +479,119 @@ export class GameStudioGateway extends TypertRemoteService {
385
479
  });
386
480
  }
387
481
  /**
388
- * 浏览器半区上报自己的 `location.origin`。
482
+ * 【本地 ComfyUI】连接自检:读 `/system_stats` 与 `/queue`,不排队生图,不产生费用。
483
+ *
484
+ * 顺带报一次「工作流里探测到的注入点」——设置页只填 URL 和工作流,绑定对不对
485
+ * 全靠这一步看得见;后面生成时用的就是同一套探测。
486
+ */
487
+ async testComfy() {
488
+ const config = await loadConfig();
489
+ const status = await testComfy({
490
+ baseUrl: config.comfyBaseUrl,
491
+ timeoutMs: config.comfyTimeoutMs,
492
+ cookies: config.comfyCookies
493
+ });
494
+ let nodes = 0;
495
+ let bindings;
496
+ let notes = [];
497
+ const parsed = parseComfyWorkflow(config.comfyWorkflow);
498
+ if (parsed.ok === true) {
499
+ nodes = parsed.nodes;
500
+ // 连节点定义一起查:这样预览里能看到「工作流里没连、但接得下 IMAGE」的首帧注入点,
501
+ // 与真正提交时的探测口径完全一致。
502
+ const info = await fetchComfyObjectInfo({ baseUrl: config.comfyBaseUrl, timeoutMs: config.comfyTimeoutMs, cookies: config.comfyCookies }, Object.keys(parsed.workflow).map((id) => parsed.workflow[id]?.class_type ?? "")).catch(() => undefined);
503
+ const detected = detectComfyBindings(parsed.workflow, {
504
+ prompt: config.comfyPromptTarget,
505
+ first: config.comfyFirstFrameTarget
506
+ }, info);
507
+ bindings = {
508
+ prompt: formatBinding(detected.bindings.prompt),
509
+ first: formatBinding(detected.bindings.first),
510
+ last: formatBinding(detected.bindings.last),
511
+ width: formatBinding(detected.bindings.width),
512
+ height: formatBinding(detected.bindings.height),
513
+ seconds: formatBinding(detected.bindings.seconds),
514
+ seed: formatBinding(detected.bindings.seed)
515
+ };
516
+ notes = detected.notes;
517
+ // 界面格式(官方示例工作流就是这种)会在解析时自动转成 API 格式,这一步说出来,
518
+ // 免得用户以为自己粘错了。
519
+ if (parsed.converted === true) {
520
+ notes = [`检测到 ComfyUI 界面格式的工作流,已自动转成 API 格式(${parsed.nodes} 个节点)。`, ...notes];
521
+ if ((parsed.droppedWidgets ?? 0) > 0)
522
+ notes.push(`有 ${parsed.droppedWidgets} 个控件值没能对应到输入名(这份工作流导出的版本比较老)。建议在 ComfyUI 里用「工作流 → 导出(API) / Save (API Format)」重新导出。`);
523
+ }
524
+ }
525
+ else {
526
+ notes = [`工作流无法解析:${parsed.error}`];
527
+ }
528
+ return {
529
+ baseUrl: normalizeComfyBaseUrl(config.comfyBaseUrl),
530
+ version: status.version,
531
+ device: status.device ?? "",
532
+ queueRunning: status.queueRunning,
533
+ queuePending: status.queuePending,
534
+ nodes,
535
+ bindings,
536
+ notes
537
+ };
538
+ }
539
+ /**
540
+ * 【谱乐 AI】连接自检:读一页历史,不生成、不排队、不扣生成积分。
541
+ * 402 视为「Key 有效但积分不足」,由 `testMusicConnection` 用 warning 表达。
542
+ */
543
+ async testMusic() {
544
+ const config = await loadConfig();
545
+ if (config.musicApiKey.trim() === "")
546
+ throw new Error("尚未配置谱乐 AI API Key");
547
+ const result = await testMusicConnection({
548
+ baseUrl: config.musicBaseUrl,
549
+ apiKey: config.musicApiKey,
550
+ timeoutMs: config.musicTimeoutMs
551
+ });
552
+ return {
553
+ ...result,
554
+ baseUrl: config.musicBaseUrl,
555
+ model: config.musicModel
556
+ };
557
+ }
558
+ /**
559
+ * 【火山引擎 Seed-Audio】连接自检:真实生成一条极短音效。
560
+ *
561
+ * 没有免费的探活端点;读历史 / 模型列表都不能证明「Key 能生成」。设置页按钮
562
+ * 必须写明会产生少量费用。
563
+ */
564
+ async testSfx() {
565
+ const config = await loadConfig();
566
+ const blocker = sfxBlocker(config);
567
+ if (blocker !== undefined)
568
+ throw new Error(blocker);
569
+ const result = await testSfxConnection({
570
+ baseUrl: config.sfxBaseUrl,
571
+ apiKey: config.sfxApiKey,
572
+ model: config.sfxModel,
573
+ timeoutMs: Math.min(config.sfxTimeoutMs, 180000)
574
+ });
575
+ return {
576
+ ...result,
577
+ baseUrl: config.sfxBaseUrl,
578
+ model: config.sfxModel
579
+ };
580
+ }
581
+ /**
582
+ * 浏览器半区上报自己的 `location.origin` 与应用路径前缀。
389
583
  *
390
584
  * 宿主不知道对外 origin(可能被反代改写),而模型要在回复里贴可点链接,
391
- * 只能由页面自己报一次。返回体里回带上「认没认」,方便界面自检。
585
+ * 只能由页面自己报一次。`path` 是 DSH 0.2.1 `--public-url` 的路径前缀
586
+ * (例如挂在 `https://host/prefix/` 时是 `/prefix`),宿主据此拼回链与
587
+ * 产物地址。返回体里回带上「认没认」,方便界面自检。
392
588
  */
393
589
  async reportClientOrigin(payload) {
394
- const origin = asString(asRecord(payload).origin);
395
- const accepted = rememberClientOrigin(origin);
396
- return accepted ? { ok: true, origin } : { ok: false, message: `拒绝非 http(s) origin:${origin}` };
590
+ const input = asRecord(payload);
591
+ const origin = asString(input.origin);
592
+ const path = typeof input.path === "string" ? input.path : undefined;
593
+ const accepted = rememberClientOrigin(origin, path);
594
+ return accepted ? { ok: true, origin, path: path ?? "" } : { ok: false, message: `拒绝非 http(s) origin:${origin}` };
397
595
  }
398
596
  // ── 项目 ────────────────────────────────────────────────────────────────
399
597
  async listProjects() {
@@ -421,7 +619,7 @@ export class GameStudioGateway extends TypertRemoteService {
421
619
  return {
422
620
  ...project,
423
621
  jobs: listJobs(projectId),
424
- assetBase: `${ROUTE_PREFIX}/assets/${projectId}/`
622
+ assetBase: assetBasePath(`${ROUTE_PREFIX}/assets/${projectId}/`)
425
623
  };
426
624
  }
427
625
  async deleteProject(payload) {
@@ -465,7 +663,11 @@ export class GameStudioGateway extends TypertRemoteService {
465
663
  project.source = { file: relative, name: originalName };
466
664
  log(project, "info", `已上传源图:${originalName}(${(bytes.length / 1024).toFixed(0)} KB)`);
467
665
  });
468
- return { ok: true, file: relative, name: originalName };
666
+ // 换了源图 = 阶段①重来:八个方向图 / 转圈视频 / 候选帧 / 阶段②③④的产物
667
+ // 都是上一张图跑出来的。不清掉的话 turnFirstFrame() 会继续拿旧的方向图当首帧,
668
+ // 新源图根本进不了模型——表现就是「换了源图,生成结果一点没变」。
669
+ const discarded = await resetDerivedFromSource(projectId);
670
+ return { ok: true, file: relative, name: originalName, discarded };
469
671
  }
470
672
  /**
471
673
  * 选用一段**本地视频**(用户自己选的,不走远程生成)。
@@ -484,7 +686,7 @@ export class GameStudioGateway extends TypertRemoteService {
484
686
  const project = await readProject(projectId);
485
687
  return {
486
688
  ...pack,
487
- assetBase: `${ROUTE_PREFIX}/assets/${projectId}/`,
689
+ assetBase: assetBasePath(`${ROUTE_PREFIX}/assets/${projectId}/`),
488
690
  name: project?.name ?? projectId
489
691
  };
490
692
  }
@@ -719,6 +921,23 @@ export class GameStudioGateway extends TypertRemoteService {
719
921
  });
720
922
  return { ok: true, id, module, reviewMode };
721
923
  }
924
+ // 音乐生成编辑(模块七)。**别重犯 rig / tile / map 那三个漏**:wire 的
925
+ // module 枚举、tools 的模块表与这里必须成对加。
926
+ if (module === "music") {
927
+ await musicgen.patchMusicJob(id, (job) => {
928
+ job.reviewMode = reviewMode;
929
+ musicgen.musicLog(job, "info", `审核模式:${reviewMode === "manual" ? "每一步人工审核" : "agent 自动审核"}`);
930
+ });
931
+ return { ok: true, id, module, reviewMode };
932
+ }
933
+ // 音效生成(模块八)。同样:wire 的 module 枚举、tools 的模块表与这里必须成对加。
934
+ if (module === "sfx") {
935
+ await sfxgen.patchSfxJob(id, (job) => {
936
+ job.reviewMode = reviewMode;
937
+ sfxgen.sfxLog(job, "info", `审核模式:${reviewMode === "manual" ? "每一步人工审核" : "agent 自动审核"}`);
938
+ });
939
+ return { ok: true, id, module, reviewMode };
940
+ }
722
941
  throw new Error(`未知模块:${module}`);
723
942
  }
724
943
  // ── 地图地块生成(模块五)──────────────────────────────────────────────
@@ -1036,22 +1255,70 @@ export class GameStudioGateway extends TypertRemoteService {
1036
1255
  const result = await mapgen.importMapTileset(asString(input.projectId), asString(input.name), asString(input.data), {
1037
1256
  cell: input.cell,
1038
1257
  shape: input.shape,
1039
- animRows: input.animRows
1258
+ animRows: input.animRows,
1259
+ // 素材自己的播放速度:0.5~30 帧/秒;留空 = 跟全局(校验在 mapgen.parseAssetFps 里)。
1260
+ fps: input.fps,
1261
+ // 把大图缩到格子时的清晰度与倍数(校验在 mapgen.parseClarity / parseAssetScale 里)。
1262
+ clarity: input.clarity,
1263
+ scale: input.scale,
1264
+ // 会动的素材怎么循环(校验在 mapgen.parseAssetLoop 里)。
1265
+ loop: input.loop,
1266
+ // 整图规格(给了它就是整图;校验在 mapgen.parseStampSpec 里)。
1267
+ stamp: input.stamp,
1268
+ // 整图:导入时抠绿幕(手动那条路;AI 那条在 composeMapAsset 里已经抠过)。
1269
+ stampKey: input.stampKey
1040
1270
  });
1041
- return { tilesets: result.tilesets.map(mapTilesetBrief), warnings: result.warnings };
1271
+ // `rev` 不在 project.json 里(派生数据),要在回给界面时现取 —— 少了它重烘后界面会拿旧缓存图。
1272
+ const revisions = await mapgen.tilesetRevisions(asString(input.projectId));
1273
+ return {
1274
+ tilesets: result.tilesets.map((tileset) => ({ ...mapTilesetBrief(tileset), rev: revisions.get(tileset.id) })),
1275
+ warnings: result.warnings
1276
+ };
1042
1277
  }
1043
1278
  /** 内置素材:本机现算,零成本(4 张自动连接图 + 1 张道具图)。 */
1044
1279
  async importSampleTileset(payload) {
1045
1280
  const result = await mapgen.importSampleTileset(asString(asRecord(payload).projectId));
1046
1281
  return { tilesets: result.tilesets.map(mapTilesetBrief), warnings: result.warnings };
1047
1282
  }
1283
+ /**
1284
+ * 整理 AI 生成的那几张图 → 一张落在 `ai/` 的待确认素材图。
1285
+ *
1286
+ * `shape`(普通 / 整格 / 拼块)是**生图前就定好的计划**:宿主按它把图规整成地图
1287
+ * 编辑器要的几何。只整理、不导入 —— 素材属性在新增那一刻定死,所以交给用户在
1288
+ * 「新增素材」窗口里确认一次(界面按返回的 openUrl 把图预选好、用法也预选好)。
1289
+ */
1290
+ async composeMapAsset(payload) {
1291
+ const input = asRecord(payload);
1292
+ const files = Array.isArray(input.files) ? input.files.map((file) => asString(file)) : [];
1293
+ return mapgen.composeMapAsset({
1294
+ projectId: asString(input.projectId),
1295
+ name: asString(input.name),
1296
+ files,
1297
+ shape: input.shape,
1298
+ cell: input.cell,
1299
+ animRows: input.animRows === true ? true : input.animRows === false ? false : undefined,
1300
+ // 整图:占几格(校验在 mapgen.parseStampSpec 里;不给就按 3×3 常见尺寸?不 —— 明确报错)。
1301
+ stampCols: input.stampCols,
1302
+ stampRows: input.stampRows
1303
+ });
1304
+ }
1305
+ async recomposeMapTileset(payload) {
1306
+ const input = asRecord(payload);
1307
+ return mapgen.recomposeMapTileset(asString(input.projectId), asString(input.tilesetId), {
1308
+ files: Array.isArray(input.files) ? input.files.map((file) => String(file)) : undefined,
1309
+ clarity: input.clarity
1310
+ });
1311
+ }
1048
1312
  async saveMapTileset(payload) {
1049
1313
  const input = asRecord(payload);
1050
1314
  const result = await mapgen.saveMapTileset(asString(input.projectId), asString(input.tilesetId), {
1051
1315
  name: typeof input.name === "string" ? input.name : undefined,
1052
1316
  cell: input.cell === undefined ? undefined : { width: Number(asRecord(input.cell).width), height: Number(asRecord(input.cell).height) },
1053
1317
  shape: mapgen.parseTilesetShape(input.shape),
1054
- animRows: typeof input.animRows === "boolean" ? input.animRows : undefined
1318
+ animRows: typeof input.animRows === "boolean" ? input.animRows : undefined,
1319
+ // `null` = 清掉自己的速度(跟全局);`undefined` = 这次不动它。
1320
+ fps: input.fps === undefined ? undefined : input.fps === null ? null : Number(input.fps),
1321
+ loop: input.loop
1055
1322
  });
1056
1323
  return { tileset: mapTilesetBrief(result.tileset), warnings: result.warnings };
1057
1324
  }
@@ -1105,7 +1372,8 @@ export class GameStudioGateway extends TypertRemoteService {
1105
1372
  view: { x: Number(view.x) || 0, y: Number(view.y) || 0, width: Number(view.width) || 0, height: Number(view.height) || 0 },
1106
1373
  have: mapHave(input.have),
1107
1374
  layerIds: Array.isArray(input.layerIds) ? input.layerIds.map((entry) => Number(entry)) : undefined,
1108
- pending: Array.isArray(input.pending) ? input.pending : undefined
1375
+ pending: Array.isArray(input.pending) ? input.pending : undefined,
1376
+ pass: input.pass === true
1109
1377
  });
1110
1378
  }
1111
1379
  /** 一键生成:整层一次提交(一次撤销就能回去),同种子逐字节可复现。 */
@@ -1262,7 +1530,7 @@ export class GameStudioGateway extends TypertRemoteService {
1262
1530
  }
1263
1531
  async prepareFramePick(payload) {
1264
1532
  const input = asRecord(payload);
1265
- const count = input.count === undefined || input.count === null ? undefined : clampInt(input.count, 32, 8, 64);
1533
+ const count = input.count === undefined || input.count === null ? undefined : clampInt(input.count, 32, TURN_FRAME_COUNT_MIN, TURN_FRAME_COUNT_MAX);
1266
1534
  return startFramePick(asString(input.projectId), asString(input.key), count);
1267
1535
  }
1268
1536
  async setFramePick(payload) {
@@ -1413,7 +1681,12 @@ export class GameStudioGateway extends TypertRemoteService {
1413
1681
  const job = await imagegen.readImageJob(jobId);
1414
1682
  if (job === undefined)
1415
1683
  throw new Error(`任务不存在:${jobId}`);
1416
- return { ...job, assetBase: `${ROUTE_PREFIX}/image-assets/${jobId}/` };
1684
+ /**
1685
+ * `dir` 是**本机绝对目录**:对话里的 agent 要把生成结果交给别的模块
1686
+ * (例如 `composeMapAsset` 整理地图素材),而 `assetBase` 是给浏览器用的 URL。
1687
+ * 产物绝对路径 = `dir + "/" + item.file`(`out/img-00.png`)。
1688
+ */
1689
+ return { ...job, dir: imagegen.imageJobDir(jobId), assetBase: assetBasePath(`${ROUTE_PREFIX}/image-assets/${jobId}/`) };
1417
1690
  }
1418
1691
  async deleteImageJob(payload) {
1419
1692
  await imagegen.deleteImageJob(asString(asRecord(payload).jobId));
@@ -1519,7 +1792,16 @@ export class GameStudioGateway extends TypertRemoteService {
1519
1792
  const job = await seqgen.readSequenceJob(jobId);
1520
1793
  if (job === undefined)
1521
1794
  throw new Error(`任务不存在:${jobId}`);
1522
- return { ...job, tasks: seqgen.listSequenceTasks(jobId), assetBase: `${ROUTE_PREFIX}/sequence-assets/${jobId}/` };
1795
+ /**
1796
+ * `dir` 与本机绝对路径的用法同 `getImageJob`:抽帧产物的绝对路径 =
1797
+ * `dir + "/" + file`,其中 `file` 取 `frames.files` 里那串相对路径。
1798
+ */
1799
+ return {
1800
+ ...job,
1801
+ dir: seqgen.sequenceJobDir(jobId),
1802
+ tasks: seqgen.listSequenceTasks(jobId),
1803
+ assetBase: assetBasePath(`${ROUTE_PREFIX}/sequence-assets/${jobId}/`)
1804
+ };
1523
1805
  }
1524
1806
  async deleteSequenceJob(payload) {
1525
1807
  await seqgen.deleteSequenceJob(asString(asRecord(payload).jobId));
@@ -2078,6 +2360,329 @@ export class GameStudioGateway extends TypertRemoteService {
2078
2360
  async runRigAtlas(payload) {
2079
2361
  return riggen.startAtlas(asString(asRecord(payload).jobId));
2080
2362
  }
2363
+ // ── 音乐生成编辑(模块七)──────────────────────────────────────────────
2364
+ //
2365
+ // 这一组方法全部只碰 `music-jobs/`;生成/工具类任务由 musicgen 的后台任务表
2366
+ // 推进,界面与对话都通过 `getMusicJob` / `refreshMusicJob` 看结果。
2367
+ async getMusicGuide(payload) {
2368
+ const input = asRecord(payload);
2369
+ return musicGuidePayload(typeof input.lang === "string" ? input.lang : undefined);
2370
+ }
2371
+ async getMusicScoreGuide(payload) {
2372
+ const input = asRecord(payload);
2373
+ return musicScoreGuidePayload(typeof input.lang === "string" ? input.lang : undefined);
2374
+ }
2375
+ /** 谱曲依赖自检:强制重新探测(不生成、不计费)。 */
2376
+ async testMusicScore() {
2377
+ const config = await loadConfig();
2378
+ return detectScoreDeps(config, { force: true });
2379
+ }
2380
+ async saveMusicScorePlan(payload) {
2381
+ const input = asRecord(payload);
2382
+ return musicgen.saveMusicScorePlan(asString(input.jobId), input.plan);
2383
+ }
2384
+ async runMusicScore(payload) {
2385
+ const input = asRecord(payload);
2386
+ return musicgen.runMusicScore(asString(input.jobId), {
2387
+ title: typeof input.title === "string" ? input.title : undefined,
2388
+ plan: input.plan,
2389
+ script: asString(input.script),
2390
+ basedOn: typeof input.basedOn === "string" ? input.basedOn : undefined,
2391
+ label: typeof input.label === "string" ? input.label : undefined
2392
+ });
2393
+ }
2394
+ async submitMusicScoreToSuno(payload) {
2395
+ const input = asRecord(payload);
2396
+ return musicgen.submitMusicScoreToSuno(asString(input.jobId), {
2397
+ scoreId: typeof input.scoreId === "string" ? input.scoreId : undefined,
2398
+ confirm: input.confirm === true,
2399
+ model: typeof input.model === "string" ? input.model : undefined,
2400
+ params: input.params === undefined || input.params === null ? undefined : asRecord(input.params),
2401
+ regenerate: input.regenerate === true,
2402
+ copyrightAudio: input.copyrightAudio === true,
2403
+ audioWeight: typeof input.audioWeight === "number" ? input.audioWeight : undefined
2404
+ });
2405
+ }
2406
+ async listMusicJobs() {
2407
+ return { jobs: await musicgen.listMusicJobs() };
2408
+ }
2409
+ async createMusicJob(payload) {
2410
+ const input = asRecord(payload);
2411
+ const job = await musicgen.createMusicJob({
2412
+ name: typeof input.name === "string" ? input.name : undefined,
2413
+ source: input.source,
2414
+ settings: input.settings,
2415
+ reviewMode: input.reviewMode === "manual" ? "manual" : input.reviewMode === "auto" ? "auto" : undefined,
2416
+ workflow: input.workflow === "compose" ? "compose" : "generate"
2417
+ });
2418
+ return musicgen.musicSnapshot(job, originForLinks());
2419
+ }
2420
+ async getMusicJob(payload) {
2421
+ const input = asRecord(payload);
2422
+ const job = await musicgen.readMusicJob(asString(input.jobId));
2423
+ if (job === undefined)
2424
+ throw new Error(`音乐任务不存在:${asString(input.jobId)}`);
2425
+ return musicgen.musicSnapshot(job, originForLinks());
2426
+ }
2427
+ async saveMusicJob(payload) {
2428
+ const input = asRecord(payload);
2429
+ const id = asString(input.jobId);
2430
+ const job = await musicgen.patchMusicJob(id, (current) => {
2431
+ if (typeof input.name === "string" && input.name.trim() !== "")
2432
+ current.name = input.name.trim().slice(0, 80);
2433
+ if (input.source !== undefined && input.source !== null) {
2434
+ current.source = musicgen.normalizeMusicSource({ ...current.source, ...asRecord(input.source) });
2435
+ }
2436
+ if (input.settings !== undefined && input.settings !== null) {
2437
+ current.settings = musicgen.normalizeMusicSettings({ ...current.settings, ...asRecord(input.settings) }, current.source);
2438
+ }
2439
+ if (input.reviewMode === "manual" || input.reviewMode === "auto")
2440
+ current.reviewMode = input.reviewMode;
2441
+ musicgen.musicLog(current, "info", "任务参数已更新");
2442
+ return current;
2443
+ });
2444
+ return musicgen.musicSnapshot(job, originForLinks());
2445
+ }
2446
+ async deleteMusicJob(payload) {
2447
+ const id = asString(asRecord(payload).jobId);
2448
+ await musicgen.deleteMusicJob(id);
2449
+ return { ok: true, id };
2450
+ }
2451
+ async setMusicApproved(payload) {
2452
+ const input = asRecord(payload);
2453
+ const id = asString(input.jobId);
2454
+ if (typeof input.approved !== "boolean")
2455
+ throw new Error("approved 必须是布尔值");
2456
+ const stage = typeof input.stage === "string" ? input.stage : undefined;
2457
+ if (stage !== undefined && !musicgen.MUSIC_STAGES.includes(stage)) {
2458
+ throw new Error(`未知阶段:${stage}(可选:${musicgen.MUSIC_STAGES.join(" / ")})`);
2459
+ }
2460
+ const job = await musicgen.patchMusicJob(id, (current) => {
2461
+ if (typeof input.scoreId === "string" && input.scoreId !== "") {
2462
+ const composition = current.compositions.find((entry) => entry.id === input.scoreId);
2463
+ if (composition === undefined)
2464
+ throw new Error(`谱曲版本不存在:${input.scoreId}`);
2465
+ composition.approved = input.approved;
2466
+ }
2467
+ else if (typeof input.versionId === "string" && input.versionId !== "") {
2468
+ const version = current.versions.find((entry) => entry.id === input.versionId);
2469
+ if (version === undefined)
2470
+ throw new Error(`版本不存在:${input.versionId}`);
2471
+ version.approved = input.approved;
2472
+ }
2473
+ else if (typeof input.songId === "string" && input.songId !== "") {
2474
+ const song = current.songs.find((entry) => entry.id === input.songId);
2475
+ if (song === undefined)
2476
+ throw new Error(`歌曲不存在:${input.songId}`);
2477
+ song.approved = input.approved;
2478
+ }
2479
+ else if (stage !== undefined) {
2480
+ current.stages[stage] = { ...current.stages[stage], approved: input.approved };
2481
+ }
2482
+ else {
2483
+ for (const song of current.songs)
2484
+ song.approved = input.approved;
2485
+ for (const composition of current.compositions)
2486
+ composition.approved = input.approved;
2487
+ for (const key of musicgen.MUSIC_STAGES)
2488
+ current.stages[key] = { ...current.stages[key], approved: input.approved };
2489
+ }
2490
+ musicgen.musicLog(current, "info", `验收标记:${input.approved ? "通过" : "取消通过"}`);
2491
+ return current;
2492
+ });
2493
+ return musicgen.musicSnapshot(job, originForLinks());
2494
+ }
2495
+ async revealMusicJob(payload) {
2496
+ const id = asString(asRecord(payload).jobId);
2497
+ const job = await musicgen.readMusicJob(id);
2498
+ if (job === undefined)
2499
+ throw new Error(`音乐任务不存在:${id}`);
2500
+ const dir = musicgen.musicJobDir(id);
2501
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
2502
+ try {
2503
+ spawn(command, [dir], { detached: true, stdio: "ignore" }).unref();
2504
+ }
2505
+ catch (error) {
2506
+ throw new Error(`无法打开目录:${error instanceof Error ? error.message : String(error)}`);
2507
+ }
2508
+ return { ok: true, dir };
2509
+ }
2510
+ async runMusicGeneration(payload) {
2511
+ const input = asRecord(payload);
2512
+ return musicgen.startMusicGeneration(asString(input.jobId), {
2513
+ engine: input.engine,
2514
+ mode: input.mode,
2515
+ model: typeof input.model === "string" ? input.model : undefined,
2516
+ params: asRecord(input.params),
2517
+ regenerate: input.regenerate === true,
2518
+ by: "ai"
2519
+ });
2520
+ }
2521
+ async cancelMusicGeneration(payload) {
2522
+ const id = asString(asRecord(payload).jobId);
2523
+ const canceled = musicgen.cancelMusicGeneration(id);
2524
+ return {
2525
+ ok: true,
2526
+ canceled,
2527
+ message: canceled
2528
+ ? "已停止本地轮询。已经提交给平台的生成仍会继续并计费;不要为了「确认」再提交一次。"
2529
+ : "当前没有可取消的生成任务。"
2530
+ };
2531
+ }
2532
+ async refreshMusicJob(payload) {
2533
+ return musicgen.refreshMusicJob(asString(asRecord(payload).jobId));
2534
+ }
2535
+ async getMusicWav(payload) {
2536
+ const input = asRecord(payload);
2537
+ return musicgen.getMusicWav(asString(input.jobId), asString(input.songId));
2538
+ }
2539
+ async getMusicLrc(payload) {
2540
+ const input = asRecord(payload);
2541
+ return musicgen.getMusicLrc(asString(input.jobId), Array.isArray(input.songIds) ? input.songIds.map((id) => String(id)) : undefined);
2542
+ }
2543
+ async listMusicHistory(payload) {
2544
+ const input = asRecord(payload);
2545
+ return musicgen.listMusicHistory({
2546
+ page: typeof input.page === "number" ? input.page : undefined,
2547
+ size: typeof input.size === "number" ? input.size : undefined,
2548
+ filters: Array.isArray(input.filters) ? input.filters.map((entry) => String(entry)) : undefined
2549
+ });
2550
+ }
2551
+ async listMusicStemInstruments() {
2552
+ return musicgen.listMusicStemInstruments();
2553
+ }
2554
+ async runMusicTool(payload) {
2555
+ const input = asRecord(payload);
2556
+ return musicgen.runMusicTool(asString(input.jobId), asString(input.kind), asRecord(input.params));
2557
+ }
2558
+ async musicPeaks(payload) {
2559
+ const input = asRecord(payload);
2560
+ return musicgen.musicPeaks(asString(input.jobId), {
2561
+ songId: typeof input.songId === "string" ? input.songId : undefined,
2562
+ versionId: typeof input.versionId === "string" ? input.versionId : undefined,
2563
+ scoreId: typeof input.scoreId === "string" ? input.scoreId : undefined,
2564
+ buckets: typeof input.buckets === "number" ? input.buckets : undefined
2565
+ }, originForLinks());
2566
+ }
2567
+ async renderMusicEdit(payload) {
2568
+ const input = asRecord(payload);
2569
+ return musicgen.renderMusicEdit(asString(input.jobId), {
2570
+ songId: typeof input.songId === "string" ? input.songId : undefined,
2571
+ versionId: typeof input.versionId === "string" ? input.versionId : undefined,
2572
+ ops: asRecord(input.ops),
2573
+ label: typeof input.label === "string" ? input.label : undefined,
2574
+ preview: input.preview === true,
2575
+ by: input.by === "ai" ? "ai" : "human",
2576
+ force: input.force === true
2577
+ });
2578
+ }
2579
+ async saveMusicVersion(payload) {
2580
+ const input = asRecord(payload);
2581
+ return musicgen.saveMusicVersion(asString(input.jobId), asString(input.versionId), typeof input.label === "string" ? input.label : undefined);
2582
+ }
2583
+ async deleteMusicVersion(payload) {
2584
+ const input = asRecord(payload);
2585
+ await musicgen.deleteMusicVersion(asString(input.jobId), asString(input.versionId));
2586
+ return { ok: true };
2587
+ }
2588
+ async exportMusic(payload) {
2589
+ const input = asRecord(payload);
2590
+ return musicgen.exportMusic(asString(input.jobId), {
2591
+ songId: typeof input.songId === "string" ? input.songId : undefined,
2592
+ versionId: typeof input.versionId === "string" ? input.versionId : undefined,
2593
+ scoreId: typeof input.scoreId === "string" ? input.scoreId : undefined,
2594
+ format: typeof input.format === "string" ? input.format : undefined,
2595
+ name: typeof input.name === "string" ? input.name : undefined,
2596
+ zip: input.zip === true
2597
+ }, { origin: originForLinks() });
2598
+ }
2599
+ // ── 音效生成(模块八,火山引擎 Seed-Audio)────────────────────────────
2600
+ //
2601
+ // 这一组只碰 `sfx-jobs/`。生成是同步 HTTP,但由 sfxgen 的后台任务表承载,
2602
+ // 界面与对话都通过 `getSfxJob` 看状态。
2603
+ async listSfxJobs() {
2604
+ return { jobs: await sfxgen.listSfxJobs() };
2605
+ }
2606
+ async createSfxJob(payload) {
2607
+ const input = asRecord(payload);
2608
+ const job = await sfxgen.createSfxJob({
2609
+ name: typeof input.name === "string" ? input.name : undefined,
2610
+ prompt: asString(input.prompt),
2611
+ settings: input.settings,
2612
+ reviewMode: input.reviewMode === "manual" ? "manual" : input.reviewMode === "auto" ? "auto" : undefined
2613
+ });
2614
+ return sfxgen.sfxSnapshot(job, originForLinks());
2615
+ }
2616
+ async getSfxJob(payload) {
2617
+ const id = asString(asRecord(payload).jobId);
2618
+ const job = await sfxgen.readSfxJob(id);
2619
+ if (job === undefined)
2620
+ throw new Error(`音效任务不存在:${id}`);
2621
+ return sfxgen.sfxSnapshot(job, originForLinks());
2622
+ }
2623
+ async saveSfxJob(payload) {
2624
+ const input = asRecord(payload);
2625
+ return sfxgen.saveSfxJob(asString(input.jobId), {
2626
+ name: typeof input.name === "string" ? input.name : undefined,
2627
+ prompt: typeof input.prompt === "string" ? input.prompt : undefined,
2628
+ settings: input.settings,
2629
+ reviewMode: input.reviewMode === "manual" ? "manual" : input.reviewMode === "auto" ? "auto" : undefined
2630
+ });
2631
+ }
2632
+ async deleteSfxJob(payload) {
2633
+ const id = asString(asRecord(payload).jobId);
2634
+ await sfxgen.deleteSfxJob(id);
2635
+ return { ok: true };
2636
+ }
2637
+ async uploadSfxRef(payload) {
2638
+ const input = asRecord(payload);
2639
+ return sfxgen.uploadSfxRef(asString(input.jobId), input.kind === "audio" ? "audio" : "image", typeof input.name === "string" ? input.name : undefined, asString(input.data));
2640
+ }
2641
+ async removeSfxRef(payload) {
2642
+ const input = asRecord(payload);
2643
+ return sfxgen.removeSfxRef(asString(input.jobId), input.kind === "audio" ? "audio" : "image", typeof input.file === "string" ? input.file : undefined);
2644
+ }
2645
+ async runSfxGeneration(payload) {
2646
+ return sfxgen.startSfxGeneration(asString(asRecord(payload).jobId));
2647
+ }
2648
+ async cancelSfxGeneration(payload) {
2649
+ const id = asString(asRecord(payload).jobId);
2650
+ const canceled = await sfxgen.cancelSfxGeneration(id);
2651
+ return {
2652
+ ok: true,
2653
+ canceled,
2654
+ message: canceled
2655
+ ? "已取消本地请求。远端可能仍会完成并计费;不要为了「确认」再提交一次。"
2656
+ : "当前没有可取消的生成任务。"
2657
+ };
2658
+ }
2659
+ async setSfxApproved(payload) {
2660
+ const input = asRecord(payload);
2661
+ const stage = input.stage === "generate" || input.stage === "export" ? input.stage : undefined;
2662
+ return sfxgen.setSfxApproved(asString(input.jobId), stage, input.approved === true);
2663
+ }
2664
+ async revealSfxJob(payload) {
2665
+ const id = asString(asRecord(payload).jobId);
2666
+ const job = await sfxgen.readSfxJob(id);
2667
+ if (job === undefined)
2668
+ throw new Error(`音效任务不存在:${id}`);
2669
+ const dir = sfxgen.sfxJobDir(id);
2670
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
2671
+ try {
2672
+ spawn(command, [dir], { detached: true, stdio: "ignore" }).unref();
2673
+ }
2674
+ catch (error) {
2675
+ throw new Error(`无法打开目录:${error instanceof Error ? error.message : String(error)}`);
2676
+ }
2677
+ return { ok: true, dir };
2678
+ }
2679
+ async exportSfx(payload) {
2680
+ const input = asRecord(payload);
2681
+ return sfxgen.exportSfx(asString(input.jobId), {
2682
+ takeId: typeof input.takeId === "string" ? input.takeId : undefined,
2683
+ zip: input.zip === true
2684
+ });
2685
+ }
2081
2686
  assertSurface() {
2082
2687
  for (const spec of METHODS) {
2083
2688
  if (typeof this[spec.method] !== "function") {
@@ -2150,6 +2755,11 @@ function mapTilesetBrief(tileset) {
2150
2755
  shape: tileset.shape,
2151
2756
  animRows: tileset.animRows,
2152
2757
  variants: tileset.variants,
2758
+ loop: tileset.loop,
2759
+ stamp: tileset.stamp,
2760
+ rev: tileset.rev,
2761
+ clarity: tileset.clarity,
2762
+ fps: tileset.fps,
2153
2763
  builtin: tileset.builtin === true ? true : undefined,
2154
2764
  tileCount: tileset.tiles.length
2155
2765
  };
@@ -2172,15 +2782,22 @@ const SERVABLE_RIG_DIRS = new Set(["source", "sheet", "parts", "layout", "rig",
2172
2782
  /** 地图地块:模板、原始生成、规整产物、装饰、地图、导出包。 */
2173
2783
  const SERVABLE_TILE_DIRS = new Set(["template", "raw", "cell", "decor", "map", "export"]);
2174
2784
  /**
2175
- * 地图编辑器(模块六):素材原图、验收预览图、导出包。
2785
+ * 地图编辑器(模块六):素材原图、验收预览图、导出包、AI 素材暂存区。
2176
2786
  *
2177
- * ⚠️ 这个白名单、`AssetScope` 类型、`resolveAssetTarget` 的分支、`SCOPES`
2178
- * 数组**四处必须同步**:漏一处就是 403,而界面只表现为「图裂了」。
2787
+ * **唯一真源在 `mapgen.SERVABLE_MAP_DIRS`**(建项目时的目录清单读的也是它)——
2788
+ * 两处各写一份的话,漏掉的那条只会以「图裂了 / 403」的形式出现,不报错。
2789
+ *
2790
+ * ⚠️ 另一半仍要同步:`AssetScope` 类型、`resolveAssetTarget` 的分支、`SCOPES`
2791
+ * 数组(那三处是 **scope** 级;`ai/` 是子目录级,只比对第一段路径,加一行就够)。
2179
2792
  *
2180
2793
  * 单项目 = 单张地图之后 `maps/` 目录不存在了(地图就是项目根下的 `map.json`,
2181
2794
  * 不通过资源路由读)。
2182
2795
  */
2183
- const SERVABLE_MAP_DIRS = new Set(["tilesets", "preview", "export"]);
2796
+ const SERVABLE_MAP_DIRS = mapgen.SERVABLE_MAP_DIRS;
2797
+ /** 音乐生成编辑(模块七):原曲、版本、波形缓存、工具产物、导出。 */
2798
+ const SERVABLE_MUSIC_DIRS = musicgen.SERVABLE_MUSIC_DIRS;
2799
+ /** 音效生成(模块八):参考素材、每次生成的音频、导出。 */
2800
+ const SERVABLE_SFX_DIRS = sfxgen.SERVABLE_SFX_DIRS;
2184
2801
  function resolveAssetTarget(scope, id, relative) {
2185
2802
  if (scope === "assets") {
2186
2803
  if (!PROJECT_ID_PATTERN.test(id))
@@ -2207,6 +2824,16 @@ function resolveAssetTarget(scope, id, relative) {
2207
2824
  return undefined;
2208
2825
  return { file: mapgen.mapAssetPath(id, relative), dirs: SERVABLE_MAP_DIRS };
2209
2826
  }
2827
+ if (scope === "music-assets") {
2828
+ if (!musicgen.isValidMusicJobId(id))
2829
+ return undefined;
2830
+ return { file: musicgen.musicAssetPath(id, relative), dirs: SERVABLE_MUSIC_DIRS };
2831
+ }
2832
+ if (scope === "sfx-assets") {
2833
+ if (!sfxgen.isValidSfxJobId(id))
2834
+ return undefined;
2835
+ return { file: sfxgen.sfxAssetPath(id, relative), dirs: SERVABLE_SFX_DIRS };
2836
+ }
2210
2837
  if (!seqgen.isValidSequenceJobId(id))
2211
2838
  return undefined;
2212
2839
  return { file: seqgen.sequenceAssetPath(id, relative), dirs: SERVABLE_SEQUENCE_DIRS };
@@ -2216,13 +2843,14 @@ function sendText(res, status, text) {
2216
2843
  res.end(text);
2217
2844
  }
2218
2845
  /**
2219
- * 把四个模块的产物路径映射到磁盘文件:
2846
+ * 把各模块的产物路径映射到磁盘文件:
2220
2847
  * /dsh-game-material-master/assets/<项目 id>/<相对路径> 八方向图
2221
2848
  * /dsh-game-material-master/image-assets/<任务 id>/<相对路径> 图片生成
2222
2849
  * /dsh-game-material-master/sequence-assets/<任务 id>/<相对路径> 序列帧生成
2223
2850
  * /dsh-game-material-master/rig-assets/<任务 id>/<相对路径> 骨骼动画生成
2224
2851
  * /dsh-game-material-master/tile-assets/<项目 id>/<相对路径> 45°地图地块生成
2225
2852
  * /dsh-game-material-master/map-assets/<项目 id>/<相对路径> 地图编辑器
2853
+ * /dsh-game-material-master/music-assets/<任务 id>/<相对路径> 音乐生成编辑
2226
2854
  *
2227
2855
  * 支持 Range:没有它浏览器里的 <video> 就不能拖动进度条,验收视频时会很难受。
2228
2856
  */
@@ -2256,7 +2884,7 @@ async function handleAsset(req, res) {
2256
2884
  // 三处同步。只改类型不改这里,TypeScript 一句话都不会说 —— `scope` 是断言出来的,
2257
2885
  // 而漏掉的那个 scope 会在这里直接掉进 404(界面表现只是「图裂了」)。
2258
2886
  // 实测:`tile-assets` 就这么漏过一轮,模板图全 404。
2259
- const SCOPES = ["assets", "image-assets", "sequence-assets", "rig-assets", "tile-assets", "map-assets"];
2887
+ const SCOPES = ["assets", "image-assets", "sequence-assets", "rig-assets", "tile-assets", "map-assets", "music-assets", "sfx-assets"];
2260
2888
  if (!SCOPES.includes(scope)) {
2261
2889
  sendText(res, 404, "Not Found");
2262
2890
  return;
@@ -2305,6 +2933,16 @@ async function handleAsset(req, res) {
2305
2933
  "Cache-Control": "private, max-age=300",
2306
2934
  "Accept-Ranges": "bytes"
2307
2935
  };
2936
+ /**
2937
+ * `?download=1`:给音乐模块的导出链接用,强制浏览器存盘而不是在线播放。
2938
+ * 文件名只用磁盘上的 basename(不接受 URL 里的文件名),中文走 RFC 5987。
2939
+ */
2940
+ if (url.searchParams.get("download") === "1") {
2941
+ const name = basename(target.file);
2942
+ const ascii = name.replace(/[^\x20-\x7e]/gu, "_").replace(/["\\]/gu, "_");
2943
+ baseHeaders["Content-Disposition"] = `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
2944
+ baseHeaders["Cache-Control"] = "no-store";
2945
+ }
2308
2946
  if (req.headers["if-none-match"] === etag) {
2309
2947
  res.writeHead(304, baseHeaders);
2310
2948
  res.end();
@@ -2344,6 +2982,13 @@ async function handleAsset(req, res) {
2344
2982
  }
2345
2983
  // ── cordis 插件体 ────────────────────────────────────────────────────────
2346
2984
  export function apply(ctx) {
2985
+ // 插件被重载时,模块缓存会把上一次的 disposed 标记原样留下来,于是所有生成类调用都
2986
+ // 静默变成「任务已在进行中」——每次 apply 都要把三个后台任务表复位。
2987
+ activatePipeline();
2988
+ seqgen.activateSequence();
2989
+ riggen.activateRig();
2990
+ musicgen.activateMusic();
2991
+ sfxgen.activateSfx();
2347
2992
  // 旧版本的数据目录叫 8dir-sprites,插件改名后搬一次,已有项目无缝接上。
2348
2993
  void migrateLegacyDataRoot()
2349
2994
  .then((moved) => {
@@ -2393,9 +3038,15 @@ export function apply(ctx) {
2393
3038
  // 恢复轮询失败不影响插件本体。
2394
3039
  }
2395
3040
  })();
3041
+ // 音乐任务(模块七):把上次没跑完的生成/工具任务接上(不重新提交,只继续查询/下载)。
3042
+ void musicgen.resumeMusicJobs().catch(() => undefined);
3043
+ // 音效任务(模块八):同步接口没有远端 taskId 可续查,残留的 running 标失败。
3044
+ void sfxgen.resumeSfxJobs().catch(() => undefined);
2396
3045
  ctx.effect(() => () => {
2397
3046
  disposePipeline();
2398
3047
  seqgen.disposeSequence();
2399
3048
  riggen.disposeRig();
3049
+ musicgen.disposeMusic();
3050
+ sfxgen.disposeSfx();
2400
3051
  }, "dsh-game-material-master: pipeline cleanup");
2401
3052
  }