dsh-game-material-master 0.6.0 → 0.7.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.
@@ -0,0 +1,151 @@
1
+ /**
2
+ * 生图后端的分发层。
3
+ *
4
+ * 插件支持两类生图后端(`config.imageProvider`):
5
+ *
6
+ * · `ark`(默认)—— 火山方舟 Seedream,走 `ark.generateImage`;
7
+ * · `custom` —— 用户自己的服务,协议见 `customimage.ts`(OpenAI / ComfyUI / SD WebUI)。
8
+ *
9
+ * 所有生图调用点(八方向图 / 图片生成 / 骨骼动画 / 地图地块)都只经过这里。
10
+ * 这样「换生图后端」只改一处,各模块不必各判一次 provider —— 历史教训是
11
+ * 这种「每处判一次」的分叉迟早会漏一处,而漏掉的那一处**不报错**,
12
+ * 只是偷偷还在用另一家模型。
13
+ */
14
+ import { generateImage } from "./ark.js";
15
+ import { CUSTOM_PROTOCOL_DEFAULTS, loadConfig } from "./config.js";
16
+ import { CustomImageError, generateCustomImage } from "./customimage.js";
17
+ export function isCustomProvider(config) {
18
+ return config.imageProvider === "custom";
19
+ }
20
+ /** 当前生图模型(Ark 是 `arkModel`,自定义是 `customModel`)。 */
21
+ export function imageModelOf(config) {
22
+ return isCustomProvider(config) ? config.customModel : config.arkModel;
23
+ }
24
+ /** 当前输出尺寸。 */
25
+ export function imageSizeOf(config) {
26
+ return isCustomProvider(config) ? config.customSize : config.arkSize;
27
+ }
28
+ /** 当前水印开关。水印是火山方舟特有的参数,自定义后端一律不带。 */
29
+ export function imageWatermarkOf(config) {
30
+ return isCustomProvider(config) ? false : config.arkWatermark;
31
+ }
32
+ /** 当前请求超时。 */
33
+ export function imageTimeoutOf(config) {
34
+ return isCustomProvider(config) ? config.customTimeoutMs : config.arkTimeoutMs;
35
+ }
36
+ /** 自定义后端自己的必填项检查(不看 `imageProvider`,供「测试连接」按钮用)。 */
37
+ export function customImageBlocker(config) {
38
+ if (config.customBaseUrl.trim() === "") {
39
+ return "尚未配置自定义生图服务的地址(设置 → 游戏素材大师 → 生图后端 → 自定义生图模型)";
40
+ }
41
+ if (config.customProtocol === "comfyui" && config.customWorkflow.trim() === "") {
42
+ return "选了 ComfyUI 协议,但还没填工作流 JSON(在 ComfyUI 里「导出(API)」拿到那份 JSON,整段粘贴)";
43
+ }
44
+ if (config.customProtocol === "openai" && config.customModel.trim() === "") {
45
+ return "选了 OpenAI 协议,但还没填模型名";
46
+ }
47
+ return undefined;
48
+ }
49
+ /**
50
+ * 当前后端「能不能开跑」。返回 undefined = 可以。
51
+ *
52
+ * 错误文案里必须写清**去哪里配**:两种后端的用户不是同一批人,
53
+ * 只说「未配置」会让人在设置页里来回找。
54
+ */
55
+ export function imageProviderBlocker(config) {
56
+ if (!isCustomProvider(config)) {
57
+ if (config.arkApiKey.trim() === "") {
58
+ return "尚未配置火山方舟 API Key(设置 → 游戏素材大师 → 生图后端 → 火山方舟)";
59
+ }
60
+ if (config.arkModel.trim() === "")
61
+ return "尚未配置火山方舟的生图模型 ID";
62
+ return undefined;
63
+ }
64
+ return customImageBlocker(config);
65
+ }
66
+ export function assertImageProviderReady(config) {
67
+ const blocker = imageProviderBlocker(config);
68
+ if (blocker !== undefined)
69
+ throw new Error(blocker);
70
+ }
71
+ /** 一句话摘要(界面角标与工具面共用)。 */
72
+ export function imageProviderSummary(config) {
73
+ if (!isCustomProvider(config))
74
+ return `火山方舟 · ${config.arkModel}`;
75
+ const label = CUSTOM_PROTOCOL_DEFAULTS[config.customProtocol]?.label ?? config.customProtocol;
76
+ const model = config.customModel.trim() === "" ? "" : ` · ${config.customModel}`;
77
+ return `自定义 · ${label} · ${config.customBaseUrl}${model}`;
78
+ }
79
+ /** 调一次生图,自动按当前后端分发。 */
80
+ export async function generateImageWithProvider(request, signal) {
81
+ const config = await loadConfig();
82
+ assertImageProviderReady(config);
83
+ if (isCustomProvider(config)) {
84
+ return generateCustomImage({
85
+ protocol: config.customProtocol,
86
+ baseUrl: config.customBaseUrl,
87
+ apiKey: config.customApiKey,
88
+ model: request.model?.trim() || config.customModel,
89
+ prompt: request.prompt,
90
+ images: request.images,
91
+ size: request.size,
92
+ timeoutMs: request.timeoutMs ?? config.customTimeoutMs,
93
+ negativePrompt: config.customNegativePrompt,
94
+ steps: config.customSteps,
95
+ cfgScale: config.customCfgScale,
96
+ sampler: config.customSampler,
97
+ denoising: config.customDenoising,
98
+ seed: config.customSeed,
99
+ workflow: config.customWorkflow
100
+ }, signal);
101
+ }
102
+ return generateImage({
103
+ baseUrl: config.arkBaseUrl,
104
+ apiKey: config.arkApiKey,
105
+ model: request.model?.trim() || config.arkModel,
106
+ prompt: request.prompt,
107
+ images: request.images,
108
+ size: request.size,
109
+ watermark: request.watermark,
110
+ timeoutMs: request.timeoutMs ?? config.arkTimeoutMs
111
+ }, signal);
112
+ }
113
+ /**
114
+ * 连通性自检:对**自定义后端**真实生成一张小图。
115
+ *
116
+ * 与 `testArk` 对称:各自测各自那一组配置,所以「当前用哪家」不影响按钮能不能点
117
+ * —— 用户经常是先把两边的地址都填好、各测一次,再决定切哪个。
118
+ * 只有真跑一次才能同时验证「地址对不对」和「服务端真的能出图」,看配置看不出来。
119
+ */
120
+ export async function testCustomImage() {
121
+ const config = await loadConfig();
122
+ const blocker = customImageBlocker(config);
123
+ if (blocker !== undefined)
124
+ throw new Error(blocker);
125
+ const result = await generateCustomImage({
126
+ protocol: config.customProtocol,
127
+ baseUrl: config.customBaseUrl,
128
+ apiKey: config.customApiKey,
129
+ model: config.customModel,
130
+ prompt: "一张纯绿色背景的空白测试图,画面中只有一个居中的小圆点",
131
+ images: [],
132
+ size: config.customSize,
133
+ timeoutMs: config.customTimeoutMs,
134
+ negativePrompt: config.customNegativePrompt,
135
+ steps: config.customSteps,
136
+ cfgScale: config.customCfgScale,
137
+ sampler: config.customSampler,
138
+ denoising: config.customDenoising,
139
+ // 测试图固定种子,便于对比两次测试的结果是否一致(排查缓存 / 没真跑的问题)。
140
+ seed: 20261016,
141
+ workflow: config.customWorkflow
142
+ });
143
+ return {
144
+ ok: true,
145
+ provider: `自定义 · ${CUSTOM_PROTOCOL_DEFAULTS[config.customProtocol]?.label ?? config.customProtocol}`,
146
+ model: config.customModel,
147
+ bytes: result.bytes.length,
148
+ ext: result.ext
149
+ };
150
+ }
151
+ export { CustomImageError };
package/lib/index.js CHANGED
@@ -15,12 +15,13 @@ import { fileURLToPath } from "node:url";
15
15
  import { spawn } from "node:child_process";
16
16
  import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
17
17
  import { appendJobLog } from "./jsonio.js";
18
- import { ARK_MODEL_PRESETS, DEFAULT_CONFIG, ROW_ORDER_VERSION, MINIMAX_HOST_PRESETS, MINIMAX_MODEL_PRESETS, loadConfig, maskConfig, migrateLegacyDataRoot, projectsRoot, saveConfig } from "./config.js";
18
+ import { ARK_MODEL_PRESETS, CUSTOM_PROTOCOLS, CUSTOM_PROTOCOL_DEFAULTS, DEFAULT_CONFIG, ROW_ORDER_VERSION, MINIMAX_HOST_PRESETS, MINIMAX_MODEL_PRESETS, loadConfig, maskConfig, migrateLegacyDataRoot, projectsRoot, saveConfig } from "./config.js";
19
19
  import { DEFAULT_ROW_ORDER, DIRECTION_KEYS, TURN_DIRECTION_DEFAULT, TURN_FRAME_COUNT_MAX, TURN_FRAME_COUNT_MIN, defaultPrompts, directionOf, localizePrompts, normalizePromptLang } from "./directions.js";
20
20
  import { checkFfmpeg } from "./media.js";
21
21
  import { testArk } from "./ark.js";
22
+ import { customImageBlocker, imageModelOf, imageProviderBlocker, imageProviderSummary, isCustomProvider, testCustomImage } from "./imageprovider.js";
22
23
  import { COMP_SHARE_BASE_URL, COMP_SHARE_MODEL_ID, capabilityOf, isCompshareModel, normalizeDuration, normalizeResolution, pathPrefixOf, testMiniMax } from "./minimax.js";
23
- import { applyTurnPicks, clearVideos, disposePipeline, ensurePoller, listJobs, pollVideosOnce, resetFramePicks, resetTurnPicks, setFramePick, setFramePicks, setImageMode, setTurnPick, setTurnPicks, startAllImages, startCompose, startFramePick, startExtract, startImage, startRekey, startTurnFrames, startTurnVideo, startVideos } from "./pipeline.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";
24
25
  import { assetPath, createProject, deleteProject, listProjects, log, patchProject, projectDir, projectExists, readProject, } from "./store.js";
25
26
  import * as imagegen from "./imagegen.js";
26
27
  import * as seqgen from "./seqgen.js";
@@ -244,6 +245,24 @@ export class GameStudioGateway extends TypertRemoteService {
244
245
  rowOrder: [...config.rowOrder],
245
246
  defaults: { ...DEFAULT_CONFIG },
246
247
  arkModels: ARK_MODEL_PRESETS,
248
+ /**
249
+ * 生图后端的呈现材料。
250
+ *
251
+ * `imageProviderBlocker` 由宿主算好回传,界面与**对话工具面**共用同一份判断
252
+ * (tools.ts 的 intake 也读它):两边各写一套「配好了没」的规则,
253
+ * 迟早会出现「界面说没配好、模型说配好了」这种互相矛盾的提示。
254
+ */
255
+ customProtocols: CUSTOM_PROTOCOLS.map((key) => ({
256
+ id: key,
257
+ label: CUSTOM_PROTOCOL_DEFAULTS[key].label,
258
+ baseUrl: CUSTOM_PROTOCOL_DEFAULTS[key].baseUrl,
259
+ hint: CUSTOM_PROTOCOL_DEFAULTS[key].hint
260
+ })),
261
+ imageProviderSummary: imageProviderSummary(config),
262
+ /** 当前生效的生图模型(模块里那个只读展示位用它,比 summary 短)。 */
263
+ imageModel: imageModelOf(config),
264
+ imageProviderBlocker: imageProviderBlocker(config) ?? null,
265
+ customImageBlocker: customImageBlocker(config) ?? null,
247
266
  minimaxModels: MINIMAX_MODEL_PRESETS,
248
267
  minimaxHosts: MINIMAX_HOST_PRESETS,
249
268
  // 「优云智算版 H3」由用户在模型下拉里显式选择,选中后网关地址/路径/档位全部跟着它走。
@@ -269,13 +288,26 @@ export class GameStudioGateway extends TypertRemoteService {
269
288
  }
270
289
  /**
271
290
  * 保存配置。
272
- * 约定:`arkApiKey` / `minimaxApiKey` **只有用户确实改了才带**——不带就是保持原值,
273
- * 带空串才是清除。这样界面就不必把明文 key 回填到输入框里。
291
+ * 约定:`arkApiKey` / `minimaxApiKey` / `customApiKey` **只有用户确实改了才带**——
292
+ * 不带就是保持原值,带空串才是清除。这样界面就不必把明文 key 回填到输入框里。
274
293
  */
275
294
  async saveConfig(payload) {
276
295
  const input = asRecord(payload);
277
296
  const patch = {};
278
297
  const directKeys = [
298
+ "imageProvider",
299
+ "customProtocol",
300
+ "customBaseUrl",
301
+ "customModel",
302
+ "customSize",
303
+ "customNegativePrompt",
304
+ "customSteps",
305
+ "customCfgScale",
306
+ "customSampler",
307
+ "customDenoising",
308
+ "customSeed",
309
+ "customWorkflow",
310
+ "customTimeoutMs",
279
311
  "arkBaseUrl",
280
312
  "arkModel",
281
313
  "arkSize",
@@ -316,10 +348,14 @@ export class GameStudioGateway extends TypertRemoteService {
316
348
  patch.arkApiKey = input.arkApiKey.trim();
317
349
  if (typeof input.minimaxApiKey === "string")
318
350
  patch.minimaxApiKey = input.minimaxApiKey.trim();
351
+ if (typeof input.customApiKey === "string")
352
+ patch.customApiKey = input.customApiKey.trim();
319
353
  if (input.clearArkApiKey === true)
320
354
  patch.arkApiKey = "";
321
355
  if (input.clearMinimaxApiKey === true)
322
356
  patch.minimaxApiKey = "";
357
+ if (input.clearCustomApiKey === true)
358
+ patch.customApiKey = "";
323
359
  const saved = await saveConfig(patch);
324
360
  this.ffmpegCache = undefined;
325
361
  return this.decorateConfig(saved);
@@ -335,6 +371,10 @@ export class GameStudioGateway extends TypertRemoteService {
335
371
  timeoutMs: config.arkTimeoutMs
336
372
  });
337
373
  }
374
+ /** 测自定义生图后端。与 testArk 对称,各自测各自那一组配置。 */
375
+ async testCustomImage() {
376
+ return testCustomImage();
377
+ }
338
378
  async testMinimax() {
339
379
  const config = await loadConfig();
340
380
  return testMiniMax({
@@ -427,6 +467,27 @@ export class GameStudioGateway extends TypertRemoteService {
427
467
  });
428
468
  return { ok: true, file: relative, name: originalName };
429
469
  }
470
+ /**
471
+ * 选用一段**本地视频**(用户自己选的,不走远程生成)。
472
+ *
473
+ * `key` 是槽位:`turn`(转圈视频)或八个方向之一的 key。远端生成与本地导入
474
+ * 产出的节点完全同形,所以阶段 3、4 不必区分;转圈模式在导入后会自动抽候选帧。
475
+ */
476
+ async uploadVideo(payload) {
477
+ const input = asRecord(payload);
478
+ return importLocalVideo(asString(input.projectId), asString(input.key), asString(input.name, "local-video"), asString(input.data));
479
+ }
480
+ /** 把项目里所有中间图片打成一个 zip(落在 `out/` 下,返回相对路径给界面下载)。 */
481
+ async exportImages(payload) {
482
+ const projectId = asString(asRecord(payload).projectId);
483
+ const pack = await exportImages(projectId);
484
+ const project = await readProject(projectId);
485
+ return {
486
+ ...pack,
487
+ assetBase: `${ROUTE_PREFIX}/assets/${projectId}/`,
488
+ name: project?.name ?? projectId
489
+ };
490
+ }
430
491
  async savePrompts(payload) {
431
492
  const input = asRecord(payload);
432
493
  const projectId = asString(input.projectId);
@@ -1372,9 +1433,11 @@ export class GameStudioGateway extends TypertRemoteService {
1372
1433
  job.suffix = input.suffix;
1373
1434
  if (input.settings !== undefined) {
1374
1435
  const raw = asRecord(input.settings);
1375
- // 生图模型是全局设置(设置 → 游戏素材大师 → 生图模型),任务里不保留可覆盖的副本。
1376
- job.settings.model = (await loadConfig()).arkModel;
1377
- job.settings.size = asString(raw.size, job.settings.size);
1436
+ const current = await loadConfig();
1437
+ // 生图模型是全局设置(设置 → 游戏素材大师 → 生图后端),任务里不保留可覆盖的副本。
1438
+ job.settings.model = imageModelOf(current);
1439
+ // 自定义后端的尺寸也是全局参数;火山方舟下才保留任务级覆盖。
1440
+ job.settings.size = isCustomProvider(current) ? current.customSize : asString(raw.size, job.settings.size);
1378
1441
  job.settings.count = clampInt(raw.count, job.settings.count, 1, 8);
1379
1442
  job.settings.watermark = raw.watermark === true;
1380
1443
  }
package/lib/mapdoc.js CHANGED
@@ -32,9 +32,15 @@ export function emptyData(cols, rows) {
32
32
  export function defaultLayer(id, name) {
33
33
  return { id, name: typeof name === "string" && name !== "" ? name : "图层" };
34
34
  }
35
- /** 默认两层(AsLib 同款:一层地面、一层装饰)。名字**中文硬编码** —— 宿主侧没有 i18n 通道。 */
35
+ /**
36
+ * 默认三层:地理层 / 装饰层 / 建筑层。
37
+ *
38
+ * 名字**中文硬编码** —— 宿主侧没有 i18n 通道(界面显示宿主给的名字,用户随时能改)。
39
+ * 「标记层」不在这个数组里:它装的是带名字的标记(见 `MapMarker`),不是图块序号,
40
+ * 在图层卡里是一行固定入口。
41
+ */
36
42
  function defaultLayers() {
37
- return [defaultLayer("l0", "图层 1"), defaultLayer("l1", "图层 2")];
43
+ return [defaultLayer("l0", "地理层"), defaultLayer("l1", "装饰层"), defaultLayer("l2", "建筑层")];
38
44
  }
39
45
  export function createMapDoc(id, name, cols, rows) {
40
46
  assertMapSize(cols, rows);
@@ -43,7 +49,7 @@ export function createMapDoc(id, name, cols, rows) {
43
49
  const data = {};
44
50
  for (const layer of layers)
45
51
  data[layer.id] = emptyData(cols, rows);
46
- return { id, name, cols, rows, layers, data, createdAt: now, updatedAt: now };
52
+ return { id, name, cols, rows, layers, data, markers: [], createdAt: now, updatedAt: now };
47
53
  }
48
54
  /** 读盘 / 外部输入 → 合法文档:补缺字段、把图层数据裁齐到 `cols × rows`。 */
49
55
  export function normalizeMapDoc(raw, fallbackId) {
@@ -72,6 +78,21 @@ export function normalizeMapDoc(raw, fallbackId) {
72
78
  }
73
79
  if (layers.length === 0)
74
80
  layers.push(...defaultLayers());
81
+ /**
82
+ * 老文档升级:**只动从来没被改过名的出厂两层**。
83
+ *
84
+ * 判据是「正好两层,且名字就是出厂名 `图层 1` / `图层 2`」—— 用户自己改过名的文档
85
+ * 一个字都不动(猜错了语义比不改更坏)。幂等:升级完名字已经不是出厂名,
86
+ * 下次读不会再来一遍。
87
+ */
88
+ if (layers.length === 2 && layers[0].name === "图层 1" && layers[1].name === "图层 2") {
89
+ layers[0].name = "地理层";
90
+ layers[1].name = "装饰层";
91
+ let extra = 0;
92
+ while (used.has(`l${extra}`))
93
+ extra++;
94
+ layers.push({ id: `l${extra}`, name: "建筑层" });
95
+ }
75
96
  const layersData = (input.data ?? {});
76
97
  const data = {};
77
98
  for (const layer of layers) {
@@ -93,15 +114,56 @@ export function normalizeMapDoc(raw, fallbackId) {
93
114
  rows,
94
115
  layers,
95
116
  data,
117
+ markers: normalizeMarkers(input.markers, cols, rows),
96
118
  createdAt: typeof input.createdAt === "string" ? input.createdAt : now,
97
119
  updatedAt: typeof input.updatedAt === "string" ? input.updatedAt : now
98
120
  };
99
121
  }
122
+ /**
123
+ * 读盘 / 外部输入 → 合法标记表。
124
+ *
125
+ * - 缺字段(老文档)→ 空表,不抛;
126
+ * - **越界的丢掉**(地图被改小过):留着的话标记会画在地图外面,而导出 `map.json`
127
+ * 里的坐标又对不上号;
128
+ * - id 缺失或重复一律重新分配,否则两个标记共用一个 id,op 会改错那一个。
129
+ */
130
+ function normalizeMarkers(raw, cols, rows) {
131
+ if (!Array.isArray(raw))
132
+ return [];
133
+ const used = new Set();
134
+ const out = [];
135
+ let seq = 0;
136
+ const nextId = () => {
137
+ seq++;
138
+ while (used.has(`m${seq}`))
139
+ seq++;
140
+ return `m${seq}`;
141
+ };
142
+ for (const item of raw) {
143
+ const marker = item;
144
+ const r = Math.round(Number(marker?.r));
145
+ const c = Math.round(Number(marker?.c));
146
+ if (!Number.isFinite(r) || !Number.isFinite(c))
147
+ continue;
148
+ if (r < 0 || c < 0 || r >= rows || c >= cols)
149
+ continue;
150
+ const given = typeof marker?.id === "string" && marker.id !== "" ? marker.id : "";
151
+ const id = given !== "" && !used.has(given) ? given : nextId();
152
+ used.add(id);
153
+ out.push({ id, r, c, name: typeof marker?.name === "string" ? marker.name : "" });
154
+ }
155
+ return out;
156
+ }
100
157
  export function cloneDoc(doc) {
101
158
  const data = {};
102
159
  for (const [key, value] of Object.entries(doc.data))
103
160
  data[key] = [...value];
104
- return { ...doc, layers: doc.layers.map((layer) => ({ ...layer })), data };
161
+ return {
162
+ ...doc,
163
+ layers: doc.layers.map((layer) => ({ ...layer })),
164
+ data,
165
+ markers: doc.markers.map((marker) => ({ ...marker }))
166
+ };
105
167
  }
106
168
  // ── 结构操作(图层 / 尺寸)────────────────────────────────────────────────
107
169
  export function nextLayerId(doc) {
@@ -172,12 +234,13 @@ export function clearLayer(doc, layerId) {
172
234
  }
173
235
  /**
174
236
  * 改地图尺寸(左上角对齐)。缩小时被丢掉的格子**计数返回**,且可撤销
175
- * (调用方在改之前存一份快照)。
237
+ * (调用方在改之前存一份快照)。标记同样按新边界裁剪 —— 留在界外的标记既画不出来,
238
+ * 导出里的坐标也是错的,所以**必须一起丢**,并把条数报给调用方。
176
239
  */
177
240
  export function resizeDoc(doc, cols, rows) {
178
241
  assertMapSize(cols, rows);
179
242
  if (cols === doc.cols && rows === doc.rows)
180
- return { dropped: 0 };
243
+ return { dropped: 0, droppedMarkers: 0 };
181
244
  let dropped = 0;
182
245
  for (const layer of doc.layers) {
183
246
  const source = doc.data[layer.id] ?? emptyData(doc.cols, doc.rows);
@@ -200,8 +263,11 @@ export function resizeDoc(doc, cols, rows) {
200
263
  }
201
264
  doc.cols = cols;
202
265
  doc.rows = rows;
266
+ const kept = doc.markers.filter((marker) => marker.r < rows && marker.c < cols);
267
+ const droppedMarkers = doc.markers.length - kept.length;
268
+ doc.markers = kept;
203
269
  doc.updatedAt = new Date().toISOString();
204
- return { dropped };
270
+ return { dropped, droppedMarkers };
205
271
  }
206
272
  /** 画一条线(Bresenham):拖动时两点之间的格子不能漏(漏了就是「虚线」)。 */
207
273
  export function lineCells(r0, c0, r1, c1) {
@@ -253,6 +319,8 @@ export function applyOps(doc, ops, layout) {
253
319
  const dirty = new Map();
254
320
  const undo = [];
255
321
  const skipped = [];
322
+ /** 有不占格的改动(标记改名)。它不进 `changed`,但文档真的变了。 */
323
+ let touched = false;
256
324
  const canonical = (r, c) => {
257
325
  if (!Number.isInteger(r) || !Number.isInteger(c))
258
326
  return undefined;
@@ -288,12 +356,28 @@ export function applyOps(doc, ops, layout) {
288
356
  }
289
357
  return before;
290
358
  };
359
+ /** 标记 op 用的两个小工具:标脏一格 / 从第 N 个标记起全部标脏。 */
360
+ const markCell = (r, c) => {
361
+ const index = r * doc.cols + c;
362
+ changed.add(index);
363
+ dirty.set(index, { r, c });
364
+ };
365
+ const markNumberingFrom = (from) => {
366
+ for (let i = Math.max(0, from); i < doc.markers.length; i++) {
367
+ const marker = doc.markers[i];
368
+ markCell(marker.r, marker.c);
369
+ }
370
+ };
291
371
  for (const raw of ops) {
292
372
  const op = raw;
293
373
  if (op === null || typeof op !== "object" || typeof op.kind !== "string") {
294
374
  skipped.push("认不出的 op");
295
375
  continue;
296
376
  }
377
+ if (op.kind === "marker") {
378
+ touched = applyMarkerOp(doc, op, { canonical, markCell, markNumberingFrom }, skipped, undo) || touched;
379
+ continue;
380
+ }
297
381
  if (typeof op.layerId !== "string" || doc.data[op.layerId] === undefined) {
298
382
  skipped.push(`图层不存在:${String(op.layerId)}`);
299
383
  continue;
@@ -382,15 +466,104 @@ export function applyOps(doc, ops, layout) {
382
466
  skipped.push(`不支持的 op:${String(op.kind)}`);
383
467
  }
384
468
  }
385
- if (changed.size > 0)
469
+ if (changed.size > 0 || touched)
386
470
  doc.updatedAt = new Date().toISOString();
387
471
  return {
388
472
  changed: changed.size,
473
+ touched,
389
474
  skipped,
390
475
  dirty: [...dirty.values()].sort((a, b) => a.r - b.r || a.c - b.c),
391
476
  undo: undo.reverse()
392
477
  };
393
478
  }
479
+ /**
480
+ * 应用一条标记 op。返回「文档是否真的变了」。
481
+ *
482
+ * 编号 = 下标 + 1,所以**增删都要把后面那些标记的格子一起标脏**:删掉第 2 个之后,
483
+ * 原来的第 3 个圆圈里就写着 2 —— 不标脏的话界面上那一格永远不会重画,屏幕上留着旧号码。
484
+ * (宿主每次查询都会回整份标记表,所以只脏一个块也能拉到新号码;但脏哪一块是**宿主**
485
+ * 算的,不能指望「用户恰好看得见被删的那个」。)
486
+ */
487
+ function applyMarkerOp(doc, op, env, skipped, undo) {
488
+ const indexOf = (id) => (typeof id === "string" ? doc.markers.findIndex((marker) => marker.id === id) : -1);
489
+ const occupiedAt = (r, c) => doc.markers.findIndex((marker) => marker.r === r && marker.c === c);
490
+ const occupiedText = (index) => `这一格已经有标记了(第 ${index + 1} 个)`;
491
+ if (op.op === "add") {
492
+ const target = env.canonical(op.r, op.c);
493
+ if (target === undefined) {
494
+ skipped.push(`越界格 (${op.r},${op.c})`);
495
+ return false;
496
+ }
497
+ const occupied = occupiedAt(target.r, target.c);
498
+ if (occupied >= 0) {
499
+ skipped.push(occupiedText(occupied));
500
+ return false;
501
+ }
502
+ const given = typeof op.id === "string" && op.id !== "" ? op.id : "";
503
+ if (given !== "" && indexOf(given) >= 0) {
504
+ skipped.push(`标记 id 重复:${given}`);
505
+ return false;
506
+ }
507
+ const id = given !== "" ? given : nextMarkerId(doc);
508
+ const at = Number.isInteger(op.at) ? Math.min(doc.markers.length, Math.max(0, Number(op.at))) : doc.markers.length;
509
+ doc.markers.splice(at, 0, { id, r: target.r, c: target.c, name: typeof op.name === "string" ? op.name : "" });
510
+ env.markCell(target.r, target.c);
511
+ env.markNumberingFrom(at);
512
+ undo.push({ kind: "marker", op: "remove", id });
513
+ return true;
514
+ }
515
+ const index = indexOf(op.id);
516
+ if (index < 0) {
517
+ skipped.push(`标记不存在:${String(op.id)}`);
518
+ return false;
519
+ }
520
+ const marker = doc.markers[index];
521
+ if (op.op === "remove") {
522
+ doc.markers.splice(index, 1);
523
+ env.markCell(marker.r, marker.c);
524
+ env.markNumberingFrom(index);
525
+ // 逆操作**插回原位置**:插到末尾的话,撤销之后编号顺序就变了。
526
+ undo.push({ kind: "marker", op: "add", id: marker.id, r: marker.r, c: marker.c, name: marker.name, at: index });
527
+ return true;
528
+ }
529
+ if (op.op === "move") {
530
+ const target = env.canonical(op.r, op.c);
531
+ if (target === undefined) {
532
+ skipped.push(`越界格 (${op.r},${op.c})`);
533
+ return false;
534
+ }
535
+ if (target.r === marker.r && target.c === marker.c)
536
+ return false;
537
+ const occupied = occupiedAt(target.r, target.c);
538
+ if (occupied >= 0) {
539
+ skipped.push(occupiedText(occupied));
540
+ return false;
541
+ }
542
+ const from = { r: marker.r, c: marker.c };
543
+ marker.r = target.r;
544
+ marker.c = target.c;
545
+ env.markCell(from.r, from.c);
546
+ env.markCell(target.r, target.c);
547
+ undo.push({ kind: "marker", op: "move", id: marker.id, r: from.r, c: from.c });
548
+ return true;
549
+ }
550
+ const name = typeof op.name === "string" ? op.name : "";
551
+ if (marker.name === name)
552
+ return false;
553
+ const before = marker.name;
554
+ marker.name = name;
555
+ undo.push({ kind: "marker", op: "rename", id: marker.id, name: before });
556
+ return true;
557
+ }
558
+ /** 下一个不冲突的标记 id(`m1`、`m2`…)。删掉的不回收,免得和撤销栈里的旧 id 撞上。 */
559
+ export function nextMarkerId(doc) {
560
+ let seq = doc.markers.length;
561
+ for (;;) {
562
+ seq++;
563
+ if (!doc.markers.some((marker) => marker.id === `m${seq}`))
564
+ return `m${seq}`;
565
+ }
566
+ }
394
567
  /**
395
568
  * 撤销:把逆操作原样应用(它本身也是 op)。
396
569
  *
package/lib/mapexport.js CHANGED
@@ -39,7 +39,13 @@ import { bitmapToPng, planBounds, rasterize } from "./maprender.js";
39
39
  // 引用对「只在函数体里用到的绑定」是安全的(下面只在调用时读 `mapAssetPath`)。
40
40
  import { mapAssetPath } from "./mapgen.js";
41
41
  import { zipEntries } from "./zip.js";
42
- export const OWN_JSON_FORMAT = "dsh-gem-map@2";
42
+ /**
43
+ * 自有 JSON 的格式标识。
44
+ *
45
+ * - `@2`:单项目单地图(去掉 `project` 段)。
46
+ * - `@3`:顶层多了 `markers`(标记点:编号 + 名字 + 格坐标)。
47
+ */
48
+ export const OWN_JSON_FORMAT = "dsh-gem-map@3";
43
49
  /** 文件名安全化:名字直接进目录会踩到 `/`、`:` 与超长名。 */
44
50
  export function safeFileName(input, fallback = "map") {
45
51
  const cleaned = (input ?? "")
@@ -57,8 +63,12 @@ export function safeFileName(input, fallback = "map") {
57
63
  * - 没勾:导出目录里没有这些图,读 `map.json` 的人得回项目目录取 —— 这条写在这里,
58
64
  * 免得把 `image` 当成「相对导出目录」而在别处找不到文件。
59
65
  *
60
- * `project` 按契约留在签名上(旧版写过 `project` 段),`dsh-gem-map@2` 的形态里不带它:
66
+ * `project` 按契约留在签名上(旧版写过 `project` 段),`dsh-gem-map@2` 起的形态里不带它:
61
67
  * 一张地图就是一个项目,再套一层只是重复。
68
+ *
69
+ * `markers` 是**源数据**(位置 + 名字),不是画出来的圆圈:`map.png` 里没有标记,
70
+ * 引擎按坐标自己渲染。编号 `n` 写出来是为了让人一眼对得上界面上的数字,
71
+ * 它等于数组下标 + 1(删掉一个,后面自动往前顶)。
62
72
  */
63
73
  export function buildOwnJson(context, doc, project) {
64
74
  void project;
@@ -77,7 +87,8 @@ export function buildOwnJson(context, doc, project) {
77
87
  tileCount: tileset.tiles.length
78
88
  })),
79
89
  legend: flatTiles(context.tilesets).map((flat) => ({ index: flat.index, tilesetId: flat.tilesetId, rect: flat.tile.rect })),
80
- layers: doc.layers.map((layer) => ({ name: layer.name, data: [...(doc.data[layer.id] ?? [])] }))
90
+ layers: doc.layers.map((layer) => ({ name: layer.name, data: [...(doc.data[layer.id] ?? [])] })),
91
+ markers: doc.markers.map((marker, index) => ({ n: index + 1, name: marker.name, r: marker.r, c: marker.c }))
81
92
  };
82
93
  }
83
94
  /** 解出导出用的图集位图。解不出来的留给 `rasterize` 报警(不能静默缺图)。 */
package/lib/mapgen.js CHANGED
@@ -408,6 +408,8 @@ function restoreDoc(target, snapshot) {
408
408
  target.rows = snapshot.rows;
409
409
  target.layers = snapshot.layers.map((layer) => ({ ...layer }));
410
410
  target.data = Object.fromEntries(Object.entries(snapshot.data).map(([key, value]) => [key, [...value]]));
411
+ // ⚠️ 标记也要一起还原:漏了这一句就会「撤销之后标记回不来」——而且不报错。
412
+ target.markers = snapshot.markers.map((marker) => ({ ...marker }));
411
413
  target.updatedAt = new Date().toISOString();
412
414
  }
413
415
  // ── 渲染上下文与坐标 ──────────────────────────────────────────────────────
@@ -478,7 +480,9 @@ export async function applyMapOps(projectId, ops, opts = {}) {
478
480
  const doc = await theDocOrFresh(projectId);
479
481
  const layout = layoutOf(project.grid, doc.cols, doc.rows);
480
482
  const result = applyOps(doc, ops, layout);
481
- if (result.changed > 0) {
483
+ // `touched`(标记改名这类不占格的改动)也要记一步撤销 —— 只看 `changed > 0` 的话,
484
+ // 改名会「生效了但撤不回来」。
485
+ if (result.changed > 0 || result.touched === true) {
482
486
  pushHistory(projectId, { undo: result.undo, redo: ops, stroke: opts.stroke }, doc);
483
487
  scheduleDocWrite(projectId, doc);
484
488
  }
@@ -558,10 +562,14 @@ export async function saveMapDocStructure(projectId, patch) {
558
562
  for (const layerPatch of patch.layers ?? []) {
559
563
  if (typeof layerPatch?.name !== "string" || layerPatch.name.trim() === "")
560
564
  continue;
565
+ // ⚠️ `renameLayer` 对「图层不存在」和「名字没变」都返回 false:
566
+ // 不先判存在性的话,用户把名字原样提交一次就会看到一句「图层不存在」。
567
+ if (!doc.layers.some((layer) => layer.id === layerPatch.id)) {
568
+ warnings.push(`图层不存在:${layerPatch?.id}`);
569
+ continue;
570
+ }
561
571
  if (renameLayer(doc, layerPatch.id, layerPatch.name.trim()))
562
572
  structural = true;
563
- else
564
- warnings.push(`图层不存在:${layerPatch?.id}`);
565
573
  }
566
574
  if (patch.addLayer !== undefined) {
567
575
  addLayer(doc, patch.addLayer?.name);
@@ -602,6 +610,8 @@ export async function saveMapDocStructure(projectId, patch) {
602
610
  structural = true;
603
611
  if (dropped > 0)
604
612
  warnings.push(`缩小地图丢掉了 ${dropped} 个已画的格子(可以撤销)。`);
613
+ if (result.droppedMarkers > 0)
614
+ warnings.push(`缩小地图丢掉了 ${result.droppedMarkers} 个落在界外的标记(可以撤销)。`);
605
615
  }
606
616
  }
607
617
  if (structural) {
@@ -1205,6 +1215,7 @@ export async function mapPlan(projectId, o) {
1205
1215
  visibleKeys,
1206
1216
  chunks: plan.chunks.filter((chunk) => wanted.has(chunk.key) && (!have.has(chunk.key) || forced.has(chunk.key))),
1207
1217
  legend: plan.legend,
1218
+ markers: plan.markers,
1208
1219
  fps: plan.fps,
1209
1220
  frameCount: plan.frameCount,
1210
1221
  truncated,
@@ -1252,6 +1263,7 @@ export async function mapView(p, options = {}) {
1252
1263
  })),
1253
1264
  legend: flat.map((tile) => ({ index: tile.index, tilesetId: tile.tilesetId, rect: tile.tile.rect })),
1254
1265
  layers,
1266
+ markers: doc.markers.map((marker, index) => ({ id: marker.id, n: index + 1, r: marker.r, c: marker.c, name: marker.name })),
1255
1267
  filled: layers.reduce((sum, layer) => sum + layer.filled, 0),
1256
1268
  stages: p.stages,
1257
1269
  reviewMode: p.reviewMode,