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/mapgen.js CHANGED
@@ -8,10 +8,15 @@
8
8
  * ├── project.json 元数据:网格、素材、阶段、日志
9
9
  * ├── map.json 这张地图:图层元数据 + 每层数据(0 = 空)
10
10
  * ├── tilesets/<tsId>.png 导入的素材原图(原样保存,不改写)
11
+ * ├── ai/<名字>.png AI 生成素材的**暂存区**:对话里整理好、等用户确认的那张图
11
12
  * ├── preview/map.png 验收图:宿主算好的地图渲染图
12
13
  * └── export/<安全名>/ 导出:map.png + map.json + manifest.json
13
14
  * ```
14
15
  *
16
+ * ⚠️ `ai/` 里的东西**不是素材**:素材的属性在「新增素材」那一刻定死、之后只能删掉
17
+ * 重来,所以宿主只把图整理好(`composeMapAsset`),由用户确认后走
18
+ * `importMapTileset` 才进 `tilesets/`。
19
+ *
15
20
  * 参考 AsLib 的 RPG Map Maker:一屏、零术语、地图四周**环绕**、A2 素材自动连接、
16
21
  * 动画地块、内置素材、一键生成。旧的「多地图 / 地形族 / 掩码覆盖 / 等距网格 /
17
22
  * 层高偏移 / Tiled 导出」全部删掉 —— 那些正是「预览好看、导出位移」「族配不齐
@@ -27,18 +32,20 @@
27
32
  * 撤销 / 重做是宿主侧**逆操作日志**(结构操作才存整份快照),界面不需要自己维护
28
33
  * 撤销栈 —— 旧模块那个「整份草稿 + 客户端撤销栈」正是「撤销跳步」的来源。
29
34
  */
30
- import { mkdir, readdir, rm, writeFile } from "node:fs/promises";
35
+ import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
31
36
  import { existsSync } from "node:fs";
32
37
  import { randomUUID } from "node:crypto";
33
38
  import { join } from "node:path";
34
39
  import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
35
40
  import { dataRoot } from "./config.js";
36
- import { decodeFile, pngSize, probeImageSize, sniffImageExt } from "./bitmap.js";
41
+ import { decodeFile, encodeBitmap, pngSize, probeImageSize, sniffImageExt } from "./bitmap.js";
42
+ import { keyGreen } from "./chroma.js";
37
43
  import { addLayer, applyOps, clearLayer, cloneDoc, createMapDoc, filledCount, isDocEmpty, moveLayer, normalizeMapDoc, removeLayer, renameLayer, resizeDoc, revertOps } from "./mapdoc.js";
38
44
  import { assertGrid, assertMapSize, canonicalChunk, chunkKey, chunksInRange, dirtyChunksFor, layoutOf, normalizeGrid, parseChunkKey, viewCellRange, MAX_MAP_DIM, MAX_PLAN_CHUNKS } from "./mapgeom.js";
39
- import { bitmapToPng, buildPlan, rasterize } from "./maprender.js";
40
- import { COMMON_TILE_SIZES, buildTiles, detectLayout, flatIndexByValue, flatTiles, layoutFor } from "./maptiles.js";
45
+ import { bitmapToPng, buildPlan, rasterize, stampCellsOf } from "./maprender.js";
46
+ import { COMMON_TILE_SIZES, buildTiles, composeAssetSheet, detectLayout, flatIndexByValue, flatTiles, layoutFor, safeAssetStem, sheetPlanOf, tileSeamRatios, trimUniformBorder, sizeFromBytes, parseAssetFps, parseAssetLoop, parseStampSpec, composeStampSource, stampTilesetImage, keyStampBackground, STAMP_KEY_OPTIONS, STAMP_MAX_CELLS, parseAssetScale, parseClarity, resampleToSize, A2_ROWS, MAX_ASSET_SCALE, assertStampFitsProject, } from "./maptiles.js";
41
47
  import { exportMap, safeFileName } from "./mapexport.js";
48
+ import { assetBasePath } from "./links.js";
42
49
  import { primeSampleTextures, renderSampleTilesets } from "./mapsamplegen.js";
43
50
  /** 四个阶段(对话面契约:`stage=assets|rules|paint|export`;`rules` 自动完成、界面不显示)。 */
44
51
  export const MAP_STAGES = ["assets", "rules", "paint", "export"];
@@ -71,10 +78,15 @@ export function isValidMapProjectId(id) {
71
78
  /**
72
79
  * 子目录白名单(静态资源路由按**第一段**比对,漏一条就是 403 + 图裂)。
73
80
  *
74
- * ⚠️ 与 `index.ts` 的 `AssetScope` 类型、`resolveAssetTarget` 分支、`SCOPES` 数组
75
- * **四处必须同步**。`maps/` 已经不存在了(单项目单地图 → `map.json` 在项目根)。
81
+ * **这是唯一真源**:`index.ts` 的资源路由直接引用这一份,建项目时的目录清单也用它 ——
82
+ * 两边各写一份的话,「建了目录但路由 403」只会以「图裂了」的形式出现(曾经踩过)。
83
+ *
84
+ * ⚠️ 另一半仍要同步:`index.ts` 的 `AssetScope` 类型、`resolveAssetTarget` 分支、
85
+ * `SCOPES` 数组(那三处是 **scope** 级,不是子目录级)。`maps/` 已经不存在了
86
+ * (单项目单地图 → `map.json` 在项目根);`ai/` 是「AI 生成素材」的暂存区
87
+ * (整理好、等用户在「新增素材」里确认的那张图)。
76
88
  */
77
- export const SERVABLE_MAP_DIRS = new Set(["tilesets", "preview", "export"]);
89
+ export const SERVABLE_MAP_DIRS = new Set(["tilesets", "preview", "export", "ai"]);
78
90
  /** 新项目默认地图尺寸(单屏一屏就能画完)。 */
79
91
  const DEFAULT_COLS = 32;
80
92
  const DEFAULT_ROWS = 32;
@@ -175,9 +187,18 @@ function normalizeTileset(raw) {
175
187
  const cell = normalizeCell(source.cell) ?? { width: 32, height: 32 };
176
188
  const shape = isTilesetShape(source.shape) ? source.shape : "plain";
177
189
  const animRows = source.animRows === true;
190
+ // 整图规格:读盘时**不抛**(老数据 / 坏数据当成「不是整图」处理,等重导),只认能解析出来的。
191
+ let stamp;
192
+ try {
193
+ stamp = parseStampSpec(source.stamp);
194
+ }
195
+ catch {
196
+ stamp = undefined;
197
+ }
198
+ const shapeSafe = stamp !== undefined ? "stamp" : shape === "stamp" ? "plain" : shape;
178
199
  const rawTiles = source.tiles;
179
200
  const previous = Array.isArray(rawTiles) ? rawTiles : undefined;
180
- const tiles = buildTiles({ shape, cell, imageWidth, imageHeight, animRows }, previous);
201
+ const tiles = buildTiles({ shape: shapeSafe, cell, imageWidth, imageHeight, animRows, stamp }, previous);
181
202
  const tileset = {
182
203
  id: typeof source.id === "string" && source.id !== "" ? source.id : `ts${randomUUID().slice(0, 6)}`,
183
204
  name: typeof source.name === "string" && source.name !== "" ? source.name : "素材",
@@ -185,9 +206,13 @@ function normalizeTileset(raw) {
185
206
  imageWidth,
186
207
  imageHeight,
187
208
  cell,
188
- shape,
209
+ shape: shapeSafe,
189
210
  animRows,
190
- variants: variantsOf(shape, cell, imageWidth, imageHeight, animRows),
211
+ stamp,
212
+ variants: stamp === undefined ? variantsOf(shapeSafe, cell, imageWidth, imageHeight, animRows) : stamp.frames,
213
+ loop: parseAssetLoop(source.loop),
214
+ clarity: parseClarity(source.clarity),
215
+ fps: parseAssetFps(source.fps),
191
216
  builtin: source.builtin === true ? true : undefined,
192
217
  tiles
193
218
  };
@@ -201,14 +226,14 @@ function asRecord(value) {
201
226
  return value !== null && typeof value === "object" ? value : {};
202
227
  }
203
228
  function isTilesetShape(value) {
204
- return value === "plain" || value === "a2quad" || value === "corner16";
229
+ return value === "plain" || value === "a2quad" || value === "corner16" || value === "stamp";
205
230
  }
206
231
  /** 界面 / 工具面传上来的形态字符串收口:不合法**明确报错**,不静默改成别的值。 */
207
232
  export function parseTilesetShape(value) {
208
233
  if (value === undefined || value === null || value === "")
209
234
  return undefined;
210
235
  if (!isTilesetShape(value))
211
- throw new Error(`未知素材形态:${String(value)}(可选 plain / a2quad / corner16)`);
236
+ throw new Error(`未知素材形态:${String(value)}(可选 plain / a2quad / corner16 / stamp)`);
212
237
  return value;
213
238
  }
214
239
  /** 整数收口;形状不对时抛中文错,不静默改成别的值。 */
@@ -448,10 +473,38 @@ function pickDropKeys(dirtyCanonical, have, doc) {
448
473
  }
449
474
  return out;
450
475
  }
451
- function outcomeOf(projectId, changed, skipped, layout, cells, have, doc) {
476
+ function outcomeOf(projectId, changed, skipped, layout, cells, have, doc, stamps = 0) {
452
477
  const dirtyChunks = cells.length === 0 ? [] : dirtyChunksFor(cells, layout);
453
478
  const state = historyState(projectId);
454
- return { changed, skipped, dirtyChunks, dropKeys: pickDropKeys(dirtyChunks, have, doc), canUndo: state.canUndo, canRedo: state.canRedo };
479
+ return { changed, skipped, stamps, dirtyChunks, dropKeys: pickDropKeys(dirtyChunks, have, doc), canUndo: state.canUndo, canRedo: state.canRedo };
480
+ }
481
+ /**
482
+ * 「素材 id → 占几格」:整图 op 只带素材 id,占格由**宿主**从素材上读
483
+ * (客户端传 cols/rows 等于把印多大交给界面,一旦对不上就是几何错位)。
484
+ */
485
+ function stampSpecResolver(project) {
486
+ const byId = new Map(project.tilesets.map((tileset) => [tileset.id, tileset]));
487
+ return (tilesetId) => {
488
+ const spec = byId.get(tilesetId)?.stamp;
489
+ return spec === undefined ? undefined : { cols: spec.cols, rows: spec.rows };
490
+ };
491
+ }
492
+ /**
493
+ * 整图占的格子 + 每格通行性(区域叠加用)。
494
+ *
495
+ * 与渲染计划同一个口径:`stampSpan` 算占格、`tileset.stamp.pass` 取三态、坐标取模。
496
+ * 越界的格(地图改小过)直接跳过。
497
+ */
498
+ function passCellsOf(project, doc) {
499
+ if (doc.stamps.length === 0)
500
+ return [];
501
+ const context = renderContextFor(project, doc);
502
+ const out = [];
503
+ for (const stamp of doc.stamps) {
504
+ for (const cell of stampCellsOf(context, doc, stamp))
505
+ out.push({ r: cell.r, c: cell.c, kind: cell.pass });
506
+ }
507
+ return out;
455
508
  }
456
509
  function indexCells(indices, doc) {
457
510
  const out = [];
@@ -479,14 +532,14 @@ export async function applyMapOps(projectId, ops, opts = {}) {
479
532
  const project = await readProjectOrThrow(projectId);
480
533
  const doc = await theDocOrFresh(projectId);
481
534
  const layout = layoutOf(project.grid, doc.cols, doc.rows);
482
- const result = applyOps(doc, ops, layout);
535
+ const result = applyOps(doc, ops, layout, { stampSpecOf: stampSpecResolver(project) });
483
536
  // `touched`(标记改名这类不占格的改动)也要记一步撤销 —— 只看 `changed > 0` 的话,
484
537
  // 改名会「生效了但撤不回来」。
485
538
  if (result.changed > 0 || result.touched === true) {
486
539
  pushHistory(projectId, { undo: result.undo, redo: ops, stroke: opts.stroke }, doc);
487
540
  scheduleDocWrite(projectId, doc);
488
541
  }
489
- return outcomeOf(projectId, result.changed, result.skipped, layout, result.dirty, opts.have, doc);
542
+ return outcomeOf(projectId, result.changed, result.skipped, layout, result.dirty, opts.have, doc, result.stamps);
490
543
  }
491
544
  export async function undoMap(projectId, have) {
492
545
  const project = await readProjectOrThrow(projectId);
@@ -503,7 +556,7 @@ export async function undoMap(projectId, have) {
503
556
  else {
504
557
  let indices;
505
558
  try {
506
- indices = revertOps(doc, entry.undo);
559
+ indices = revertOps(doc, entry.undo, { stampSpecOf: stampSpecResolver(project) });
507
560
  }
508
561
  catch {
509
562
  // 栈被容量上限裁剪过之后,这一步的逆操作可能已经对不上:**放弃这一步**,
@@ -535,7 +588,7 @@ export async function redoMap(projectId, have) {
535
588
  else {
536
589
  let indices;
537
590
  try {
538
- indices = revertOps(doc, entry.redo);
591
+ indices = revertOps(doc, entry.redo, { stampSpecOf: stampSpecResolver(project) });
539
592
  }
540
593
  catch {
541
594
  state.entries.splice(state.index + 1, 1);
@@ -638,6 +691,93 @@ export async function saveMapDocStructure(projectId, patch) {
638
691
  *
639
692
  * `opts` 里留空的项走自动识别;给了就用用户的(值不合法就退回识别,不静默改)。
640
693
  */
694
+ /**
695
+ * **原地重新整理**一张 AI 素材:用同一份源图按现在的规则重烘一遍,**保留素材 id 与图块数**。
696
+ *
697
+ * 为什么要有它:整格 / 拼块的 16 块是**烘进素材图**的(收口、竖段换向、转角斜接都在里面),
698
+ * 生成规则一改,已有素材不会自动变。而「删掉再导一次」会把画在那张素材上的格子清空
699
+ * (宿主按图块序号重映射,素材没了自然就空了)—— 用户的地图就废了。
700
+ * 这条路径按 id 原地替换图片 + 重建 16 块,图块序号一个都不动。
701
+ *
702
+ * 前置条件:非内置素材、给了至少一张源图、形态与格子沿用素材自己的(不让这里改几何)。
703
+ */
704
+ export async function recomposeMapTileset(projectId, tilesetId, input = {}) {
705
+ const project = await readProjectOrThrow(projectId);
706
+ const index = project.tilesets.findIndex((tileset) => tileset.id === tilesetId);
707
+ if (index < 0)
708
+ throw new Error(`没有这块素材:${tilesetId}`);
709
+ const tileset = project.tilesets[index];
710
+ if (tileset.builtin === true)
711
+ throw new Error("内置素材不能重新整理(它们是程序化生成的,删掉重装即可)");
712
+ const files = (input.files ?? []).map((file) => String(file)).filter((file) => file !== "");
713
+ if (files.length === 0)
714
+ throw new Error("重新整理需要源图:files 里给至少一张图片的绝对路径");
715
+ if (tileset.shape === "corner16" && files.length !== 1) {
716
+ throw new Error("整格只要**一块**无缝砖:files 给 1 张(整格没有帧这一维)");
717
+ }
718
+ const clarity = input.clarity === undefined ? parseClarity(tileset.clarity) : parseClarity(input.clarity);
719
+ /** 先按 4 倍分辨率烘,再按清晰度缩到格子 —— 与 `composeMapAsset` 同一条口径(细节只丢一次)。 */
720
+ const scale = MAX_ASSET_SCALE;
721
+ const bigCell = { width: tileset.cell.width * scale, height: tileset.cell.height * scale };
722
+ const frames = [];
723
+ for (const file of files)
724
+ frames.push(trimUniformBorder(await decodeFile(file)).bitmap);
725
+ const plan = sheetPlanOf(tileset.shape, bigCell, frames.length, tileset.stamp);
726
+ /**
727
+ * 交给 `registerTileset` 的**源图**:
728
+ * - 整图 = `cols × rows*frames` 的源图(**不烘旋转**)—— 烘焙由 `registerTileset` 做,
729
+ * 这里先烘一遍的话会被烘第二次(真机翻车过:1024×2560 的图被再压成 256×64)。
730
+ * - 其它形态 = 照旧缩到最终尺寸。
731
+ */
732
+ const payload = tileset.stamp === undefined
733
+ ? (() => {
734
+ const big = composeAssetSheet(frames, plan, "smooth");
735
+ return resampleToSize(big, big.width / scale, big.height / scale, clarity);
736
+ })()
737
+ : composeStampSource(frames, tileset.stamp, bigCell, "smooth");
738
+ /** 尺寸校验用**成品**尺寸:整图是烘完 4 个旋转之后的大小。 */
739
+ const fitted = tileset.stamp === undefined ? payload : stampTilesetImage(payload, tileset.stamp, tileset.cell, clarity);
740
+ /**
741
+ * ⚠️ **写盘之前**先对尺寸:重烘只能把「本来就是 AI 整理出来的素材」重新烘一遍。
742
+ * 手动导的图集(例如一张 2×2 的普通图 = 4 块)用 `composeMapAsset` 的口径烘出来只有 1 块,
743
+ * 尺寸一变,图块序号就整体错位、地图上画过的地方全会变形 —— 这种必须明确拒绝,而不是写下去。
744
+ */
745
+ if (fitted.width !== tileset.imageWidth || fitted.height !== tileset.imageHeight) {
746
+ throw new Error(`重烘出来的尺寸和原素材不一样(${fitted.width}×${fitted.height} vs ${tileset.imageWidth}×${tileset.imageHeight}):` +
747
+ `这块素材不是按「AI 生成素材」的方式整理的(整格 1 张 / 拼块 N 张 / 普通 N 帧),不能原地重烘 —— ` +
748
+ `源图数量或用法对不上。`);
749
+ }
750
+ const warnings = [];
751
+ const rebuilt = await registerTileset(projectId, {
752
+ id: tileset.id,
753
+ name: tileset.name,
754
+ // 整图交**源图**(registerTileset 会缩到格子再烘旋转),其它形态交最终图。
755
+ bytes: encodeBitmap(payload),
756
+ overrides: tileset.stamp === undefined ? { clarity } : { clarity, stamp: tileset.stamp },
757
+ known: {
758
+ shape: tileset.shape,
759
+ cell: { width: tileset.cell.width, height: tileset.cell.height },
760
+ animRows: tileset.animRows,
761
+ fps: tileset.fps,
762
+ loop: tileset.loop,
763
+ clarity,
764
+ builtin: false
765
+ },
766
+ projectGrid: { width: project.grid.tileWidth, height: project.grid.tileHeight }
767
+ }, warnings);
768
+ await patchMapProject(projectId, (fresh) => {
769
+ const at = fresh.tilesets.findIndex((entry) => entry.id === tileset.id);
770
+ if (at >= 0)
771
+ fresh.tilesets[at] = rebuilt;
772
+ appendJobLog(fresh.logs, "info", `重新整理素材:${rebuilt.name}(按现在的规则重烘,图块序号不变,地图不用改)`);
773
+ });
774
+ // 用真实视图回给界面(调色板 / 说明都要现算,别在这里手搓一份)。
775
+ const view = await mapView(await readMapProject(projectId));
776
+ const fresh = view.tilesets.find((entry) => entry.id === rebuilt.id);
777
+ if (fresh === undefined)
778
+ throw new Error("重新整理后找不到这块素材,请刷新页面");
779
+ return { tileset: fresh, warnings };
780
+ }
641
781
  export async function importMapTileset(projectId, name, base64, opts = {}) {
642
782
  const project = await readProjectOrThrow(projectId);
643
783
  if (base64.trim() === "")
@@ -650,7 +790,8 @@ export async function importMapTileset(projectId, name, base64, opts = {}) {
650
790
  id: newTilesetId(),
651
791
  name: name.trim() === "" ? `素材 ${project.tilesets.length + 1}` : name.trim(),
652
792
  bytes,
653
- overrides: { cell: opts.cell, shape: opts.shape, animRows: opts.animRows }
793
+ overrides: { cell: opts.cell, shape: opts.shape, animRows: opts.animRows, fps: opts.fps, clarity: opts.clarity, scale: opts.scale, loop: opts.loop, stamp: opts.stamp, stampKey: opts.stampKey },
794
+ projectGrid: { width: project.grid.tileWidth, height: project.grid.tileHeight }
654
795
  }, warnings);
655
796
  await patchMapProject(projectId, (fresh) => {
656
797
  fresh.tilesets.push(tileset);
@@ -675,16 +816,47 @@ export async function importSampleTileset(projectId) {
675
816
  const existing = new Set(project.tilesets.map((tileset) => tileset.name));
676
817
  const warnings = [];
677
818
  const created = [];
678
- for (const sample of renderSampleTilesets()) {
819
+ /**
820
+ * 内置素材是按 **32×32 一格**画出来的。项目的网格可能是 16 / 48 / 64 —— 直接塞进去
821
+ * 图块会压边(渲染按素材自己的格子画,和地图网格不一致就错位),所以这里按比例重采样:
822
+ * 整数倍放大用最近邻(像素画放大,边缘干净),缩小 / 非整数倍用面积平均。
823
+ */
824
+ const samples = renderSampleTilesets();
825
+ const targetCell = Math.max(1, Math.round(project.grid.tileWidth));
826
+ const sourceCell = Math.max(1, samples[0]?.cell.width ?? 32);
827
+ const scaled = targetCell !== sourceCell;
828
+ const ratio = targetCell / sourceCell;
829
+ // 整数倍放大用最近邻(像素画放大,边缘干净);缩小 / 非整数倍用面积平均。
830
+ const clarity = ratio >= 2 && Number.isInteger(ratio) ? "sharp" : "smooth";
831
+ for (const sample of samples) {
679
832
  if (existing.has(sample.name)) {
680
833
  warnings.push(`内置素材「${sample.name}」已经在项目里了,跳过。`);
681
834
  continue;
682
835
  }
836
+ let bytes = sample.bytes;
837
+ if (scaled) {
838
+ /**
839
+ * PNG 解码统一走 ffmpeg,而 ffmpeg 只认文件路径 —— 落一个临时文件再删。
840
+ * (`png.ts` 只有编码器;为这一点在 src 里再写一个 PNG 解码器不值得。)
841
+ */
842
+ const size = sizeFromBytes(sample.bytes) ?? { width: sample.cell.width, height: sample.cell.height };
843
+ const scratch = join(mapProjectDir(projectId), `tilesets/${sample.file}.in.png`);
844
+ await writeFile(scratch, sample.bytes);
845
+ try {
846
+ const source = await decodeFile(scratch);
847
+ const fitted = resampleToSize(source, Math.max(1, Math.round(size.width * ratio)), Math.max(1, Math.round(size.height * ratio)), clarity);
848
+ bytes = encodeBitmap(fitted);
849
+ }
850
+ finally {
851
+ await rm(scratch, { force: true });
852
+ }
853
+ }
683
854
  const tileset = await registerTileset(projectId, {
684
855
  id: newTilesetId(),
685
856
  name: sample.name,
686
- bytes: sample.bytes,
687
- known: { shape: sample.shape, cell: sample.cell, animRows: sample.animRows, builtin: true }
857
+ bytes,
858
+ known: { shape: sample.shape, cell: { width: targetCell, height: targetCell }, animRows: sample.animRows, builtin: true },
859
+ projectGrid: { width: targetCell, height: targetCell }
688
860
  }, warnings);
689
861
  await patchMapProject(projectId, (fresh) => {
690
862
  fresh.tilesets.push(tileset);
@@ -699,6 +871,212 @@ export async function importSampleTileset(projectId) {
699
871
  }
700
872
  return { tilesets: created, warnings };
701
873
  }
874
+ // ── AI 生成素材:把对话里生成的一批帧整理成一张暂存的素材图 ────────────────
875
+ /** 一帧源图的字节上限(与上传那条路同一个上限)。 */
876
+ const FRAME_MAX_BYTES = 30 * 1024 * 1024;
877
+ /** 一列最多几帧。 */
878
+ const FRAME_COUNT_MAX = 64;
879
+ /**
880
+ * 把「AI 生成的那几张图」按**事先定好的素材形态**整理成一张可直接导入的素材图,
881
+ * 落在项目的 `ai/` 暂存区。
882
+ *
883
+ * 与 `importMapTileset` 的分工:这里**不进素材列表**。素材的属性在新增那一刻定死、
884
+ * 之后只能删掉重来,所以放给用户在地图编辑器的「新增素材」窗口里确认一次
885
+ * (名字 / 格子 / 用法 / 会动吗都预填好)—— 对话替用户把图整理好,但不替他拍板。
886
+ *
887
+ * 几何口径全在这里定死,调用方(对话里的 agent)不需要自己算:
888
+ * · **格子 = 地图网格**(`cell` 留空时)。图块按原始尺寸画在格子左上角,一格素材
889
+ * 与网格不同尺寸就会压到邻居格上;
890
+ * · 普通:每张裁成方格 → 竖排(`stackFrames`);
891
+ * · 整格:**一块**无缝墙砖 → 从同一块砖的像素拼出 16 种接法(`corner16SheetFromTile`),
892
+ * 「断」的边由代码加收口;
893
+ * · 拼块:每个变体**一块**无缝砖 → 拼出 N 列 × 5 行(`a2SheetFromTiles`),
894
+ * 每一格的四个小格按它自己那一侧的接法加收口。
895
+ *
896
+ * ⚠️ 整格 / 拼块**不再让模型直接画多格排布**:模型画的 n 个格子是各自独立的,而地图上
897
+ * 相邻两格常常取自不同格子 —— 实测一条墙的接缝处边缘差 201、块内相邻列才 58,就是那条
898
+ * 「接缝」。把「一块砖」交给模型、把「怎么拼」留给代码,接缝等于砖自身的环绕缝(最好的
899
+ * 可能值),`tileSeamRatios` 还会把这个环绕缝量出来写进 `notes`。
900
+ */
901
+ export async function composeMapAsset(input) {
902
+ const project = await readProjectOrThrow(input.projectId);
903
+ const files = (input.files ?? []).map((file) => String(file));
904
+ if (files.length === 0)
905
+ throw new Error("没有可整理的帧:files 不能为空。");
906
+ if (files.length > FRAME_COUNT_MAX)
907
+ throw new Error(`一份素材最多 ${FRAME_COUNT_MAX} 张图,收到 ${files.length} 张。`);
908
+ const shape = parseTilesetShape(input.shape) ?? "plain";
909
+ const cell = normalizeCell(input.cell) ?? { width: project.grid.tileWidth, height: project.grid.tileHeight };
910
+ /**
911
+ * 整图:**每张图 = 一帧的整张图**(不是一格),占几格由 `stampCols / stampRows` 定。
912
+ *
913
+ * 与另外三种形态的区别:普通 / 整格 / 拼块都是「一块砖或一格内容」,
914
+ * 整图是「一张画占 N×M 格」—— 所以这里不做任何「从一块砖拼出全部格子」的事,
915
+ * 只把每帧缩到 `cols × rows` 格、竖排、交给导入端的烘焙(4 个旋转)。
916
+ */
917
+ const stampSpec = shape === "stamp"
918
+ ? parseStampSpec({ cols: input.stampCols, rows: input.stampRows, frames: files.length })
919
+ : undefined;
920
+ if (shape === "stamp" && stampSpec === undefined) {
921
+ throw new Error(`整图要给「占几格」:stampCols / stampRows(2~${STAMP_MAX_CELLS})。`);
922
+ }
923
+ /** 一张整图最多和整张地图一样大(再大地图上也画不全)。 */
924
+ if (stampSpec !== undefined) {
925
+ const owning = await readTheDoc(project.id);
926
+ if (owning !== undefined)
927
+ assertStampFitsProject(stampSpec, owning.cols, owning.rows);
928
+ }
929
+ /**
930
+ * 整格只有 16 块、**没有「帧」这一维**(4×4 全是接法,动画行也是接法行),
931
+ * 所以多给几张只有两种可能:形态判断错了,或者想要「会动的整格」(做不到)。
932
+ * 两种都要说清楚 —— 默默用第一张会浪费一次真实计费的生图,只回一句「张数不对」
933
+ * 则会让调用方/用户一直以为是参数问题。
934
+ */
935
+ if (shape === "corner16" && files.length !== 1) {
936
+ throw new Error(`整格自动连接的素材需要**一块**无缝墙砖(收到 ${files.length} 张:16 种接法由宿主从这一块拼出来)。` +
937
+ `整格**没有动画** —— 它只有 16 种接法,多出来的帧没有地方放;想要「既自动连接、又会动」的素材请改用拼块(a2quad),它的帧数就是变体。`);
938
+ }
939
+ const animRows = shape === "plain" ? input.animRows ?? files.length > 1 : false;
940
+ const frames = [];
941
+ /** 每张源图裁掉了多少边(全部为 0 时说明没白边,不用提)。 */
942
+ const trimmedAmounts = [];
943
+ /** 整图抠绿幕的结果(keyed = 被判成背景的像素占比;0 = 没抠)。 */
944
+ const keyedAmounts = [];
945
+ for (const file of files) {
946
+ let info;
947
+ try {
948
+ info = await stat(file);
949
+ }
950
+ catch {
951
+ throw new Error(`读不到帧文件:${file}`);
952
+ }
953
+ if (!info.isFile())
954
+ throw new Error(`不是文件:${file}`);
955
+ if (info.size > FRAME_MAX_BYTES) {
956
+ throw new Error(`帧文件 ${(info.size / 1024 / 1024).toFixed(1)}MB 超过上限 ${FRAME_MAX_BYTES / 1024 / 1024}MB:${file}`);
957
+ }
958
+ /**
959
+ * 模型经常在四周留一圈白边(提示词里写了「不要留边」也拦不住)。裁边要在**这里**做:
960
+ * ① 这一步拿到的是原图,裁剪无损;② 拼成一张素材图之后再裁就只能裁到整张的边,
961
+ * 多帧竖排时中间几帧的白框裁不到。
962
+ */
963
+ /**
964
+ * 整图先抠绿幕:它是「立在格子上的物件」,绿幕是模型加的假背景 ——
965
+ * 留着会在地图上出现一块绿框,而且把本该空着的角落也涂满。
966
+ * 其它形态不抠(它们的背景就是材质本身)。
967
+ */
968
+ const keyed = shape === "stamp" ? keyStampBackground(await decodeFile(file), (rgba, width, height) => keyGreen(rgba, width, height, STAMP_KEY_OPTIONS)) : undefined;
969
+ if (keyed !== undefined)
970
+ keyedAmounts.push(keyed.keyed);
971
+ const trimmed = trimUniformBorder(keyed === undefined ? (keyed === undefined ? await decodeFile(file) : keyed.bitmap) : keyed.bitmap);
972
+ trimmedAmounts.push({ file, left: trimmed.left, top: trimmed.top, right: trimmed.right, bottom: trimmed.bottom });
973
+ frames.push(trimmed.bitmap);
974
+ }
975
+ /**
976
+ * 「图片最终处理的清晰度」:**这一步先不缩到格子**。
977
+ *
978
+ * 用户在「新增素材」里选好清晰度再缩,才可能真的更清楚 —— 如果这里就用最近邻缩到
979
+ * 32px,细节已经丢了,后面再选什么算法都救不回来。所以这里只留到 `cell × k`
980
+ * (k 由源图每块多大决定,上限 `MAX_ASSET_SCALE`),并把这个倍数交给回链:
981
+ * 「新增素材」据此知道「这张图每格 128px,导入时按清晰度缩到 32px」。
982
+ */
983
+ const sourceBlockPx = (() => {
984
+ if (shape === "corner16")
985
+ return frames[0].width; // 一张 = 一块
986
+ if (shape === "a2quad")
987
+ return Math.min(frames[0].width, Math.round(frames[0].height / A2_ROWS)); // 一张 = 一列 5 行
988
+ /**
989
+ * 整图:一张 = 一整幅画(cols × rows 格)。按「一格平均多少像素」估倍数,
990
+ * 这样 2048 的图对上 3×3 格时会留到 4 倍,导进 32px 格子也还够细。
991
+ */
992
+ if (shape === "stamp") {
993
+ const spec = stampSpec;
994
+ return Math.min(frames[0].width / spec.cols, frames[0].height / spec.rows);
995
+ }
996
+ return Math.min(frames[0].width, frames[0].height); // 普通:一张 = 一格
997
+ })();
998
+ const scale = Math.max(1, Math.min(MAX_ASSET_SCALE, Math.floor(sourceBlockPx / Math.max(1, Math.min(cell.width, cell.height)))));
999
+ const bigCell = { width: cell.width * scale, height: cell.height * scale };
1000
+ const plan = sheetPlanOf(shape, bigCell, frames.length, stampSpec);
1001
+ const notes = [];
1002
+ if (shape === "stamp") {
1003
+ const keyedCount = keyedAmounts.filter((fraction) => fraction > 0).length;
1004
+ if (keyedCount > 0) {
1005
+ const average = keyedAmounts.reduce((sum, value) => sum + value, 0) / keyedAmounts.length;
1006
+ notes.push(`已抠掉绿幕背景(平均 ${Math.round(average * 100)}% 的像素变成透明${keyedCount < frames.length ? `,${keyedCount}/${frames.length} 张抠掉了` : ""}):` +
1007
+ `整图是「立在格子上的物件」,背景要透明才看得见地砖;留着绿幕的话地图上会多出一块绿框。`);
1008
+ }
1009
+ else {
1010
+ notes.push("**没检测到绿幕背景**:这次按原图用了(画面会连背景一起印到地图上)。想要背景透明,让模型把背景画成**纯绿**(#00FF00 一类,不要渐变 / 阴影),或者自己用透明 PNG。");
1011
+ }
1012
+ }
1013
+ {
1014
+ const touched = trimmedAmounts.filter((entry) => entry.left + entry.top + entry.right + entry.bottom > 0);
1015
+ if (touched.length > 0) {
1016
+ const first = touched[0];
1017
+ const sides = [first.left > 0 ? `左 ${first.left}px` : "", first.top > 0 ? `上 ${first.top}px` : "", first.right > 0 ? `右 ${first.right}px` : "", first.bottom > 0 ? `下 ${first.bottom}px` : ""].filter(Boolean).join("、");
1018
+ notes.push(`自动裁掉了四周的纯色边框(${sides}${touched.length > 1 ? `,${touched.length}/${frames.length} 张都有` : ""}):模型在提示词之外另留了一圈边,` +
1019
+ `留着的话每块素材边上都会带一道白框。裁完才是真正的画面范围。`);
1020
+ }
1021
+ }
1022
+ /**
1023
+ * 源图比例与目标差得多时提醒一句:整格 / 拼块要的是**一块方砖**,长宽比差得多会被
1024
+ * 拉伸(内容变形,但砖的性质还在);普通要的是格子比例。
1025
+ */
1026
+ /** 整图比的是「整张画」的比例(cols × rows 格),不是一格的方形。 */
1027
+ const targetRatio = stampSpec === undefined ? cell.width / cell.height : (stampSpec.cols * cell.width) / (stampSpec.rows * cell.height);
1028
+ const sourceRatios = frames.map((frame) => frame.width / frame.height);
1029
+ const worst = sourceRatios.reduce((acc, ratio) => Math.max(acc, Math.abs(Math.log(ratio / targetRatio))), 0);
1030
+ if (worst > Math.log(1.6)) {
1031
+ const wanted = stampSpec === undefined ? `${cell.width}:${cell.height}` : `${stampSpec.cols * cell.width}:${stampSpec.rows * cell.height}(整张 ${stampSpec.cols}×${stampSpec.rows} 格)`;
1032
+ notes.push(`这张图要求的长宽比是 ${wanted}(${shape === "corner16" ? "整格" : shape === "a2quad" ? "拼块" : "普通"}素材的**一块**),模型给的是 ${sourceRatios
1033
+ .map((ratio) => ratio.toFixed(2))
1034
+ .join(" / ")}:已经拉伸对齐,但内容会被压扁或拉长。下次可以在提示词里要求按这个比例出图。`);
1035
+ }
1036
+ /**
1037
+ * 砖自身的环绕缝:整格 / 拼块的图都是「一块砖铺出去」,砖左右 / 上下接不上自己的话,
1038
+ * 地图上每隔一格就会出现一道可见的缝 —— 那正是这次要根除的东西,所以必须量出来说清。
1039
+ */
1040
+ if (shape !== "plain" && shape !== "stamp") {
1041
+ const seams = frames.map((frame) => tileSeamRatios(resampleToSize(frame, Math.max(1, Math.floor(cell.width)), Math.max(1, Math.floor(cell.height)), "smooth")));
1042
+ const bad = seams.filter((seam) => Math.max(seam.horizontal, seam.vertical) > 2.2);
1043
+ if (bad.length > 0) {
1044
+ const worstSeam = bad.reduce((acc, seam) => (Math.max(seam.horizontal, seam.vertical) > Math.max(acc.horizontal, acc.vertical) ? seam : acc), bad[0]);
1045
+ notes.push(`这块砖自己接不上自己(左右缝是内部的 ${worstSeam.horizontal.toFixed(1)} 倍、上下缝是 ${worstSeam.vertical.toFixed(1)} 倍):平铺出去每隔一格会有一道可见的缝。` +
1046
+ `让模型重画一张**四边都能与自身相接**的无缝材质(画面均匀、边缘不要有只出现一次的细节),比调格子参数有用。`);
1047
+ }
1048
+ }
1049
+ /**
1050
+ * 大图 → `cell × k` 这一步同样是**缩小**(2048 → 128 也有 16 倍),最近邻一样会走样,
1051
+ * 所以这里固定用面积平均;用户选的清晰度作用于最后那一步 `k× → 1×`(导入时)。
1052
+ */
1053
+ const sheet = stampSpec === undefined ? composeAssetSheet(frames, plan, "smooth") : composeStampSource(frames, stampSpec, bigCell, "smooth");
1054
+ const name = input.name === undefined || String(input.name).trim() === "" ? "AI 素材" : String(input.name).trim();
1055
+ const file = `ai/${safeAssetStem(name)}.png`;
1056
+ await mkdir(join(mapProjectDir(project.id), "ai"), { recursive: true });
1057
+ await writeFile(mapAssetPath(project.id, file), encodeBitmap(sheet));
1058
+ const shapeLabel = shape === "plain" ? "普通" : shape === "corner16" ? "整格" : shape === "a2quad" ? "拼块" : "整图";
1059
+ await patchMapProject(project.id, (fresh) => {
1060
+ appendJobLog(fresh.logs, "info", `整理 AI 素材:${name}(${shapeLabel} / ${frames.length} 张 → ${sheet.width}×${sheet.height}${scale > 1 ? `,每格 ${bigCell.width}px(${scale} 倍,导入时按清晰度缩到 ${cell.width}px)` : ""},落在 ${file},等你在「新增素材」里确认)`);
1061
+ });
1062
+ return {
1063
+ file,
1064
+ name,
1065
+ shape,
1066
+ cell,
1067
+ width: sheet.width,
1068
+ height: sheet.height,
1069
+ frameCount: shape === "corner16" ? 1 : frames.length,
1070
+ variants: shape === "a2quad" ? frames.length : 1,
1071
+ animRows,
1072
+ /** 仅整图:占几格 / 几帧(回链据此预填「占几格」)。 */
1073
+ ...(stampSpec === undefined ? {} : { stamp: { cols: stampSpec.cols, rows: stampSpec.rows, frames: stampSpec.frames } }),
1074
+ ...(stampSpec === undefined ? {} : { keyed: keyedAmounts.reduce((sum, value) => sum + value, 0) / Math.max(1, keyedAmounts.length) }),
1075
+ /** 这张素材图是「每格几倍分辨率」:1 = 就是格子大小;>1 = 导入时还要按清晰度缩一次。 */
1076
+ scale,
1077
+ notes
1078
+ };
1079
+ }
702
1080
  function newTilesetId() {
703
1081
  return `ts${Date.now().toString(36)}${randomUUID().slice(0, 4)}`;
704
1082
  }
@@ -713,22 +1091,107 @@ async function registerTileset(projectId, input, warnings) {
713
1091
  * (明确拒绝,不静默改成别的值),而原图是在这个函数里写盘的 —— 先写后抛会留下孤儿图。
714
1092
  */
715
1093
  const overrideCell = input.overrides?.cell === undefined ? undefined : normalizeCell(input.overrides.cell);
1094
+ const loop = parseAssetLoop(input.overrides?.loop);
1095
+ const clarity = parseClarity(input.overrides?.clarity);
1096
+ const scale = parseAssetScale(input.overrides?.scale);
1097
+ /**
1098
+ * 整图:规格(占几格 / 几帧 / 区域)先解析、先校验 —— 与别的属性一样「先校验再写文件」。
1099
+ * 有规格就**强制**形态为 `stamp`(用户不用再选一次,也避免「选了整图却没给占格」)。
1100
+ */
1101
+ const stamp = parseStampSpec(input.overrides?.stamp);
1102
+ /**
1103
+ * 整图最多和整张地图一样大。校验放在**写盘之前**(与其它属性同一个原则):
1104
+ * `projectGrid` 是像素,这里用不到 —— 地图格子数从项目里现读(`registerTileset` 有 projectId)。
1105
+ */
1106
+ if (stamp !== undefined) {
1107
+ // 格子数是**地图文档**的属性(`MapDoc.cols/rows`),不在 project.json 里。
1108
+ const owning = await readTheDoc(projectId);
1109
+ if (owning !== undefined)
1110
+ assertStampFitsProject(stamp, owning.cols, owning.rows);
1111
+ }
1112
+ const forcedShape = parseTilesetShape(input.overrides?.shape);
716
1113
  const ext = sniffImageExt(input.bytes);
717
1114
  const relative = `tilesets/${input.id}.${ext}`;
718
1115
  await mkdir(join(mapProjectDir(projectId), "tilesets"), { recursive: true });
719
- // 写原图(不改写:形态参数随便调,随时能重算)
720
- await writeFile(mapAssetPath(projectId, relative), input.bytes);
721
- const size = await probeSize(mapAssetPath(projectId, relative), input.bytes);
1116
+ /**
1117
+ * 「图片最终处理的清晰度」就是在这一步生效的:
1118
+ * 素材图如果是「每格 k 倍分辨率」(AI 生成的那条路会带 `scale`),先按用户选的清晰度
1119
+ * 缩到 1 倍再落盘 —— 于是**存下来的素材图正好是格子大小**,调色板 / 渲染 / legend
1120
+ * 全都不用改,缩小的算法只在这一处决定。
1121
+ *
1122
+ * `scale = 1`(自己导一张格子大小的图,绝大多数情况)时一个像素都不动。
1123
+ */
1124
+ const target = mapAssetPath(projectId, relative);
1125
+ // 先落原字节(解码要读盘),`scale > 1` 时再把它换成缩好的那份。
1126
+ await writeFile(target, input.bytes);
1127
+ let storedBytes = input.bytes;
1128
+ /**
1129
+ * 整图的格子**必须等于地图网格**(整图一次占 N×M 格,格子不符就必然错位),
1130
+ * 所以这里直接拿项目网格当格尺寸,并缩到 `占格 × 帧数` 的目标尺寸再烘焙 4 个旋转。
1131
+ */
1132
+ const stampCell = stamp === undefined ? undefined : (overrideCell ?? { width: input.projectGrid?.width ?? 32, height: input.projectGrid?.height ?? 32 });
1133
+ try {
1134
+ // 「导入时抠绿幕」:手动导一张带绿幕的整图时用(AI 那条路在 composeMapAsset 里已经抠过)。
1135
+ const keyedSource = input.overrides?.stampKey === true;
1136
+ if (stamp !== undefined && stampCell !== undefined) {
1137
+ const rawSource = await decodeFile(target);
1138
+ const source = keyedSource ? keyStampBackground(rawSource, (rgba, width, height) => keyGreen(rgba, width, height, STAMP_KEY_OPTIONS)).bitmap : rawSource;
1139
+ if (keyedSource) {
1140
+ // 抠完的源图要写回去:下面 resample + 烘焙读的是盘上这份(也便于排查)。
1141
+ storedBytes = encodeBitmap(source);
1142
+ await writeFile(target, storedBytes);
1143
+ }
1144
+ const targetWidth = Math.max(1, stamp.cols * stampCell.width);
1145
+ const targetHeight = Math.max(1, stamp.rows * stamp.frames * stampCell.height);
1146
+ /**
1147
+ * ⚠️ 长宽比对不上时说一声:占几格填错了(例如 3×3 填成 3×2)时,画面会被拉伸,
1148
+ * 而「拉伸」这件事本身不报错、只体现在肉眼里。
1149
+ */
1150
+ const ratioSource = source.width / Math.max(1, source.height);
1151
+ const ratioTarget = targetWidth / Math.max(1, targetHeight);
1152
+ if (Math.abs(ratioSource - ratioTarget) / Math.max(1e-6, ratioTarget) > 0.05) {
1153
+ warnings.push(`这张图的长宽比(${source.width}×${source.height})和「占 ${stamp.cols}×${stamp.rows} 格 × ${stamp.frames} 帧」对不上,` +
1154
+ `已经按目标尺寸拉齐 —— 如果画面看起来被压扁/拉长,多半是占格填错了,删掉重新新增一张。`);
1155
+ }
1156
+ void targetWidth;
1157
+ void targetHeight;
1158
+ // 缩到「一格 = 一格地图格子」再烘 4 个旋转(与原地重烘同一条口径)。
1159
+ const baked = stampTilesetImage(source, stamp, stampCell, clarity);
1160
+ storedBytes = encodeBitmap(baked);
1161
+ await writeFile(target, storedBytes);
1162
+ }
1163
+ else if (scale > 1) {
1164
+ const source = await decodeFile(target);
1165
+ const fitted = resampleToSize(source, Math.max(1, Math.round(source.width / scale)), Math.max(1, Math.round(source.height / scale)), clarity);
1166
+ storedBytes = encodeBitmap(fitted);
1167
+ await writeFile(target, storedBytes);
1168
+ }
1169
+ }
1170
+ catch (error) {
1171
+ // 缩图失败不能留下一张「半成品」素材图:删掉再抛,用户重试时不会撞见上一张坏图。
1172
+ await rm(target, { force: true });
1173
+ throw error;
1174
+ }
1175
+ const size = await probeSize(target, storedBytes);
722
1176
  const guess = input.known ?? detectLayout(size.width, size.height);
723
- const shape = parseTilesetShape(input.overrides?.shape) ?? guess.shape;
724
- const cell = overrideCell ?? guess.cell;
1177
+ const shape = stamp !== undefined ? "stamp" : (forcedShape ?? guess.shape);
1178
+ const cell = stamp !== undefined ? (stampCell ?? guess.cell) : (overrideCell ?? guess.cell);
725
1179
  const animRows = input.known?.animRows ?? (input.overrides?.animRows === true);
1180
+ /** 播放速度:**先校验再写文件**(`parseAssetFps` 对越界值是抛错的,见同一个函数里的注释)。 */
1181
+ const fps = parseAssetFps(input.overrides?.fps);
1182
+ if (input.projectGrid !== undefined &&
1183
+ input.overrides?.cell === undefined &&
1184
+ input.known === undefined &&
1185
+ (cell.width !== input.projectGrid.width || cell.height !== input.projectGrid.height)) {
1186
+ warnings.push(`这张素材一格是 ${cell.width}×${cell.height},而地图格子是 ${input.projectGrid.width}×${input.projectGrid.height} —— ` +
1187
+ `图块只会画在格子左上角,看起来像缩小了一圈。导入时把「格子大小」填成 ${input.projectGrid.width}×${input.projectGrid.height}(= 地图网格)就对了。`);
1188
+ }
726
1189
  if (!commonSizeFits(size.width, size.height)) {
727
1190
  // ⚠️ 文案要跟着产品规则走:属性在新增时定死、界面不再提供修改入口 ——
728
1191
  // 所以这里告诉用户「删掉重新新增」,而不是让他去找一个界面上没有的入口。
729
1192
  warnings.push(`这张图(${size.width}×${size.height})不是常见瓦片尺寸的整数倍,已按 ${cell.width}×${cell.height} 试切;不对的话删掉它、按你想要的格子大小重新新增一张。`);
730
1193
  }
731
- const tiles = buildTiles({ shape, cell, imageWidth: size.width, imageHeight: size.height, animRows });
1194
+ const tiles = buildTiles({ shape, cell, imageWidth: size.width, imageHeight: size.height, animRows, stamp });
732
1195
  const tileset = {
733
1196
  id: input.id,
734
1197
  name: input.name,
@@ -738,7 +1201,11 @@ async function registerTileset(projectId, input, warnings) {
738
1201
  cell,
739
1202
  shape,
740
1203
  animRows,
741
- variants: variantsOf(shape, cell, size.width, size.height, animRows),
1204
+ stamp,
1205
+ variants: stamp === undefined ? variantsOf(shape, cell, size.width, size.height, animRows) : stamp.frames,
1206
+ loop,
1207
+ clarity,
1208
+ fps,
742
1209
  // 内置素材:属性**不允许修改**(见 saveMapTileset),可以整张删掉,也能一键恢复
743
1210
  builtin: input.known?.builtin === true ? true : undefined,
744
1211
  tiles
@@ -803,13 +1270,45 @@ export async function saveMapTileset(projectId, tilesetId, patch) {
803
1270
  if (tileset === undefined)
804
1271
  throw new Error(`素材不存在:${tilesetId}`);
805
1272
  /**
806
- * 内置素材的属性**不允许修改**(这是产品约定:属性在新增那一刻定下来)。
807
- * 想换形态 / 格子就自己新增一张;内置的可以整张删掉,再用「恢复默认素材」拿回来。
1273
+ * 内置素材:**表现层属性可以改**(名字 / 播放速度 / 循环方式),**几何不许改**
1274
+ * (形态 / 格子尺寸 —— 那会重切图块、把画过的格子整体错位,而且内置素材是按 32 格画的)。
1275
+ *
1276
+ * 老约定是「内置一律不许改」,但用户要的恰恰是「改名 / 调速度」这类轻量改动,
1277
+ * 所以这里把边界收在「几何」上,而不是「整张图」。
808
1278
  */
809
- if (tileset.builtin === true)
810
- throw new Error(`「${tileset.name}」是内置素材,属性不能改 —— 可以删掉它,或者自己新增一张素材。`);
1279
+ const touchesGeometry = patch.cell !== undefined ||
1280
+ patch.shape !== undefined ||
1281
+ (typeof patch.animRows === "boolean" && patch.animRows !== tileset.animRows) ||
1282
+ (nextCell !== undefined && (nextCell.width !== tileset.cell.width || nextCell.height !== tileset.cell.height)) ||
1283
+ (nextShape !== undefined && nextShape !== tileset.shape);
1284
+ if (tileset.builtin === true && touchesGeometry) {
1285
+ throw new Error(`「${tileset.name}」是内置素材:名字 / 播放速度 / 循环方式可以改,形态与格子尺寸不能改 —— 想换就自己新增一张。`);
1286
+ }
811
1287
  if (typeof patch.name === "string" && patch.name.trim() !== "")
812
1288
  tileset.name = patch.name.trim();
1289
+ /**
1290
+ * 播放速度是**表现层属性**(不动几何、不动序号),所以单独走一条:不触发重切、
1291
+ * 不重映射图层数据,只是换个数 —— 想调快调慢随时改,不用删掉重来。
1292
+ * `null` = 清掉(跟「设置 → 动画速度」那条全局速度走)。
1293
+ */
1294
+ /**
1295
+ * 循环方式:只改「帧序怎么展开」,同样不动几何 / 序号,随时能改。
1296
+ * 改完立刻生效(下一次 `mapPlan` 就是新帧序),不需要重切素材。
1297
+ */
1298
+ if (patch.loop !== undefined) {
1299
+ const nextLoop = parseAssetLoop(patch.loop);
1300
+ if (nextLoop !== tileset.loop) {
1301
+ tileset.loop = nextLoop;
1302
+ appendJobLog(fresh.logs, "info", `改素材循环方式:${tileset.name}(${nextLoop === "forward" ? "正放" : nextLoop === "reverse" ? "倒放" : "来回"})`);
1303
+ }
1304
+ }
1305
+ if (patch.fps !== undefined) {
1306
+ const nextFps = parseAssetFps(patch.fps);
1307
+ if (nextFps !== tileset.fps) {
1308
+ tileset.fps = nextFps;
1309
+ appendJobLog(fresh.logs, "info", `改素材播放速度:${tileset.name}(${nextFps === undefined ? "跟全局" : `${nextFps} 帧/秒`})`);
1310
+ }
1311
+ }
813
1312
  const shape = patch.shape ?? tileset.shape;
814
1313
  const cell = nextCell ?? tileset.cell;
815
1314
  const animRows = typeof patch.animRows === "boolean" ? patch.animRows : tileset.animRows;
@@ -883,6 +1382,19 @@ async function remapDocToIndices(projectId, before, after) {
883
1382
  await writeTheDoc(projectId, doc);
884
1383
  return { pruned: lost, warnings };
885
1384
  }
1385
+ /** 摘掉引用了某张素材的整图,返回张数(素材被删 / 换过切分时用)。 */
1386
+ async function dropStampsOfTileset(projectId, tilesetId) {
1387
+ const doc = await theDocOrFresh(projectId);
1388
+ const keep = doc.stamps.filter((stamp) => stamp.tilesetId !== tilesetId);
1389
+ const dropped = doc.stamps.length - keep.length;
1390
+ if (dropped === 0)
1391
+ return 0;
1392
+ doc.stamps = keep;
1393
+ doc.updatedAt = new Date().toISOString();
1394
+ scheduleDocWrite(projectId, doc);
1395
+ await flushMapDoc(projectId);
1396
+ return dropped;
1397
+ }
886
1398
  export async function removeMapTileset(projectId, tilesetId) {
887
1399
  const project = await readProjectOrThrow(projectId);
888
1400
  const tileset = project.tilesets.find((item) => item.id === tilesetId);
@@ -896,7 +1408,15 @@ export async function removeMapTileset(projectId, tilesetId) {
896
1408
  await rm(mapAssetPath(projectId, tileset.file), { force: true });
897
1409
  const fresh = await readProjectOrThrow(projectId);
898
1410
  const remap = await remapDocToIndices(projectId, beforeKeys, indexKeys(fresh.tilesets));
899
- return { removed: tileset.name, pruned: remap.pruned, warnings: remap.warnings };
1411
+ /**
1412
+ * 整图是**独立的对象**(不占 `layer.data`),所以 `remapDocToIndices` 清不到它们 ——
1413
+ * 素材没了、整图还在的话渲染器只会报一句「素材不见了」而地图上留个洞。这里一起摘掉。
1414
+ */
1415
+ const droppedStamps = await dropStampsOfTileset(projectId, tilesetId);
1416
+ const warnings = [...remap.warnings];
1417
+ if (droppedStamps > 0)
1418
+ warnings.push(`顺带删掉了 ${droppedStamps} 张用「${tileset.name}」印的整图(素材没了,它们画不出来)。`);
1419
+ return { removed: tileset.name, pruned: remap.pruned, warnings };
900
1420
  }
901
1421
  function xorshift32(seed) {
902
1422
  let state = (seed >>> 0) === 0 ? 0xffffffff : seed >>> 0;
@@ -920,16 +1440,31 @@ function normalizeSeed(seed) {
920
1440
  return (n >>> 0) === 0 ? 0xffffffff : n >>> 0;
921
1441
  }
922
1442
  async function normalizeTilePool(tiles, project) {
923
- const available = flatTiles(project.tilesets).map((tile) => tile.index);
1443
+ /**
1444
+ * 整图**不进随机池**:它一次占 N×M 格、要旋转、还要带区域,按格刷只会得到一堆错位的碎片
1445
+ * (`paint` 里对整图的图块序号本来就会跳过)。用户手选了也剔掉,并留一条警告说明原因。
1446
+ */
1447
+ const flat = flatTiles(project.tilesets);
1448
+ const stampValues = new Set();
1449
+ for (const tileset of project.tilesets) {
1450
+ if (tileset.stamp === undefined)
1451
+ continue;
1452
+ for (const entry of flat)
1453
+ if (entry.tilesetId === tileset.id)
1454
+ stampValues.add(entry.index);
1455
+ }
1456
+ const available = flat.map((tile) => tile.index).filter((index) => !stampValues.has(index));
924
1457
  if (tiles === undefined || tiles.length === 0)
925
1458
  return available;
926
- const max = available.length;
927
- return tiles.map((value) => {
1459
+ const max = flat.length;
1460
+ return tiles
1461
+ .map((value) => {
928
1462
  const n = Math.round(Number(value));
929
1463
  if (!Number.isFinite(n) || n < 0 || n > max)
930
1464
  throw new Error(`图块序号越界:${String(value)}(可选 0..${max})`);
931
1465
  return n;
932
- });
1466
+ })
1467
+ .filter((n) => !stampValues.has(n));
933
1468
  }
934
1469
  /**
935
1470
  * 一键铺满某一层(整个操作是**一次提交**,所以一次撤销就能回到原样)。
@@ -951,6 +1486,9 @@ export async function runMapGenerate(projectId, opts) {
951
1486
  const pool = await normalizeTilePool(opts.tiles, project);
952
1487
  const seed = normalizeSeed(opts.seed);
953
1488
  const warnings = [];
1489
+ if (pool.length === 0) {
1490
+ warnings.push("没有可铺的图块:整图不能一笔一格地铺(它一次占 N×M 格),先把普通 / 整格 / 拼块素材选进「一键生成」。");
1491
+ }
954
1492
  const values = generateValues(opts.kind, doc.cols, doc.rows, pool, seed, warnings);
955
1493
  const cells = [];
956
1494
  for (let r = 0; r < doc.rows; r++) {
@@ -1193,7 +1731,7 @@ export async function mapPlan(projectId, o) {
1193
1731
  const preview = cloneDoc(doc);
1194
1732
  // 同一个 applyOps:预览与真实编辑**走同一套校验与语义**,不会画出「提交后不一样」的东西
1195
1733
  const previewLayout = layoutOf(project.grid, preview.cols, preview.rows);
1196
- const overlay = applyOps(preview, o.pending, previewLayout);
1734
+ const overlay = applyOps(preview, o.pending, previewLayout, { stampSpecOf: stampSpecResolver(project) });
1197
1735
  doc = preview;
1198
1736
  for (const key of dirtyChunksFor(overlay.dirty, previewLayout))
1199
1737
  forced.add(key);
@@ -1216,7 +1754,9 @@ export async function mapPlan(projectId, o) {
1216
1754
  chunks: plan.chunks.filter((chunk) => wanted.has(chunk.key) && (!have.has(chunk.key) || forced.has(chunk.key))),
1217
1755
  legend: plan.legend,
1218
1756
  markers: plan.markers,
1757
+ ...(o.pass === true ? { pass: passCellsOf(project, doc) } : {}),
1219
1758
  fps: plan.fps,
1759
+ fpsMax: plan.fpsMax,
1220
1760
  frameCount: plan.frameCount,
1221
1761
  truncated,
1222
1762
  warnings: plan.warnings
@@ -1224,7 +1764,7 @@ export async function mapPlan(projectId, o) {
1224
1764
  }
1225
1765
  // ── 视图 ──────────────────────────────────────────────────────────────────
1226
1766
  export function mapAssetBase(projectId) {
1227
- return `/dsh-game-material-master/map-assets/${projectId}/`;
1767
+ return assetBasePath(`/dsh-game-material-master/map-assets/${projectId}/`);
1228
1768
  }
1229
1769
  /**
1230
1770
  * 界面视图。
@@ -1232,6 +1772,26 @@ export function mapAssetBase(projectId) {
1232
1772
  * `options` 里的 `projectId` / `origin` 是旧调用的兼容位(**视图一律用相对路径**,
1233
1773
  * 绝对 URL 由 `mapSnapshot` 拼给模型)—— 留着是为了不改动已有的调用点签名。
1234
1774
  */
1775
+ /**
1776
+ * 每张素材图的版本号(文件 mtime,毫秒):界面拼 URL 时带 `?v=`。
1777
+ *
1778
+ * 少了它,`recomposeMapTileset`(原地重烘)之后浏览器会继续用缓存里的旧图 ——
1779
+ * 表现是「重烘跑完了,画面一点没变」,只能靠硬刷新救。
1780
+ */
1781
+ export async function tilesetRevisions(projectId) {
1782
+ const project = await readProjectOrThrow(projectId);
1783
+ return new Map(await Promise.all(project.tilesets.map(async (tileset) => [tileset.id, await fileRevision(join(mapProjectDir(projectId), tileset.file))])));
1784
+ }
1785
+ /** 文件 mtime(毫秒);取不到就给 undefined(界面那边会退化成不带 `?v=`)。 */
1786
+ async function fileRevision(path) {
1787
+ try {
1788
+ const info = await stat(path);
1789
+ return Math.round(info.mtimeMs);
1790
+ }
1791
+ catch {
1792
+ return undefined;
1793
+ }
1794
+ }
1235
1795
  export async function mapView(p, options = {}) {
1236
1796
  void options;
1237
1797
  const doc = await theDocOrFresh(p.id);
@@ -1239,6 +1799,8 @@ export async function mapView(p, options = {}) {
1239
1799
  const listing = await readExportListingRelative(p);
1240
1800
  const state = historyState(p.id);
1241
1801
  const layers = doc.layers.map((layer) => ({ id: layer.id, name: layer.name, filled: filledCount(doc, layer.id) }));
1802
+ // 素材图的版本号(mtime)先批量取好:`map` 里不能用 await,只能先算。
1803
+ const revisions = await tilesetRevisions(p.id);
1242
1804
  return {
1243
1805
  id: p.id,
1244
1806
  name: p.name,
@@ -1256,9 +1818,14 @@ export async function mapView(p, options = {}) {
1256
1818
  shape: tileset.shape,
1257
1819
  animRows: tileset.animRows,
1258
1820
  variants: tileset.variants,
1821
+ loop: tileset.loop,
1822
+ clarity: tileset.clarity,
1823
+ fps: tileset.fps,
1824
+ stamp: tileset.stamp === undefined ? undefined : { cols: tileset.stamp.cols, rows: tileset.stamp.rows, frames: tileset.stamp.frames },
1259
1825
  tileCount: tileset.tiles.length,
1826
+ rev: revisions.get(tileset.id),
1260
1827
  builtin: tileset.builtin === true ? true : undefined,
1261
- reason: layoutFor(tileset.shape, tileset.cell, tileset.imageWidth, tileset.imageHeight).reason,
1828
+ reason: layoutFor(tileset.shape, tileset.cell, tileset.imageWidth, tileset.imageHeight, tileset.stamp).reason,
1262
1829
  palette: paletteFor(tileset, flat)
1263
1830
  })),
1264
1831
  legend: flat.map((tile) => ({ index: tile.index, tilesetId: tile.tilesetId, rect: tile.tile.rect })),
@@ -1289,8 +1856,40 @@ export async function mapView(p, options = {}) {
1289
1856
  */
1290
1857
  function paletteFor(tileset, flat) {
1291
1858
  const mine = flat.filter((tile) => tile.tilesetId === tileset.id);
1292
- if (tileset.shape !== "a2quad")
1859
+ /**
1860
+ * 整图:调色板里**只有一条**,缩略图是**整张图**(frame 0 / 旋转 0 的整块)。
1861
+ *
1862
+ * 它印出来占 N×M 格、要旋转、要带区域 —— 一条一条列出 36 个小格只会让人
1863
+ * 以为「整图可以一格一格刷」(那正是它要解决的问题)。
1864
+ */
1865
+ if (tileset.shape === "stamp" && tileset.stamp !== undefined) {
1866
+ const spec = tileset.stamp;
1867
+ const first = mine.find((tile) => (tile.tile.stamp?.frame ?? 0) === 0 && tile.tile.stamp?.rot === 0 && tile.tile.stamp.r === 0 && tile.tile.stamp.c === 0);
1868
+ if (first === undefined)
1869
+ return [];
1870
+ return [
1871
+ {
1872
+ index: first.index,
1873
+ rect: { x: 0, y: 0, width: spec.cols * tileset.cell.width, height: spec.rows * tileset.cell.height }
1874
+ }
1875
+ ];
1876
+ }
1877
+ if (tileset.shape !== "a2quad") {
1878
+ /**
1879
+ * 「翻页图」(`animRows`):同一列的每一行是**同一个逻辑块的不同帧**,帧由宿主按全局帧号
1880
+ * 现推(`maprender` 的 `cycle`),所以调色板每列只出**第 0 帧**那一条。
1881
+ *
1882
+ * 每帧都出一条的话,用户看到的就是 N 个一模一样的笔刷 —— 内置道具图(8 列 × 5 帧)
1883
+ * 曾经就是这样:`animRows` 少写了一个 true,40 个小格全成了独立图块,
1884
+ * 调色板里 40 条有 32 条逐像素重复。
1885
+ */
1886
+ if (tileset.animRows === true) {
1887
+ const first = mine.filter((tile) => (tile.tile.frame ?? 0) === 0);
1888
+ const list = first.length > 0 ? first : mine.slice(0, 1);
1889
+ return list.map((tile) => ({ index: tile.index, rect: tile.tile.rect }));
1890
+ }
1293
1891
  return mine.map((tile) => ({ index: tile.index, rect: tile.tile.rect }));
1892
+ }
1294
1893
  let fullRow = 0;
1295
1894
  for (const tile of mine)
1296
1895
  fullRow = Math.max(fullRow, tile.tile.shape ?? 0);
@@ -1552,7 +2151,7 @@ async function readPreviewFiles(projectId) {
1552
2151
  }
1553
2152
  }
1554
2153
  function absoluteAssetUrl(projectId, origin, relative) {
1555
- return `${origin}/dsh-game-material-master/map-assets/${projectId}/${relative}`;
2154
+ return `${origin}${assetBasePath(`/dsh-game-material-master/map-assets/${projectId}/`)}${relative}`;
1556
2155
  }
1557
2156
  /**
1558
2157
  * 工具用的快照:把界面里的**相对**资源路径全部换成可点的**绝对** URL
@@ -1578,7 +2177,7 @@ export async function mapSnapshot(project, origin, options = {}) {
1578
2177
  nextActions.push({ step: "done", why: "素材、地图、导出都有产物了。可以继续改地图,或 runMapPreview({projectId}) 重新出验收图。" });
1579
2178
  return {
1580
2179
  ...rest,
1581
- assetBase: `${origin}/dsh-game-material-master/map-assets/${project.id}/`,
2180
+ assetBase: `${origin}${mapAssetBase(project.id)}`,
1582
2181
  tilesets: view.tilesets.map((tileset) => ({ ...tileset, url: absoluteAssetUrl(project.id, origin, tileset.file) })),
1583
2182
  previewUrls: preview.map((relative) => absoluteAssetUrl(project.id, origin, relative)),
1584
2183
  exportBaseUrl: listing?.base ?? "",