dsh-game-material-master 0.10.2 → 0.11.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
@@ -34,18 +34,18 @@
34
34
  */
35
35
  import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
36
36
  import { existsSync } from "node:fs";
37
- import { randomUUID } from "node:crypto";
37
+ import { createHash, randomUUID } from "node:crypto";
38
38
  import { join } from "node:path";
39
39
  import { appendJobLog, messageOf, readJson, sweepTempFiles, writeJsonAtomic } from "./jsonio.js";
40
40
  import { dataRoot } from "./config.js";
41
41
  import { decodeFile, encodeBitmap, pngSize, probeImageSize, sniffImageExt } from "./bitmap.js";
42
42
  import { keyGreen } from "./chroma.js";
43
- import { addLayer, applyOps, clearLayer, cloneDoc, createMapDoc, filledCount, isDocEmpty, moveLayer, normalizeMapDoc, removeLayer, renameLayer, resizeDoc, revertOps } from "./mapdoc.js";
44
- import { assertGrid, assertMapSize, canonicalChunk, chunkKey, chunksInRange, dirtyChunksFor, layoutOf, normalizeGrid, parseChunkKey, viewCellRange, MAX_MAP_DIM, MAX_PLAN_CHUNKS } from "./mapgeom.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";
43
+ import { addLayer, applyOps, cellIndex, clearLayer, cloneDoc, createMapDoc, filledCount, isDocEmpty, moveLayer, normalizeMapDoc, removeLayer, renameLayer, resizeDoc, revertOps } from "./mapdoc.js";
44
+ import { assertGrid, assertMapSize, canonicalChunk, chunkKey, chunksInRange, dirtyChunksFor, layoutOf, normalizeGrid, parseChunkKey, viewCellRange, wrapCell, MAX_MAP_DIM, MAX_PLAN_CHUNKS } from "./mapgeom.js";
45
+ import { bitmapToPng, buildPlan, rasterize, renderMapView, 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, STAMP_MIN_CELLS, parseAssetScale, parseClarity, resampleToSize, A2_ROWS, MAX_ASSET_SCALE, assertStampFitsProject, } from "./maptiles.js";
47
47
  import { exportMap, safeFileName } from "./mapexport.js";
48
- import { assetBasePath } from "./links.js";
48
+ import { assetBasePath, originForLinks } from "./links.js";
49
49
  import { primeSampleTextures, renderSampleTilesets } from "./mapsamplegen.js";
50
50
  /** 四个阶段(对话面契约:`stage=assets|rules|paint|export`;`rules` 自动完成、界面不显示)。 */
51
51
  export const MAP_STAGES = ["assets", "rules", "paint", "export"];
@@ -531,15 +531,32 @@ function allCells(doc) {
531
531
  export async function applyMapOps(projectId, ops, opts = {}) {
532
532
  const project = await readProjectOrThrow(projectId);
533
533
  const doc = await theDocOrFresh(projectId);
534
- const layout = layoutOf(project.grid, doc.cols, doc.rows);
535
- const result = applyOps(doc, ops, layout, { stampSpecOf: stampSpecResolver(project) });
534
+ const currentRevision = await mapRevision(project, doc);
535
+ if (opts.ifRevision !== undefined && opts.ifRevision !== "" && opts.ifRevision !== currentRevision) {
536
+ throw new Error(`版本不一致:当前 ${currentRevision},请求 ${opts.ifRevision};请重新 mapInspect 后再改。`);
537
+ }
538
+ const target = opts.dryRun === true ? cloneDoc(doc) : doc;
539
+ const layout = layoutOf(project.grid, target.cols, target.rows);
540
+ const result = applyOps(target, ops, layout, { stampSpecOf: stampSpecResolver(project) });
536
541
  // `touched`(标记改名这类不占格的改动)也要记一步撤销 —— 只看 `changed > 0` 的话,
537
542
  // 改名会「生效了但撤不回来」。
538
- if (result.changed > 0 || result.touched === true) {
543
+ if (opts.dryRun !== true && (result.changed > 0 || result.touched === true)) {
539
544
  pushHistory(projectId, { undo: result.undo, redo: ops, stroke: opts.stroke }, doc);
540
545
  scheduleDocWrite(projectId, doc);
541
546
  }
542
- return outcomeOf(projectId, result.changed, result.skipped, layout, result.dirty, opts.have, doc, result.stamps);
547
+ const summary = {
548
+ cells: result.changed,
549
+ markers: ops.filter((op) => op?.kind === "marker").length,
550
+ stamps: result.stamps,
551
+ objects: 0
552
+ };
553
+ const revision = opts.dryRun === true ? currentRevision : await mapRevision(project, doc);
554
+ return {
555
+ ...outcomeOf(projectId, result.changed, result.skipped, layout, result.dirty, opts.have, target, result.stamps),
556
+ revision,
557
+ ...(opts.dryRun === true ? { dryRun: true } : {}),
558
+ summary
559
+ };
543
560
  }
544
561
  export async function undoMap(projectId, have) {
545
562
  const project = await readProjectOrThrow(projectId);
@@ -564,14 +581,14 @@ export async function undoMap(projectId, have) {
564
581
  // (界面里抛异常就是「点了撤销整个面板报错」)。
565
582
  state.entries.splice(state.index, 1);
566
583
  state.index = Math.max(-1, state.index - 1);
567
- return outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc);
584
+ return { ...outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc), revision: await mapRevision(project, doc) };
568
585
  }
569
586
  cells = indexCells(indices, doc);
570
587
  }
571
588
  state.index--;
572
589
  scheduleDocWrite(projectId, doc);
573
590
  // 结构快照可能把尺寸改回去了 —— 脏块必须按**改完之后**的布局算。
574
- return outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc);
591
+ return { ...outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc), revision: await mapRevision(project, doc) };
575
592
  }
576
593
  export async function redoMap(projectId, have) {
577
594
  const project = await readProjectOrThrow(projectId);
@@ -592,14 +609,14 @@ export async function redoMap(projectId, have) {
592
609
  }
593
610
  catch {
594
611
  state.entries.splice(state.index + 1, 1);
595
- return outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc);
612
+ return { ...outcomeOf(projectId, 0, [], layoutOf(project.grid, doc.cols, doc.rows), [], have, doc), revision: await mapRevision(project, doc) };
596
613
  }
597
614
  cells = indexCells(indices, doc);
598
615
  }
599
616
  state.index++;
600
617
  scheduleDocWrite(projectId, doc);
601
618
  // 结构快照可能改掉了尺寸 —— 脏块按**改完之后**的布局算(同 undoMap)。
602
- return outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc);
619
+ return { ...outcomeOf(projectId, cells.length, [], layoutOf(project.grid, doc.cols, doc.rows), cells, have, doc), revision: await mapRevision(project, doc) };
603
620
  }
604
621
  export async function saveMapDocStructure(projectId, patch) {
605
622
  const project = await readProjectOrThrow(projectId);
@@ -684,7 +701,7 @@ export async function saveMapDocStructure(projectId, patch) {
684
701
  }
685
702
  if (structural)
686
703
  await flushMapDoc(projectId);
687
- return { doc: cloneDoc(doc), dropped, warnings };
704
+ return { doc: cloneDoc(doc), dropped, warnings, revision: await mapRevision(await readProjectOrThrow(projectId), doc) };
688
705
  }
689
706
  /**
690
707
  * 导入一张素材图。**属性在这一刻定下来,之后只能删掉重来**(界面上不再提供修改入口)。
@@ -918,7 +935,7 @@ export async function composeMapAsset(input) {
918
935
  ? parseStampSpec({ cols: input.stampCols, rows: input.stampRows, frames: files.length })
919
936
  : undefined;
920
937
  if (shape === "stamp" && stampSpec === undefined) {
921
- throw new Error(`整图要给「占几格」:stampCols / stampRows(2~${STAMP_MAX_CELLS})。`);
938
+ throw new Error(`整图要给「占几格」:stampCols / stampRows(${STAMP_MIN_CELLS}~${STAMP_MAX_CELLS})。`);
922
939
  }
923
940
  /** 一张整图最多和整张地图一样大(再大地图上也画不全)。 */
924
941
  if (stampSpec !== undefined) {
@@ -1059,8 +1076,11 @@ export async function composeMapAsset(input) {
1059
1076
  await patchMapProject(project.id, (fresh) => {
1060
1077
  appendJobLog(fresh.logs, "info", `整理 AI 素材:${name}(${shapeLabel} / ${frames.length} 张 → ${sheet.width}×${sheet.height}${scale > 1 ? `,每格 ${bigCell.width}px(${scale} 倍,导入时按清晰度缩到 ${cell.width}px)` : ""},落在 ${file},等你在「新增素材」里确认)`);
1061
1078
  });
1079
+ const localPath = mapAssetPath(project.id, file);
1062
1080
  return {
1063
1081
  file,
1082
+ localPath,
1083
+ previewPath: localPath,
1064
1084
  name,
1065
1085
  shape,
1066
1086
  cell,
@@ -1282,10 +1302,37 @@ export async function saveMapTileset(projectId, tilesetId, patch) {
1282
1302
  (nextCell !== undefined && (nextCell.width !== tileset.cell.width || nextCell.height !== tileset.cell.height)) ||
1283
1303
  (nextShape !== undefined && nextShape !== tileset.shape);
1284
1304
  if (tileset.builtin === true && touchesGeometry) {
1285
- throw new Error(`「${tileset.name}」是内置素材:名字 / 播放速度 / 循环方式可以改,形态与格子尺寸不能改 —— 想换就自己新增一张。`);
1305
+ throw new Error(`「${tileset.name}」是内置素材:名字 / 播放速度 / 循环方式 / 整图的通行区域可以改,形态与格子尺寸不能改 —— 想换就自己新增一张。`);
1286
1306
  }
1287
1307
  if (typeof patch.name === "string" && patch.name.trim() !== "")
1288
1308
  tileset.name = patch.name.trim();
1309
+ /**
1310
+ * 整图的**逐格通行区域**:只改「这格能不能走 / 谁盖住谁」,不动几何、不动图块序号,
1311
+ * 所以和名字 / 速度一样随时能改(地图上已经印好的整图下一次 `mapPlan` 就用新值)。
1312
+ *
1313
+ * 长度必须与 `cols*rows` 一致:短了会被 `parseStampSpec` 按 0 补齐 ——
1314
+ * 那等于把用户没点过的格子静默改成「不可通过」,不报错、只在走位时绊住。
1315
+ */
1316
+ if (patch.stampPass !== undefined) {
1317
+ if (tileset.shape !== "stamp" || tileset.stamp === undefined) {
1318
+ throw new Error(`「${tileset.name}」不是整图素材,没有「哪些格子能走」这一项可改。`);
1319
+ }
1320
+ const expected = tileset.stamp.cols * tileset.stamp.rows;
1321
+ if (!Array.isArray(patch.stampPass) || patch.stampPass.length !== expected) {
1322
+ throw new Error(`整图的通行区域要给 ${expected} 个值(${tileset.stamp.cols}×${tileset.stamp.rows}),收到 ${Array.isArray(patch.stampPass) ? `${patch.stampPass.length} 个` : "的不是数组"}。`);
1323
+ }
1324
+ const nextStamp = parseStampSpec({
1325
+ cols: tileset.stamp.cols,
1326
+ rows: tileset.stamp.rows,
1327
+ frames: tileset.stamp.frames,
1328
+ pass: patch.stampPass
1329
+ });
1330
+ if (nextStamp !== undefined && JSON.stringify(nextStamp.pass) !== JSON.stringify(tileset.stamp.pass)) {
1331
+ tileset.stamp = nextStamp;
1332
+ const walkable = nextStamp.pass.filter((value) => value !== 0).length;
1333
+ appendJobLog(fresh.logs, "info", `改素材通行区域:${tileset.name}(${walkable}/${expected} 格能走)`);
1334
+ }
1335
+ }
1289
1336
  /**
1290
1337
  * 播放速度是**表现层属性**(不动几何、不动序号),所以单独走一条:不触发重切、
1291
1338
  * 不重映射图层数据,只是换个数 —— 想调快调慢随时改,不用删掉重来。
@@ -1501,7 +1548,7 @@ export async function runMapGenerate(projectId, opts) {
1501
1548
  const label = opts.kind === "random" ? "随机铺满" : opts.kind === "maze" ? "迷宫" : "大陆";
1502
1549
  appendJobLog(fresh.logs, "info", `一键生成(${label}):改了 ${result.changed} 格,种子 ${seed}`);
1503
1550
  });
1504
- return { changed: result.changed, seed, warnings: [...warnings, ...result.skipped] };
1551
+ return { changed: result.changed, seed, warnings: [...warnings, ...result.skipped], revision: result.revision };
1505
1552
  }
1506
1553
  function generateValues(kind, cols, rows, tiles, seed, warnings) {
1507
1554
  if (kind === "random")
@@ -1792,6 +1839,257 @@ async function fileRevision(path) {
1792
1839
  return undefined;
1793
1840
  }
1794
1841
  }
1842
+ const INSPECT_SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1843
+ function inspectInt(value, fallback, min, max) {
1844
+ const n = Math.round(Number(value));
1845
+ if (!Number.isFinite(n))
1846
+ return fallback;
1847
+ return Math.max(min, Math.min(max, n));
1848
+ }
1849
+ function inspectRegion(value, doc) {
1850
+ const raw = (value ?? {});
1851
+ const r0 = inspectInt(raw.r0, 0, -MAX_MAP_DIM, MAX_MAP_DIM);
1852
+ const c0 = inspectInt(raw.c0, 0, -MAX_MAP_DIM, MAX_MAP_DIM);
1853
+ const r1 = inspectInt(raw.r1, doc.rows, -MAX_MAP_DIM, MAX_MAP_DIM);
1854
+ const c1 = inspectInt(raw.c1, doc.cols, -MAX_MAP_DIM, MAX_MAP_DIM);
1855
+ if (r1 <= r0 || c1 <= c0)
1856
+ throw new Error("region 必须是正矩形(r1 > r0、c1 > c0)。");
1857
+ return { r0, c0, r1, c1 };
1858
+ }
1859
+ function regionCellCount(region) {
1860
+ return (region.r1 - region.r0) * (region.c1 - region.c0);
1861
+ }
1862
+ function nextInspectRange(region, limit) {
1863
+ const width = Math.max(1, Math.min(region.c1 - region.c0, limit));
1864
+ const height = Math.max(1, Math.min(region.r1 - region.r0, Math.ceil(limit / width)));
1865
+ return { r0: region.r0, c0: region.c0, r1: region.r0 + height, c1: region.c0 + width };
1866
+ }
1867
+ /**
1868
+ * 读一块地图的语义状态:逐格图块索引(文本 + 可选数组)、标记、整图、通行性、统计。
1869
+ *
1870
+ * 与 `mapPlan` 的区别:这里不返回像素坐标 / chunk / `have`,也不按视口变化。
1871
+ * 它是 Agent 回答「这一片是什么」的稳定入口。
1872
+ */
1873
+ export async function mapInspect(projectId, options = {}) {
1874
+ const project = await readProjectOrThrow(projectId);
1875
+ const doc = await theDocOrFresh(projectId);
1876
+ const layout = layoutOf(project.grid, doc.cols, doc.rows);
1877
+ const region = inspectRegion(options.region, doc);
1878
+ const maxCells = inspectInt(options.maxCells, 4096, 1, 65_536);
1879
+ const maxItems = inspectInt(options.maxItems, 200, 1, 2_000);
1880
+ const format = options.format === "text" || options.format === "json" ? options.format : "both";
1881
+ const include = new Set(options.include ?? ["layers", "markers", "stamps", "pass", "stats", "legend"]);
1882
+ const layerFilter = options.layerIds === undefined ? undefined : new Set(options.layerIds.map(String));
1883
+ const cells = regionCellCount(region);
1884
+ const truncated = cells > maxCells;
1885
+ const nextRange = truncated ? nextInspectRange(region, maxCells) : null;
1886
+ const flat = flatTiles(project.tilesets);
1887
+ const byIndex = new Map(flat.map((entry) => [entry.index, entry]));
1888
+ const used = new Map();
1889
+ const symbolOf = new Map();
1890
+ const symbolFor = (index) => {
1891
+ const existing = symbolOf.get(index);
1892
+ if (existing !== undefined)
1893
+ return existing;
1894
+ const symbol = symbolOf.size < INSPECT_SYMBOLS.length ? INSPECT_SYMBOLS[symbolOf.size] : "?";
1895
+ symbolOf.set(index, symbol);
1896
+ return symbol;
1897
+ };
1898
+ const layers = [];
1899
+ const rowsByLayer = new Map();
1900
+ const histogram = new Map();
1901
+ let filled = 0;
1902
+ const wantRows = !truncated && format !== "json";
1903
+ for (const layer of doc.layers) {
1904
+ if (layerFilter !== undefined && !layerFilter.has(layer.id))
1905
+ continue;
1906
+ const data = doc.data[layer.id] ?? [];
1907
+ const rows = [];
1908
+ let layerFilled = 0;
1909
+ for (let r = region.r0; r < region.r1; r++) {
1910
+ let row = "";
1911
+ for (let c = region.c0; c < region.c1; c++) {
1912
+ const wrapped = wrapCell(layout, r, c);
1913
+ const outside = wrapped.r < 0 || wrapped.c < 0 || wrapped.r >= doc.rows || wrapped.c >= doc.cols;
1914
+ const value = outside ? 0 : data[cellIndex(doc, wrapped.r, wrapped.c)] ?? 0;
1915
+ if (value > 0) {
1916
+ layerFilled++;
1917
+ filled++;
1918
+ used.set(value, (used.get(value) ?? 0) + 1);
1919
+ histogram.set(value, (histogram.get(value) ?? 0) + 1);
1920
+ }
1921
+ if (!wantRows)
1922
+ continue;
1923
+ if (outside)
1924
+ row += "#";
1925
+ else if (value <= 0)
1926
+ row += "·";
1927
+ else
1928
+ row += symbolFor(value);
1929
+ }
1930
+ if (wantRows)
1931
+ rows.push(row);
1932
+ }
1933
+ rowsByLayer.set(layer.id, rows);
1934
+ layers.push({
1935
+ id: layer.id,
1936
+ name: layer.name,
1937
+ filled: layerFilled,
1938
+ ...(format === "text" || truncated ? {} : { rows })
1939
+ });
1940
+ }
1941
+ const legend = [...used.keys()]
1942
+ .sort((a, b) => a - b)
1943
+ .slice(0, INSPECT_SYMBOLS.length)
1944
+ .map((index) => {
1945
+ const entry = byIndex.get(index);
1946
+ const tileset = entry === undefined ? undefined : project.tilesets.find((item) => item.id === entry.tilesetId);
1947
+ return {
1948
+ symbol: symbolFor(index),
1949
+ index,
1950
+ ...(entry === undefined
1951
+ ? {}
1952
+ : {
1953
+ tilesetId: entry.tilesetId,
1954
+ tilesetName: tileset?.name ?? entry.tilesetId,
1955
+ tileId: entry.tile.id,
1956
+ rect: entry.tile.rect,
1957
+ shape: tileset?.shape,
1958
+ mask: entry.tile.mask,
1959
+ variant: entry.tile.variant,
1960
+ frame: entry.tile.frame
1961
+ })
1962
+ };
1963
+ });
1964
+ const markersInRegion = doc.markers.filter((marker) => marker.r >= region.r0 && marker.r < region.r1 && marker.c >= region.c0 && marker.c < region.c1);
1965
+ const markers = markersInRegion
1966
+ .slice(0, maxItems)
1967
+ .map((marker) => ({
1968
+ id: marker.id,
1969
+ n: doc.markers.indexOf(marker) + 1,
1970
+ r: marker.r,
1971
+ c: marker.c,
1972
+ name: marker.name,
1973
+ kind: marker.kind ?? "custom",
1974
+ color: marker.color ?? null,
1975
+ note: marker.note ?? "",
1976
+ tags: marker.tags ?? []
1977
+ }));
1978
+ const stampsInRegion = doc.stamps.filter((stamp) => stamp.r >= region.r0 && stamp.r < region.r1 && stamp.c >= region.c0 && stamp.c < region.c1);
1979
+ const stamps = stampsInRegion
1980
+ .slice(0, maxItems)
1981
+ .map((stamp) => {
1982
+ const tileset = project.tilesets.find((entry) => entry.id === stamp.tilesetId);
1983
+ const spec = tileset?.stamp;
1984
+ return {
1985
+ id: stamp.id,
1986
+ layerId: stamp.layerId,
1987
+ tilesetId: stamp.tilesetId,
1988
+ name: tileset?.name ?? stamp.tilesetId,
1989
+ r: stamp.r,
1990
+ c: stamp.c,
1991
+ rot: stamp.rot,
1992
+ cols: spec?.cols,
1993
+ rows: spec?.rows,
1994
+ frames: spec?.frames
1995
+ };
1996
+ });
1997
+ const pass = passCellsOf(project, doc).filter((cell) => cell.r >= region.r0 && cell.r < region.r1 && cell.c >= region.c0 && cell.c < region.c1);
1998
+ const markersByKind = new Map();
1999
+ for (const marker of doc.markers) {
2000
+ if (marker.r < region.r0 || marker.r >= region.r1 || marker.c < region.c0 || marker.c >= region.c1)
2001
+ continue;
2002
+ const kind = typeof marker.kind === "string" && marker.kind !== "" ? marker.kind : "custom";
2003
+ markersByKind.set(kind, (markersByKind.get(kind) ?? 0) + 1);
2004
+ }
2005
+ const stats = {
2006
+ cells,
2007
+ filled,
2008
+ empty: Math.max(0, cells * Math.max(1, doc.layers.length) - filled),
2009
+ fillRate: cells > 0 ? filled / (cells * Math.max(1, doc.layers.length)) : 0,
2010
+ byLayer: layers.map((layer) => ({ id: layer.id, name: layer.name, filled: layer.filled })),
2011
+ tileHistogram: [...histogram.entries()].sort((a, b) => a[0] - b[0]).map(([index, count]) => ({ index, count })),
2012
+ markersByKind: [...markersByKind.entries()].map(([kind, count]) => ({ kind, count })),
2013
+ stamps: doc.stamps.length,
2014
+ objects: 0
2015
+ };
2016
+ const text = format === "json"
2017
+ ? undefined
2018
+ : [
2019
+ `地图 ${doc.cols}×${doc.rows} · 区域 (${region.r0},${region.c0})–(${region.r1 - 1},${region.c1 - 1})`,
2020
+ ...layers.map((layer) => `${String(layer.name)}\n${(rowsByLayer.get(String(layer.id)) ?? []).join("\n") || "(内容过大,已省略逐格文本)"}`),
2021
+ `图例:${legend.map((entry) => `${String(entry.symbol)}=${String(entry.tilesetName ?? entry.tilesetId ?? "未知")}/${String(entry.index)}`).join(" ")}`
2022
+ ].join("\n\n");
2023
+ return {
2024
+ module: "map",
2025
+ projectId,
2026
+ revision: await mapRevision(project, doc),
2027
+ cols: doc.cols,
2028
+ rows: doc.rows,
2029
+ grid: project.grid,
2030
+ range: region,
2031
+ truncated,
2032
+ nextRange,
2033
+ truncatedItems: [
2034
+ ...(markersInRegion.length > markers.length ? ["markers"] : []),
2035
+ ...(stampsInRegion.length > stamps.length ? ["stamps"] : [])
2036
+ ],
2037
+ legend: include.has("legend") ? legend : [],
2038
+ layers: include.has("layers") ? layers : [],
2039
+ markers: include.has("markers") ? markers : undefined,
2040
+ stamps: include.has("stamps") ? stamps : undefined,
2041
+ pass: include.has("pass") ? pass : undefined,
2042
+ stats,
2043
+ warnings: [...warningsFor(project, doc), ...(used.size > INSPECT_SYMBOLS.length ? [`不同图块超过 ${INSPECT_SYMBOLS.length} 种,文本网格用 ? 代替,精确值请用 format=json。`] : [])],
2044
+ busy: mapBusy(projectId),
2045
+ canUndo: historyState(projectId).canUndo,
2046
+ canRedo: historyState(projectId).canRedo,
2047
+ ...(text === undefined ? {} : { text })
2048
+ };
2049
+ }
2050
+ /**
2051
+ * 文档 + 素材元数据 + 素材图 mtime 的短哈希。
2052
+ *
2053
+ * 不落盘(派生数据),同一状态稳定;写入 / 撤销 / 预览 / 检查图都带它,Agent 用它
2054
+ * 防止拿旧状态覆盖新状态。素材文件 mtime 也进哈希,因为 `recomposeMapTileset`
2055
+ * 会原地换图、元数据一个字段都不变。
2056
+ */
2057
+ export async function mapRevision(project, doc, revisions) {
2058
+ const revs = revisions ?? (await tilesetRevisions(project.id));
2059
+ const payload = JSON.stringify({
2060
+ grid: project.grid,
2061
+ doc: {
2062
+ cols: doc.cols,
2063
+ rows: doc.rows,
2064
+ layers: doc.layers,
2065
+ data: doc.data,
2066
+ markers: doc.markers,
2067
+ stamps: doc.stamps
2068
+ },
2069
+ tilesets: project.tilesets.map((tileset) => ({
2070
+ id: tileset.id,
2071
+ name: tileset.name,
2072
+ file: tileset.file,
2073
+ imageWidth: tileset.imageWidth,
2074
+ imageHeight: tileset.imageHeight,
2075
+ cell: tileset.cell,
2076
+ shape: tileset.shape,
2077
+ animRows: tileset.animRows,
2078
+ variants: tileset.variants,
2079
+ loop: tileset.loop,
2080
+ clarity: tileset.clarity,
2081
+ fps: tileset.fps,
2082
+ stamp: tileset.stamp,
2083
+ builtin: tileset.builtin === true,
2084
+ tileCount: tileset.tiles.length
2085
+ })),
2086
+ files: project.tilesets.map((tileset) => [tileset.id, revisionsOr(revs, tileset.id)])
2087
+ });
2088
+ return createHash("sha1").update(payload).digest("hex").slice(0, 12);
2089
+ }
2090
+ function revisionsOr(revisions, id) {
2091
+ return revisions.get(id) ?? 0;
2092
+ }
1795
2093
  export async function mapView(p, options = {}) {
1796
2094
  void options;
1797
2095
  const doc = await theDocOrFresh(p.id);
@@ -1801,6 +2099,7 @@ export async function mapView(p, options = {}) {
1801
2099
  const layers = doc.layers.map((layer) => ({ id: layer.id, name: layer.name, filled: filledCount(doc, layer.id) }));
1802
2100
  // 素材图的版本号(mtime)先批量取好:`map` 里不能用 await,只能先算。
1803
2101
  const revisions = await tilesetRevisions(p.id);
2102
+ const preview = (await readPreviewFiles(p.id)).map((name) => `preview/${name}`);
1804
2103
  return {
1805
2104
  id: p.id,
1806
2105
  name: p.name,
@@ -1808,6 +2107,7 @@ export async function mapView(p, options = {}) {
1808
2107
  grid: p.grid,
1809
2108
  cols: doc.cols,
1810
2109
  rows: doc.rows,
2110
+ revision: await mapRevision(p, doc, revisions),
1811
2111
  tilesets: p.tilesets.map((tileset) => ({
1812
2112
  id: tileset.id,
1813
2113
  name: tileset.name,
@@ -1830,7 +2130,17 @@ export async function mapView(p, options = {}) {
1830
2130
  })),
1831
2131
  legend: flat.map((tile) => ({ index: tile.index, tilesetId: tile.tilesetId, rect: tile.tile.rect })),
1832
2132
  layers,
1833
- markers: doc.markers.map((marker, index) => ({ id: marker.id, n: index + 1, r: marker.r, c: marker.c, name: marker.name })),
2133
+ markers: doc.markers.map((marker, index) => ({
2134
+ id: marker.id,
2135
+ n: index + 1,
2136
+ r: marker.r,
2137
+ c: marker.c,
2138
+ name: marker.name,
2139
+ ...(marker.kind === undefined ? {} : { kind: marker.kind }),
2140
+ ...(marker.color === undefined ? {} : { color: marker.color }),
2141
+ ...(marker.note === undefined ? {} : { note: marker.note }),
2142
+ ...(marker.tags === undefined ? {} : { tags: marker.tags })
2143
+ })),
1834
2144
  filled: layers.reduce((sum, layer) => sum + layer.filled, 0),
1835
2145
  stages: p.stages,
1836
2146
  reviewMode: p.reviewMode,
@@ -1840,7 +2150,8 @@ export async function mapView(p, options = {}) {
1840
2150
  maxChunks: MAX_PLAN_CHUNKS,
1841
2151
  warnings: warningsFor(p, doc),
1842
2152
  logs: p.logs.slice(-40),
1843
- preview: (await readPreviewFiles(p.id)).map((name) => `preview/${name}`),
2153
+ preview,
2154
+ previewPaths: preview.map((relative) => join(mapProjectDir(p.id), relative)),
1844
2155
  exportBase: listing?.base ?? "",
1845
2156
  exportFiles: listing?.files ?? [],
1846
2157
  exportPath: listing === undefined ? "" : join(mapProjectDir(p.id), "export", listing.dirName)
@@ -2017,10 +2328,12 @@ export async function runPreviewStage(projectId) {
2017
2328
  reserved.delete(projectId);
2018
2329
  throw error;
2019
2330
  }
2331
+ const previewPath = join(mapProjectDir(projectId), "preview", "map.png");
2020
2332
  if (project.tilesets.length === 0) {
2021
2333
  reserved.delete(projectId);
2022
- return { started: false, reason: "还没有导入素材。" };
2334
+ return { started: false, reason: "还没有导入素材。", previewPath };
2023
2335
  }
2336
+ const revisionAtStart = await mapRevision(project, await theDocOrFresh(projectId));
2024
2337
  void background(projectId, "paint", async () => {
2025
2338
  const fresh = await readProjectOrThrow(projectId);
2026
2339
  const doc = await theDocOrFresh(projectId);
@@ -2042,7 +2355,93 @@ export async function runPreviewStage(projectId) {
2042
2355
  appendJobLog(current.logs, "warn", `预览告警:${warning}`);
2043
2356
  });
2044
2357
  });
2045
- return { started: true };
2358
+ return { started: true, previewPath, revisionAtStart };
2359
+ }
2360
+ /** 检查图目录里只留最近 20 张;失败不影响本次渲染。 */
2361
+ async function pruneAgentRenders(projectId, keep = 20) {
2362
+ const dir = join(mapProjectDir(projectId), "preview", "agent");
2363
+ let names;
2364
+ try {
2365
+ names = (await readdir(dir)).filter((name) => name.endsWith(".png"));
2366
+ }
2367
+ catch {
2368
+ return;
2369
+ }
2370
+ if (names.length <= keep)
2371
+ return;
2372
+ const entries = await Promise.all(names.map(async (name) => {
2373
+ try {
2374
+ return { name, mtime: (await stat(join(dir, name))).mtimeMs };
2375
+ }
2376
+ catch {
2377
+ return { name, mtime: 0 };
2378
+ }
2379
+ }));
2380
+ entries.sort((a, b) => b.mtime - a.mtime);
2381
+ for (const entry of entries.slice(keep))
2382
+ await rm(join(dir, entry.name), { force: true }).catch(() => undefined);
2383
+ }
2384
+ /**
2385
+ * 同步渲染一块地图区域,供 Agent 用 `read_image` 看。
2386
+ *
2387
+ * 与 `runMapPreview` 的分工:这个不写阶段、不触发验收、不排队;它就是一张检查图。
2388
+ * 渲染走 `renderMapView`(同一份 `buildPlan`),所以区域图与导出图不会各算一套。
2389
+ */
2390
+ export async function runMapRender(projectId, options = {}) {
2391
+ const startedAt = Date.now();
2392
+ const project = await readProjectOrThrow(projectId);
2393
+ const doc = await theDocOrFresh(projectId);
2394
+ const revisionAtStart = await mapRevision(project, doc);
2395
+ const region = inspectRegion(options.region, doc);
2396
+ const layerIndexes = options.layerIds === undefined
2397
+ ? undefined
2398
+ : options.layerIds
2399
+ .map((id) => doc.layers.findIndex((layer) => layer.id === id))
2400
+ .filter((index) => index >= 0);
2401
+ const context = renderContextFor(project, doc);
2402
+ const lookup = await decodeTilesets(project);
2403
+ const passCells = options.overlay?.pass === true ? passCellsOf(project, doc) : undefined;
2404
+ const rendered = renderMapView(context, doc, lookup, {
2405
+ range: { r0: region.r0, c0: region.c0, r1: region.r1, c1: region.c1 },
2406
+ scale: options.scale,
2407
+ layers: layerIndexes,
2408
+ frame: options.frame,
2409
+ background: options.background,
2410
+ overlay: options.overlay,
2411
+ passCells,
2412
+ maxPixels: options.maxPixels
2413
+ });
2414
+ const dir = join(mapProjectDir(projectId), "preview", "agent");
2415
+ await mkdir(dir, { recursive: true });
2416
+ const safe = safeFileName(options.name ?? "inspect", "inspect");
2417
+ const optionsHash = createHash("sha1")
2418
+ .update(JSON.stringify({ region, scale: rendered.scale, layerIndexes, frame: options.frame ?? 0, background: options.background ?? "transparent", overlay: options.overlay ?? {} }))
2419
+ .digest("hex")
2420
+ .slice(0, 8);
2421
+ const file = `preview/agent/${safe}-${revisionAtStart}-${optionsHash}.png`;
2422
+ const localPath = join(mapProjectDir(projectId), file);
2423
+ await writeFile(localPath, bitmapToPng(rendered.bitmap));
2424
+ await pruneAgentRenders(projectId);
2425
+ const revision = await mapRevision(project, doc);
2426
+ return {
2427
+ module: "map",
2428
+ projectId,
2429
+ revision,
2430
+ revisionAtStart,
2431
+ stale: revision !== revisionAtStart,
2432
+ file,
2433
+ localPath,
2434
+ url: `${originForLinks()}${mapAssetBase(projectId)}${file}`,
2435
+ width: rendered.bitmap.width,
2436
+ height: rendered.bitmap.height,
2437
+ crop: rendered.crop,
2438
+ scale: rendered.scale,
2439
+ range: rendered.range,
2440
+ drawn: rendered.drawn,
2441
+ markersDrawn: rendered.markersDrawn,
2442
+ warnings: rendered.warnings,
2443
+ elapsedMs: Date.now() - startedAt
2444
+ };
2046
2445
  }
2047
2446
  /**
2048
2447
  * 导出目录名:跟着**地图名**走(改名地图 = 换一个自包含目录,旧目录原样留着)。