dsh-game-material-master 0.9.2 → 0.10.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/isodoc.js ADDED
@@ -0,0 +1,705 @@
1
+ /**
2
+ * 45° 地图编辑器(模块五 · iso)的**文档模型与编辑操作**。
3
+ *
4
+ * 一张地图 = 若干图层。地面层的 `data` 每格存一个**全局图块序号**(1-based,0 = 空);
5
+ * 物件层不在 `data` 里存东西 —— 物件是「参考点 + 素材 + 图层」的独立源数据,
6
+ * 占哪些格由 footprint 现算。这和模块六把「整图」单独存是同一个理由:
7
+ * 一格只装得下一个序号,装不下「占 2×2 + 通行性」。
8
+ *
9
+ * 三条口径:
10
+ *
11
+ * 1. **宿主是唯一写者**:界面只发 op,不整份提交。
12
+ * 2. **派生数据不落盘**:自动连接的 mask、物件占格、绘制顺序、bounds 全部现算。
13
+ * 3. **操作是纯函数**:`applyIsoOps` 直接改传入的 doc,并返回逆操作。
14
+ *
15
+ * 撤销栈不在这里(在 `isogen`):这里只负责「一笔怎么反做」。
16
+ */
17
+ import { MAX_ISO_OBJECTS, assertIsoMapSize, footprintCells, footprintInside, wrapCell } from "./isogeom.js";
18
+ export function isoLayerKindOf(layer) {
19
+ return layer === undefined ? undefined : layer.kind;
20
+ }
21
+ export function cellIndex(doc, r, c) {
22
+ return r * doc.cols + c;
23
+ }
24
+ export function emptyData(cols, rows) {
25
+ return new Array(cols * rows).fill(0);
26
+ }
27
+ function defaultLayers() {
28
+ return [
29
+ { id: "l0", name: "地面层", kind: "ground" },
30
+ { id: "l1", name: "装饰层", kind: "object" },
31
+ { id: "l2", name: "建筑层", kind: "object" }
32
+ ];
33
+ }
34
+ export function createIsoDoc(id, name, cols, rows) {
35
+ assertIsoMapSize(cols, rows);
36
+ const now = new Date().toISOString();
37
+ const layers = defaultLayers();
38
+ const data = {};
39
+ for (const layer of layers)
40
+ data[layer.id] = emptyData(cols, rows);
41
+ return { id, name, cols, rows, layers, data, objects: [], markers: [], createdAt: now, updatedAt: now };
42
+ }
43
+ /** 读盘 / 外部输入 → 合法文档。图层去重、数据裁齐、越界物件/标记丢掉。 */
44
+ export function normalizeIsoDoc(raw, fallbackId) {
45
+ if (raw === null || typeof raw !== "object")
46
+ return undefined;
47
+ const input = raw;
48
+ const cols = Math.max(1, Math.min(512, Math.round(Number(input.cols) || 32)));
49
+ const rows = Math.max(1, Math.min(512, Math.round(Number(input.rows) || 32)));
50
+ const rawLayers = Array.isArray(input.layers) ? input.layers : [];
51
+ const used = new Set();
52
+ const layers = [];
53
+ for (const [index, item] of rawLayers.entries()) {
54
+ const layer = item;
55
+ const id = typeof layer?.id === "string" && layer.id !== "" ? layer.id : `l${index}`;
56
+ const name = typeof layer?.name === "string" && layer.name !== "" ? layer.name : `图层 ${index + 1}`;
57
+ const kind = layer?.kind === "object" ? "object" : "ground";
58
+ let unique = id;
59
+ if (used.has(unique)) {
60
+ let bump = 0;
61
+ while (used.has(`l${bump}`))
62
+ bump++;
63
+ unique = `l${bump}`;
64
+ }
65
+ used.add(unique);
66
+ layers.push({ id: unique, name, kind });
67
+ }
68
+ if (layers.length === 0)
69
+ layers.push(...defaultLayers());
70
+ const layersData = (input.data ?? {});
71
+ const data = {};
72
+ for (const layer of layers) {
73
+ const source = layersData[layer.id];
74
+ const target = emptyData(cols, rows);
75
+ if (Array.isArray(source)) {
76
+ for (let i = 0; i < target.length; i++) {
77
+ const value = Number(source[i]);
78
+ target[i] = Number.isFinite(value) && value > 0 ? Math.round(value) : 0;
79
+ }
80
+ }
81
+ data[layer.id] = target;
82
+ }
83
+ const now = new Date().toISOString();
84
+ return {
85
+ id: typeof input.id === "string" && input.id !== "" ? input.id : fallbackId,
86
+ name: typeof input.name === "string" && input.name !== "" ? input.name : "未命名地图",
87
+ cols,
88
+ rows,
89
+ layers,
90
+ data,
91
+ objects: normalizeObjects(input.objects, layers, cols, rows),
92
+ markers: normalizeMarkers(input.markers, cols, rows),
93
+ createdAt: typeof input.createdAt === "string" ? input.createdAt : now,
94
+ updatedAt: typeof input.updatedAt === "string" ? input.updatedAt : now
95
+ };
96
+ }
97
+ function normalizeObjects(raw, layers, cols, rows) {
98
+ if (!Array.isArray(raw))
99
+ return [];
100
+ const byId = new Map(layers.map((layer) => [layer.id, layer]));
101
+ const used = new Set();
102
+ const out = [];
103
+ let seq = 0;
104
+ const nextId = () => {
105
+ seq++;
106
+ while (used.has(`o${seq}`))
107
+ seq++;
108
+ return `o${seq}`;
109
+ };
110
+ for (const item of raw) {
111
+ const entry = item;
112
+ const r = Math.round(Number(entry?.r));
113
+ const c = Math.round(Number(entry?.c));
114
+ if (!Number.isFinite(r) || !Number.isFinite(c) || r < 0 || c < 0 || r >= rows || c >= cols)
115
+ continue;
116
+ const tilesetId = typeof entry?.tilesetId === "string" ? entry.tilesetId : "";
117
+ const layerId = typeof entry?.layerId === "string" ? entry.layerId : "";
118
+ if (tilesetId === "" || byId.get(layerId)?.kind !== "object")
119
+ continue;
120
+ const given = typeof entry?.id === "string" && entry.id !== "" ? entry.id : "";
121
+ const id = given !== "" && !used.has(given) ? given : nextId();
122
+ used.add(id);
123
+ out.push({ id, tilesetId, layerId, r, c });
124
+ if (out.length >= MAX_ISO_OBJECTS)
125
+ break;
126
+ }
127
+ return out;
128
+ }
129
+ function normalizeMarkers(raw, cols, rows) {
130
+ if (!Array.isArray(raw))
131
+ return [];
132
+ const used = new Set();
133
+ const out = [];
134
+ let seq = 0;
135
+ const nextId = () => {
136
+ seq++;
137
+ while (used.has(`m${seq}`))
138
+ seq++;
139
+ return `m${seq}`;
140
+ };
141
+ for (const item of raw) {
142
+ const marker = item;
143
+ const r = Math.round(Number(marker?.r));
144
+ const c = Math.round(Number(marker?.c));
145
+ if (!Number.isFinite(r) || !Number.isFinite(c) || r < 0 || c < 0 || r >= rows || c >= cols)
146
+ continue;
147
+ const given = typeof marker?.id === "string" && marker.id !== "" ? marker.id : "";
148
+ const id = given !== "" && !used.has(given) ? given : nextId();
149
+ used.add(id);
150
+ out.push({ id, r, c, name: typeof marker?.name === "string" ? marker.name : "" });
151
+ }
152
+ return out;
153
+ }
154
+ export function cloneIsoDoc(doc) {
155
+ const data = {};
156
+ for (const [key, value] of Object.entries(doc.data))
157
+ data[key] = [...value];
158
+ return {
159
+ ...doc,
160
+ layers: doc.layers.map((layer) => ({ ...layer })),
161
+ objects: doc.objects.map((object) => ({ ...object })),
162
+ markers: doc.markers.map((marker) => ({ ...marker })),
163
+ data
164
+ };
165
+ }
166
+ // ── 结构操作 ─────────────────────────────────────────────────────────────
167
+ export function nextLayerId(doc) {
168
+ let index = doc.layers.length;
169
+ while (doc.layers.some((layer) => layer.id === `l${index}`))
170
+ index++;
171
+ return `l${index}`;
172
+ }
173
+ export function addLayer(doc, name, kind = "ground") {
174
+ const layer = {
175
+ id: nextLayerId(doc),
176
+ name: name !== undefined && name !== "" ? name : `图层 ${doc.layers.length + 1}`,
177
+ kind
178
+ };
179
+ doc.layers.push(layer);
180
+ doc.data[layer.id] = emptyData(doc.cols, doc.rows);
181
+ doc.updatedAt = new Date().toISOString();
182
+ return layer;
183
+ }
184
+ export function removeLayer(doc, layerId) {
185
+ if (doc.layers.length <= 1)
186
+ return false;
187
+ const index = doc.layers.findIndex((layer) => layer.id === layerId);
188
+ if (index < 0)
189
+ return false;
190
+ doc.layers.splice(index, 1);
191
+ delete doc.data[layerId];
192
+ doc.objects = doc.objects.filter((object) => object.layerId !== layerId);
193
+ doc.updatedAt = new Date().toISOString();
194
+ return true;
195
+ }
196
+ export function moveLayer(doc, layerId, toIndex) {
197
+ const index = doc.layers.findIndex((layer) => layer.id === layerId);
198
+ if (index < 0)
199
+ return false;
200
+ const target = Math.min(doc.layers.length - 1, Math.max(0, Math.round(toIndex)));
201
+ if (target === index)
202
+ return false;
203
+ const [layer] = doc.layers.splice(index, 1);
204
+ doc.layers.splice(target, 0, layer);
205
+ doc.updatedAt = new Date().toISOString();
206
+ return true;
207
+ }
208
+ export function renameLayer(doc, layerId, name) {
209
+ const layer = doc.layers.find((item) => item.id === layerId);
210
+ if (layer === undefined)
211
+ return false;
212
+ const trimmed = typeof name === "string" ? name.trim() : "";
213
+ if (trimmed === "" || layer.name === trimmed)
214
+ return false;
215
+ layer.name = trimmed;
216
+ doc.updatedAt = new Date().toISOString();
217
+ return true;
218
+ }
219
+ export function clearLayer(doc, layerId) {
220
+ const layer = doc.layers.find((item) => item.id === layerId);
221
+ if (layer === undefined)
222
+ return 0;
223
+ if (layer.kind === "object") {
224
+ const before = doc.objects.length;
225
+ doc.objects = doc.objects.filter((object) => object.layerId !== layerId);
226
+ doc.updatedAt = new Date().toISOString();
227
+ return before - doc.objects.length;
228
+ }
229
+ const data = doc.data[layerId];
230
+ if (data === undefined)
231
+ return 0;
232
+ let count = 0;
233
+ for (let i = 0; i < data.length; i++) {
234
+ if (data[i] !== 0) {
235
+ data[i] = 0;
236
+ count++;
237
+ }
238
+ }
239
+ doc.updatedAt = new Date().toISOString();
240
+ return count;
241
+ }
242
+ export function resizeDoc(doc, cols, rows) {
243
+ assertIsoMapSize(cols, rows);
244
+ let dropped = 0;
245
+ for (const layer of doc.layers) {
246
+ const old = doc.data[layer.id] ?? [];
247
+ const next = emptyData(cols, rows);
248
+ for (let r = 0; r < Math.min(rows, doc.rows); r++) {
249
+ for (let c = 0; c < Math.min(cols, doc.cols); c++) {
250
+ const value = old[r * doc.cols + c] ?? 0;
251
+ if (value > 0)
252
+ next[r * cols + c] = value;
253
+ else if (r < rows && c < cols)
254
+ next[r * cols + c] = 0;
255
+ }
256
+ }
257
+ for (let r = 0; r < doc.rows; r++) {
258
+ for (let c = 0; c < doc.cols; c++) {
259
+ if ((r >= rows || c >= cols) && (old[r * doc.cols + c] ?? 0) > 0)
260
+ dropped++;
261
+ }
262
+ }
263
+ doc.data[layer.id] = next;
264
+ }
265
+ const beforeObjects = doc.objects.length;
266
+ doc.objects = doc.objects.filter((object) => object.r < rows && object.c < cols);
267
+ const droppedObjects = beforeObjects - doc.objects.length;
268
+ const beforeMarkers = doc.markers.length;
269
+ doc.markers = doc.markers.filter((marker) => marker.r < rows && marker.c < cols);
270
+ const droppedMarkers = beforeMarkers - doc.markers.length;
271
+ doc.cols = cols;
272
+ doc.rows = rows;
273
+ doc.updatedAt = new Date().toISOString();
274
+ return { dropped, droppedMarkers, droppedObjects };
275
+ }
276
+ function markDirty(set, r, c) {
277
+ set.set(`${r},${c}`, { r, c });
278
+ }
279
+ function layerOf(doc, layerId) {
280
+ return doc.layers.find((layer) => layer.id === layerId);
281
+ }
282
+ function wrapPoint(layout, r, c) {
283
+ const cell = layout.wrap ? wrapCell(layout, r, c) : { r, c };
284
+ if (cell.r < 0 || cell.c < 0 || cell.r >= layout.rows || cell.c >= layout.cols)
285
+ return undefined;
286
+ return cell;
287
+ }
288
+ function objectOccupied(doc, layout, footprintOf) {
289
+ const out = new Map();
290
+ for (const object of doc.objects) {
291
+ const fp = footprintOf(object.tilesetId) ?? { cols: 1, rows: 1 };
292
+ for (const cell of footprintCells(object.r, object.c, fp)) {
293
+ const wrapped = wrapPoint(layout, cell.r, cell.c);
294
+ if (wrapped !== undefined)
295
+ out.set(`${object.layerId}|${wrapped.r},${wrapped.c}`, object.id);
296
+ }
297
+ }
298
+ return out;
299
+ }
300
+ function makeObjectId(doc) {
301
+ let seq = doc.objects.length + 1;
302
+ while (doc.objects.some((object) => object.id === `o${seq}`))
303
+ seq++;
304
+ return `o${seq}`;
305
+ }
306
+ function makeMarkerId(doc) {
307
+ let seq = doc.markers.length + 1;
308
+ while (doc.markers.some((marker) => marker.id === `m${seq}`))
309
+ seq++;
310
+ return `m${seq}`;
311
+ }
312
+ /** 应用一批 op。所有校验失败都写进 `skipped`,不抛。 */
313
+ export function applyIsoOps(doc, ops, layout, options = {}) {
314
+ const changedCells = new Map();
315
+ const skipped = [];
316
+ const undo = [];
317
+ const redo = [];
318
+ let changed = 0;
319
+ let touched = false;
320
+ const footprintOf = options.footprintOf ?? (() => ({ cols: 1, rows: 1 }));
321
+ const isObjectTileset = options.isObjectTileset ?? (() => true);
322
+ const applyPaint = (layerId, cells, recordUndo) => {
323
+ const layer = layerOf(doc, layerId);
324
+ if (layer === undefined) {
325
+ skipped.push(`没有这一层:${layerId}`);
326
+ return;
327
+ }
328
+ if (layer.kind !== "ground") {
329
+ skipped.push(`「${layer.name}」是物件层,只能用物件笔刷`);
330
+ return;
331
+ }
332
+ const data = doc.data[layerId];
333
+ if (data === undefined)
334
+ return;
335
+ const previous = [];
336
+ const applied = [];
337
+ for (const input of cells) {
338
+ const cell = wrapPoint(layout, input.r, input.c);
339
+ if (cell === undefined) {
340
+ skipped.push(`${input.r},${input.c} 在地图外`);
341
+ continue;
342
+ }
343
+ const tile = Math.max(0, Math.round(Number(input.tile) || 0));
344
+ const index = cellIndex(doc, cell.r, cell.c);
345
+ const before = data[index] ?? 0;
346
+ if (before === tile) {
347
+ applied.push({ r: cell.r, c: cell.c, tile });
348
+ continue;
349
+ }
350
+ previous.push({ r: cell.r, c: cell.c, tile: before });
351
+ data[index] = tile;
352
+ applied.push({ r: cell.r, c: cell.c, tile });
353
+ markDirty(changedCells, cell.r, cell.c);
354
+ changed++;
355
+ }
356
+ if (recordUndo) {
357
+ if (previous.length > 0)
358
+ undo.push({ kind: "paint", layerId, cells: previous });
359
+ if (applied.length > 0)
360
+ redo.push({ kind: "paint", layerId, cells: applied });
361
+ }
362
+ };
363
+ const applyObjectAdd = (op, recordUndo) => {
364
+ const layer = layerOf(doc, op.layerId);
365
+ if (layer === undefined || layer.kind !== "object") {
366
+ skipped.push("物件只能放在物件层");
367
+ return;
368
+ }
369
+ if (!isObjectTileset(op.tilesetId)) {
370
+ skipped.push("这块素材不是物件");
371
+ return;
372
+ }
373
+ const fp = footprintOf(op.tilesetId) ?? { cols: 1, rows: 1 };
374
+ if (!footprintInside(layout, op.r, op.c, fp)) {
375
+ skipped.push("物件放不下:占格超出了地图(贴边时挪一格)");
376
+ return;
377
+ }
378
+ if (doc.objects.length >= MAX_ISO_OBJECTS) {
379
+ skipped.push(`物件太多了(上限 ${MAX_ISO_OBJECTS} 个)`);
380
+ return;
381
+ }
382
+ const occupied = objectOccupied(doc, layout, footprintOf);
383
+ for (const cell of footprintCells(op.r, op.c, fp)) {
384
+ const wrapped = wrapPoint(layout, cell.r, cell.c);
385
+ if (wrapped === undefined)
386
+ continue;
387
+ if (occupied.has(`${op.layerId}|${wrapped.r},${wrapped.c}`)) {
388
+ skipped.push("这里已经有物件了(同一层不能重叠)");
389
+ return;
390
+ }
391
+ }
392
+ let id = typeof op.id === "string" && op.id !== "" && !doc.objects.some((object) => object.id === op.id) ? op.id : makeObjectId(doc);
393
+ const object = { id, tilesetId: op.tilesetId, layerId: op.layerId, r: op.r, c: op.c };
394
+ doc.objects.push(object);
395
+ for (const cell of footprintCells(op.r, op.c, fp))
396
+ markDirty(changedCells, cell.r, cell.c);
397
+ changed++;
398
+ if (recordUndo) {
399
+ undo.push({ kind: "object", op: "remove", id });
400
+ redo.push({ kind: "object", op: "add", layerId: op.layerId, tilesetId: op.tilesetId, r: op.r, c: op.c, id });
401
+ }
402
+ };
403
+ const applyObjectMove = (op, recordUndo) => {
404
+ const object = doc.objects.find((entry) => entry.id === op.id);
405
+ if (object === undefined) {
406
+ skipped.push(`没有这个物件:${op.id}`);
407
+ return;
408
+ }
409
+ const fp = footprintOf(object.tilesetId) ?? { cols: 1, rows: 1 };
410
+ if (!footprintInside(layout, op.r, op.c, fp)) {
411
+ skipped.push("物件放不下:占格超出了地图");
412
+ return;
413
+ }
414
+ const occupied = objectOccupied(doc, layout, footprintOf);
415
+ for (const cell of footprintCells(op.r, op.c, fp)) {
416
+ const wrapped = wrapPoint(layout, cell.r, cell.c);
417
+ if (wrapped === undefined)
418
+ continue;
419
+ const owner = occupied.get(`${object.layerId}|${wrapped.r},${wrapped.c}`);
420
+ if (owner !== undefined && owner !== object.id) {
421
+ skipped.push("目标位置已经有物件了");
422
+ return;
423
+ }
424
+ }
425
+ const before = { r: object.r, c: object.c };
426
+ for (const cell of footprintCells(object.r, object.c, fp))
427
+ markDirty(changedCells, cell.r, cell.c);
428
+ object.r = op.r;
429
+ object.c = op.c;
430
+ for (const cell of footprintCells(op.r, op.c, fp))
431
+ markDirty(changedCells, cell.r, cell.c);
432
+ changed++;
433
+ if (recordUndo) {
434
+ undo.push({ kind: "object", op: "move", id: object.id, r: before.r, c: before.c });
435
+ redo.push({ kind: "object", op: "move", id: object.id, r: op.r, c: op.c });
436
+ }
437
+ };
438
+ const applyObjectRemove = (op, recordUndo) => {
439
+ const index = doc.objects.findIndex((entry) => entry.id === op.id);
440
+ if (index < 0) {
441
+ skipped.push(`没有这个物件:${op.id}`);
442
+ return;
443
+ }
444
+ const object = doc.objects[index];
445
+ const fp = footprintOf(object.tilesetId) ?? { cols: 1, rows: 1 };
446
+ for (const cell of footprintCells(object.r, object.c, fp))
447
+ markDirty(changedCells, cell.r, cell.c);
448
+ doc.objects.splice(index, 1);
449
+ changed++;
450
+ if (recordUndo) {
451
+ undo.push({ kind: "object", op: "add", layerId: object.layerId, tilesetId: object.tilesetId, r: object.r, c: object.c, id: object.id });
452
+ redo.push({ kind: "object", op: "remove", id: object.id });
453
+ }
454
+ };
455
+ for (const raw of ops) {
456
+ const op = raw;
457
+ const kind = op.kind;
458
+ if (kind === "paint") {
459
+ const layerId = String(op.layerId ?? "");
460
+ const cells = Array.isArray(op.cells) ? op.cells : [];
461
+ applyPaint(layerId, cells.map((cell) => ({ r: Math.round(Number(cell?.r)), c: Math.round(Number(cell?.c)), tile: Math.round(Number(cell?.tile)) })).filter((cell) => Number.isFinite(cell.r) && Number.isFinite(cell.c)), true);
462
+ continue;
463
+ }
464
+ if (kind === "fill") {
465
+ const layerId = String(op.layerId ?? "");
466
+ const layer = layerOf(doc, layerId);
467
+ if (layer === undefined || layer.kind !== "ground") {
468
+ skipped.push("油漆桶只能用在空地层");
469
+ continue;
470
+ }
471
+ const hit = wrapPoint(layout, Math.round(Number(op.r)), Math.round(Number(op.c)));
472
+ if (hit === undefined) {
473
+ skipped.push("起点在地图外");
474
+ continue;
475
+ }
476
+ const data = doc.data[layerId];
477
+ if (data === undefined)
478
+ continue;
479
+ const tile = Math.max(0, Math.round(Number(op.tile) || 0));
480
+ const from = data[cellIndex(doc, hit.r, hit.c)] ?? 0;
481
+ if (from === tile)
482
+ continue;
483
+ const queue = [hit];
484
+ const seen = new Set();
485
+ const cells = [];
486
+ while (queue.length > 0) {
487
+ const at = queue.pop();
488
+ const key = `${at.r},${at.c}`;
489
+ if (seen.has(key))
490
+ continue;
491
+ seen.add(key);
492
+ if (at.r < 0 || at.c < 0 || at.r >= doc.rows || at.c >= doc.cols)
493
+ continue;
494
+ if ((data[at.r * doc.cols + at.c] ?? 0) !== from)
495
+ continue;
496
+ cells.push({ r: at.r, c: at.c, tile });
497
+ queue.push({ r: at.r - 1, c: at.c }, { r: at.r + 1, c: at.c }, { r: at.r, c: at.c - 1 }, { r: at.r, c: at.c + 1 });
498
+ }
499
+ applyPaint(layerId, cells, true);
500
+ continue;
501
+ }
502
+ if (kind === "rect") {
503
+ const layerId = String(op.layerId ?? "");
504
+ const layer = layerOf(doc, layerId);
505
+ if (layer === undefined || layer.kind !== "ground") {
506
+ skipped.push("矩形只能画在空地层");
507
+ continue;
508
+ }
509
+ const r0 = Math.round(Number(op.r0));
510
+ const c0 = Math.round(Number(op.c0));
511
+ const r1 = Math.round(Number(op.r1));
512
+ const c1 = Math.round(Number(op.c1));
513
+ const tile = Math.max(0, Math.round(Number(op.tile) || 0));
514
+ const filled = op.filled !== false;
515
+ const cells = [];
516
+ for (let r = Math.min(r0, r1); r <= Math.max(r0, r1); r++) {
517
+ for (let c = Math.min(c0, c1); c <= Math.max(c0, c1); c++) {
518
+ if (!filled && r !== r0 && r !== r1 && c !== c0 && c !== c1)
519
+ continue;
520
+ cells.push({ r, c, tile });
521
+ }
522
+ }
523
+ applyPaint(layerId, cells, true);
524
+ continue;
525
+ }
526
+ if (kind === "replace") {
527
+ const layerId = String(op.layerId ?? "");
528
+ const layer = layerOf(doc, layerId);
529
+ if (layer === undefined || layer.kind !== "ground") {
530
+ skipped.push("替换只能用在空地层");
531
+ continue;
532
+ }
533
+ const data = doc.data[layerId];
534
+ if (data === undefined)
535
+ continue;
536
+ const from = Math.max(0, Math.round(Number(op.from) || 0));
537
+ const to = Math.max(0, Math.round(Number(op.to) || 0));
538
+ if (from === to)
539
+ continue;
540
+ const cells = [];
541
+ for (let i = 0; i < data.length; i++) {
542
+ if (data[i] === from)
543
+ cells.push({ r: Math.floor(i / doc.cols), c: i % doc.cols, tile: to });
544
+ }
545
+ applyPaint(layerId, cells, true);
546
+ continue;
547
+ }
548
+ if (kind === "object") {
549
+ const action = op.op;
550
+ if (action === "add") {
551
+ applyObjectAdd({
552
+ kind: "object",
553
+ op: "add",
554
+ layerId: String(op.layerId ?? ""),
555
+ tilesetId: String(op.tilesetId ?? ""),
556
+ r: Math.round(Number(op.r)),
557
+ c: Math.round(Number(op.c)),
558
+ id: typeof op.id === "string" ? op.id : undefined
559
+ }, true);
560
+ }
561
+ else if (action === "move") {
562
+ applyObjectMove({ kind: "object", op: "move", id: String(op.id ?? ""), r: Math.round(Number(op.r)), c: Math.round(Number(op.c)) }, true);
563
+ }
564
+ else if (action === "remove") {
565
+ applyObjectRemove({ kind: "object", op: "remove", id: String(op.id ?? "") }, true);
566
+ }
567
+ else {
568
+ skipped.push(`未知物件操作:${String(action)}`);
569
+ }
570
+ continue;
571
+ }
572
+ if (kind === "marker") {
573
+ const action = op.op;
574
+ if (action === "add") {
575
+ const hit = wrapPoint(layout, Math.round(Number(op.r)), Math.round(Number(op.c)));
576
+ if (hit === undefined) {
577
+ skipped.push("标记点在地图外");
578
+ continue;
579
+ }
580
+ if (doc.markers.some((marker) => marker.r === hit.r && marker.c === hit.c)) {
581
+ skipped.push("这一格已经有标记了(一格最多一个)");
582
+ continue;
583
+ }
584
+ const id = typeof op.id === "string" && op.id !== "" && !doc.markers.some((marker) => marker.id === op.id) ? op.id : makeMarkerId(doc);
585
+ const name = typeof op.name === "string" ? op.name : "";
586
+ doc.markers.push({ id, r: hit.r, c: hit.c, name });
587
+ markDirty(changedCells, hit.r, hit.c);
588
+ changed++;
589
+ touched = true;
590
+ undo.push({ kind: "marker", op: "remove", id });
591
+ redo.push({ kind: "marker", op: "add", r: hit.r, c: hit.c, name, id });
592
+ continue;
593
+ }
594
+ if (action === "remove") {
595
+ const index = doc.markers.findIndex((marker) => marker.id === op.id);
596
+ if (index < 0) {
597
+ skipped.push(`没有这个标记:${String(op.id)}`);
598
+ continue;
599
+ }
600
+ const marker = doc.markers[index];
601
+ doc.markers.splice(index, 1);
602
+ for (const entry of doc.markers)
603
+ markDirty(changedCells, entry.r, entry.c);
604
+ markDirty(changedCells, marker.r, marker.c);
605
+ changed++;
606
+ touched = true;
607
+ undo.push({ kind: "marker", op: "add", r: marker.r, c: marker.c, name: marker.name, id: marker.id });
608
+ redo.push({ kind: "marker", op: "remove", id: marker.id });
609
+ continue;
610
+ }
611
+ if (action === "move") {
612
+ const marker = doc.markers.find((entry) => entry.id === op.id);
613
+ if (marker === undefined) {
614
+ skipped.push(`没有这个标记:${String(op.id)}`);
615
+ continue;
616
+ }
617
+ const hit = wrapPoint(layout, Math.round(Number(op.r)), Math.round(Number(op.c)));
618
+ if (hit === undefined) {
619
+ skipped.push("标记点在地图外");
620
+ continue;
621
+ }
622
+ if (doc.markers.some((entry) => entry.id !== marker.id && entry.r === hit.r && entry.c === hit.c)) {
623
+ skipped.push("目标格已经有标记了");
624
+ continue;
625
+ }
626
+ const before = { r: marker.r, c: marker.c };
627
+ markDirty(changedCells, before.r, before.c);
628
+ marker.r = hit.r;
629
+ marker.c = hit.c;
630
+ markDirty(changedCells, hit.r, hit.c);
631
+ changed++;
632
+ touched = true;
633
+ undo.push({ kind: "marker", op: "move", id: marker.id, r: before.r, c: before.c });
634
+ redo.push({ kind: "marker", op: "move", id: marker.id, r: hit.r, c: hit.c });
635
+ continue;
636
+ }
637
+ if (action === "rename") {
638
+ const marker = doc.markers.find((entry) => entry.id === op.id);
639
+ if (marker === undefined) {
640
+ skipped.push(`没有这个标记:${String(op.id)}`);
641
+ continue;
642
+ }
643
+ const name = typeof op.name === "string" ? op.name : "";
644
+ const before = marker.name;
645
+ marker.name = name;
646
+ touched = true;
647
+ undo.push({ kind: "marker", op: "rename", id: marker.id, name: before });
648
+ redo.push({ kind: "marker", op: "rename", id: marker.id, name });
649
+ continue;
650
+ }
651
+ skipped.push(`未知标记操作:${String(action)}`);
652
+ continue;
653
+ }
654
+ skipped.push(`未知操作:${String(kind)}`);
655
+ }
656
+ if (changed > 0 || touched)
657
+ doc.updatedAt = new Date().toISOString();
658
+ return { changed, skipped, dirty: [...changedCells.values()], touched, undo, redo };
659
+ }
660
+ /** 把 op 应用到文档(撤销 / 重做时也走这里,只是不再往回记历史)。 */
661
+ export function revertIsoOps(doc, ops, layout, options = {}) {
662
+ return applyIsoOps(doc, ops, layout, options);
663
+ }
664
+ export function nextMarkerId(doc) {
665
+ return makeMarkerId(doc);
666
+ }
667
+ export function filledCount(doc, layerId) {
668
+ if (layerId !== undefined) {
669
+ const layer = layerOf(doc, layerId);
670
+ if (layer?.kind === "object")
671
+ return doc.objects.filter((object) => object.layerId === layerId).length;
672
+ const data = doc.data[layerId] ?? [];
673
+ return data.reduce((sum, value) => sum + (value > 0 ? 1 : 0), 0);
674
+ }
675
+ let sum = 0;
676
+ for (const layer of doc.layers)
677
+ sum += filledCount(doc, layer.id);
678
+ return sum;
679
+ }
680
+ export function objectCount(doc, layerId) {
681
+ return layerId === undefined ? doc.objects.length : doc.objects.filter((object) => object.layerId === layerId).length;
682
+ }
683
+ export function isDocEmpty(doc) {
684
+ if (doc.objects.length > 0 || doc.markers.length > 0)
685
+ return false;
686
+ return Object.values(doc.data).every((data) => data.every((value) => value === 0));
687
+ }
688
+ export function usedTileIndices(doc) {
689
+ const out = new Set();
690
+ for (const data of Object.values(doc.data)) {
691
+ for (const value of data)
692
+ if (value > 0)
693
+ out.add(value);
694
+ }
695
+ return out;
696
+ }
697
+ /** 导出 / 选择范围:右下开区间,裁到地图内。 */
698
+ export function clampDocRange(doc, range) {
699
+ return {
700
+ r0: Math.max(0, Math.min(doc.rows, range.r0)),
701
+ c0: Math.max(0, Math.min(doc.cols, range.c0)),
702
+ r1: Math.max(0, Math.min(doc.rows, range.r1)),
703
+ c1: Math.max(0, Math.min(doc.cols, range.c1))
704
+ };
705
+ }