dsh-game-material-master 0.2.0 → 0.3.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/tilemap.js ADDED
@@ -0,0 +1,560 @@
1
+ /**
2
+ * 地图地块模块的**拼图**:把单元格地块按等距网格铺成一张地图。
3
+ *
4
+ * ## 坐标系统(最容易写错的一处)
5
+ *
6
+ * ```
7
+ * 单元格:cellWidth × cellHeight(默认 64×96)
8
+ * 菱形: 宽 = cellWidth,高 = cellWidth / 2(2:1 等距)
9
+ * 步进: stepX = cellWidth / 2
10
+ * stepY = 菱形高 / 2 = cellWidth / 4 ← 来自菱形高,**不是 cellHeight**
11
+ * ```
12
+ *
13
+ * 写成 `stepY = cellHeight / 4` 会得到 24(正确是 16),整张图就裂了。
14
+ * 研究期第一次拼图正是把「贴图尺寸」当成了「网格步进」,整张图裂成白格。
15
+ *
16
+ * ## 绘制顺序即遮挡顺序
17
+ *
18
+ * 按 `(r + c)` 升序绘制。前面一行的地块天然会盖住后面那格装饰的下半部 ——
19
+ * 这正是等距游戏想要的效果,**不需要**额外的 z 排序逻辑。
20
+ */
21
+ import { diamondHeight } from "./tilegeom.js";
22
+ export function emptyMapState(rows = 14, cols = 14, fill = "grass", seed = 20261004) {
23
+ return {
24
+ rows,
25
+ cols,
26
+ seed,
27
+ cells: Array.from({ length: rows }, () => Array.from({ length: cols }, () => fill)),
28
+ decor: {},
29
+ buildings: []
30
+ };
31
+ }
32
+ /**
33
+ * 确定性 PRNG(mulberry32)。
34
+ *
35
+ * **不能用 `Math.random`** —— 验收标准要求「同种子 + 同布局 → 逐像素一致」,
36
+ * 而 `Math.random` 会让每次铺图都不同,用户也就无法复现一张满意的地图。
37
+ */
38
+ export function mulberry32(seed) {
39
+ let a = seed >>> 0;
40
+ return () => {
41
+ a = (a + 0x6d2b79f5) >>> 0;
42
+ let t = a;
43
+ t = Math.imul(t ^ (t >>> 15), t | 1);
44
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
45
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
46
+ };
47
+ }
48
+ export function tileLayout(settings, rows, cols, scale = 1) {
49
+ const stepX = (settings.cellWidth / 2) * scale;
50
+ // stepY 来自**菱形高**(= cellWidth/2)的一半,不是 cellHeight/4。
51
+ // 写成 cellHeight/4 会得到 24(正确 16),整张图就裂了。
52
+ const stepY = (diamondHeight(settings) / 2) * scale;
53
+ const cellW = settings.cellWidth * scale;
54
+ const cellH = settings.cellHeight * scale;
55
+ return {
56
+ stepX,
57
+ stepY,
58
+ originX: (rows - 1) * stepX,
59
+ // 最上面那格的上方留一个单元格高,给高出地面的装饰留空间
60
+ originY: cellH,
61
+ canvasW: Math.ceil((cols + rows) * stepX + cellW),
62
+ canvasH: Math.ceil((rows + cols) * stepY + cellH * 2)
63
+ };
64
+ }
65
+ /** 第 (r, c) 格贴图的左上角像素位置。 */
66
+ export function tileOriginAt(layout, r, c) {
67
+ return {
68
+ x: Math.round(layout.originX + (c - r) * layout.stepX),
69
+ y: Math.round(layout.originY + (c + r) * layout.stepY)
70
+ };
71
+ }
72
+ /**
73
+ * 在画布上填一个**实心菱形**(用于建筑底面的地面垫底)。
74
+ *
75
+ * 为什么需要:建筑贴图只覆盖它自己那块形状,底面菱形的四个角是透明的,
76
+ * 而它占掉的 2×2 格已经被清空(否则同一个精灵会被当 1 格地面再画 4 遍)。
77
+ * 不垫底的话地图上会露出一块**透明洞**(实测建筑脚下是白色菱形缺口)。
78
+ */
79
+ function fillDiamondSolid(dst, dstW, dstH, cx, cy, halfW, halfH, color, alpha) {
80
+ const y0 = Math.max(0, Math.floor(cy - halfH));
81
+ const y1 = Math.min(dstH - 1, Math.ceil(cy + halfH));
82
+ for (let y = y0; y <= y1; y++) {
83
+ const dy = Math.abs(y + 0.5 - cy) / halfH;
84
+ if (dy > 1)
85
+ continue;
86
+ const half = halfW * (1 - dy);
87
+ const x0 = Math.max(0, Math.ceil(cx - half));
88
+ const x1 = Math.min(dstW - 1, Math.floor(cx + half));
89
+ for (let x = x0; x <= x1; x++) {
90
+ const o = (y * dstW + x) * 4;
91
+ const a = alpha / 255;
92
+ dst[o] = Math.round(color[0] * a + dst[o] * (1 - a));
93
+ dst[o + 1] = Math.round(color[1] * a + dst[o + 1] * (1 - a));
94
+ dst[o + 2] = Math.round(color[2] * a + dst[o + 2] * (1 - a));
95
+ dst[o + 3] = Math.max(dst[o + 3], alpha);
96
+ }
97
+ }
98
+ }
99
+ /** 一张贴图里不透明像素的平均颜色(用作垫底色)。 */
100
+ function averageColor(src) {
101
+ let r = 0, g = 0, b = 0, n = 0;
102
+ for (let i = 0; i < src.width * src.height; i++) {
103
+ const o = i * 4;
104
+ if (src.rgba[o + 3] < 200)
105
+ continue;
106
+ r += src.rgba[o];
107
+ g += src.rgba[o + 1];
108
+ b += src.rgba[o + 2];
109
+ n++;
110
+ }
111
+ if (n === 0)
112
+ return [0, 0, 0];
113
+ return [r / n, g / n, b / n];
114
+ }
115
+ /**
116
+ * 按「位置 + 种子」**确定性地**挑一个变体。
117
+ *
118
+ * 为什么必须确定性(而不是随机):
119
+ * · 界面要在**不花钱、不跑拼图**的前提下先预览出来,它得自己挑变体;
120
+ * · 宿主若用 `Math.random()`,预览与成品就永远对不上 ——
121
+ * 用户看到「预览和出图不一样」,会以为编辑的不是刚才那张。
122
+ *
123
+ * 位置相关的整数哈希,两边各算一次必然相同。种子参与运算,
124
+ * 所以「换个种子重铺」仍然能换出一张不一样的图。
125
+ */
126
+ export function pickVariantIndex(seed, r, c, count) {
127
+ if (count <= 1)
128
+ return 0;
129
+ const s = Number.isFinite(seed) ? Math.trunc(seed) : 0;
130
+ let h = (s ^ 0x9e3779b9) >>> 0;
131
+ h = Math.imul(h ^ (r + 0x85ebca6b), 0xc2b2ae35) >>> 0;
132
+ h = Math.imul(h ^ (c + 0x27d4eb2f), 0x165667b1) >>> 0;
133
+ h = (h ^ (h >>> 15)) >>> 0;
134
+ return h % count;
135
+ }
136
+ /**
137
+ * 从一个 `buildingGround` 条目取**形状**。
138
+ *
139
+ * 优先第 5 位的新格式;没有就按第 2/3 位的包围矩形还原(老数据)。
140
+ * 这样拼图、包围盒、界面三处读的是同一个形状。
141
+ */
142
+ export function shapeOfEntry(entry) {
143
+ if (entry === undefined)
144
+ return [[0, 0]];
145
+ const shape = entry[5];
146
+ if (Array.isArray(shape) && shape.length > 0)
147
+ return shape;
148
+ const cols = Math.max(1, entry[2] ?? 1);
149
+ const rows = Math.max(1, entry[3] ?? 1);
150
+ const out = [];
151
+ for (let r = 0; r < rows; r++)
152
+ for (let c = 0; c < cols; c++)
153
+ out.push([r, c]);
154
+ return out;
155
+ }
156
+ /**
157
+ * 形状的包围菱形**半宽/半高**(与 `tilegeom.shapeHalfWidthLocal` 同一条公式)。
158
+ *
159
+ * 每格相对锚点的水平偏移是 `(dc − dr)·cellWidth/4`,所以跨度由 `(dc−dr)` 的极差决定。
160
+ * ⚠️ 别用 `(fw+fh)/2` —— 那**只对实心矩形**成立,L 形会算出两倍宽。
161
+ */
162
+ export function shapeDiamondHalf(shape, cellWidth) {
163
+ if (shape.length === 0)
164
+ return { halfW: cellWidth / 2, halfH: cellWidth / 4 };
165
+ // 用**实际 x/y 偏移**算极差,别用「列数 + 行数」——
166
+ // 那个指数和会把同一个方向的跨度算两遍(L 形会算成 64 而不是 48)。
167
+ let minX = Infinity, maxX = -Infinity;
168
+ for (const [r, c] of shape) {
169
+ const x = c - r;
170
+ if (x < minX)
171
+ minX = x;
172
+ if (x > maxX)
173
+ maxX = x;
174
+ }
175
+ const halfW = ((maxX - minX) * (cellWidth / 2) + cellWidth) / 2;
176
+ return { halfW, halfH: halfW / 2 };
177
+ }
178
+ /**
179
+ * 形状的底面中心相对**锚点格中心**的偏移(1× 像素)。
180
+ *
181
+ * 定义:占格各格**菱形中心**的**包围盒中点**。
182
+ *
183
+ * ## 坐标变换(这里踩过好几次,务必看清)
184
+ *
185
+ * 格 `(r,c)` 相对锚点的等距偏移是
186
+ * `x = (c − r)·stepX`、`y = (c + r)·stepY`,其中
187
+ * `stepX = cellWidth/2`、`stepY = cellWidth/4`。
188
+ * 所以 x 取极差、y 取极差,各自**再除以 2**:
189
+ *
190
+ * ```
191
+ * dx = (max(c−r) + min(c−r))/2 · stepX
192
+ * dy = (max(c+r) + min(c+r))/2 · stepY
193
+ * ```
194
+ *
195
+ * 实心矩形 `fw×fh` 化简后正好是 `dx = (fw−1)·stepX/2`、`dy = (fh−1)·stepY/2`,
196
+ * 也就是老代码的 `((fw−1)·cellW/2)/2`、`((fh−1)·cellW/4)/2` —— **逐字一致**
197
+ * (注意 dy 的括号因子是 `cellW/4 = stepY`,写成 `cellW/8` 就少一半)。
198
+ *
199
+ * ⚠️ 别用「各格中心的平均」:那对不对称形状(L 形)会偏。
200
+ * ⚠️ 也别用「各格中心包围盒的中点」之外的自创定义 —— 它与
201
+ * `assembleMap` 的垫底范围、`measureAssemblyBounds` 的包围盒、界面预览
202
+ * 三处必须**同口径**,否则又是「保存后错半格」那类问题。
203
+ */
204
+ export function shapeBaseOffset(shape, cellWidth) {
205
+ if (shape.length === 0)
206
+ return { dx: 0, dy: 0 };
207
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
208
+ for (const [r, c] of shape) {
209
+ const x = c - r;
210
+ const y = c + r;
211
+ if (x < minX)
212
+ minX = x;
213
+ if (x > maxX)
214
+ maxX = x;
215
+ if (y < minY)
216
+ minY = y;
217
+ if (y > maxY)
218
+ maxY = y;
219
+ }
220
+ return {
221
+ dx: ((minX + maxX) / 2) * (cellWidth / 2),
222
+ dy: ((minY + maxY) / 2) * (cellWidth / 4)
223
+ };
224
+ }
225
+ /** 只量几何、不画像素。 */
226
+ export function measureAssemblyBounds(lookup, state, options) {
227
+ const { settings } = options;
228
+ const layout = tileLayout(settings, state.rows, state.cols);
229
+ const cellW = settings.cellWidth;
230
+ const cellH = settings.cellHeight;
231
+ // 地面菱形在单元格里的位置:上下各留 cellH/3 给装饰(见 tilegeom 的注释)
232
+ const groundInset = Math.round(cellH / 3);
233
+ const diamondH = Math.round(cellW / 2);
234
+ let left = Infinity;
235
+ let top = Infinity;
236
+ let right = -Infinity;
237
+ let bottom = -Infinity;
238
+ const put = (x, y, w, h) => {
239
+ if (!Number.isFinite(x) || !Number.isFinite(y) || w <= 0 || h <= 0)
240
+ return;
241
+ if (x < left)
242
+ left = x;
243
+ if (y < top)
244
+ top = y;
245
+ if (x + w > right)
246
+ right = x + w;
247
+ if (y + h > bottom)
248
+ bottom = y + h;
249
+ };
250
+ for (let r = 0; r < state.rows; r++) {
251
+ for (let c = 0; c < state.cols; c++) {
252
+ const origin = tileOriginAt(layout, r, c);
253
+ const family = state.cells[r]?.[c] ?? "";
254
+ if (family !== "") {
255
+ // 地面:菱形那一段(水平方向按整格,菱形只占中间 cellW,差不了多少)
256
+ const insetX = Math.round((cellW - diamondH * 2) / 2);
257
+ put(origin.x - insetX, origin.y + groundInset, cellW, diamondH);
258
+ }
259
+ const decorName = state.decor[`${r},${c}`];
260
+ if (typeof decorName === "string" && decorName !== "") {
261
+ put(origin.x, origin.y, cellW, cellH);
262
+ }
263
+ }
264
+ }
265
+ const groundByBuilding = new Map();
266
+ for (const entry of state.buildingGround ?? []) {
267
+ groundByBuilding.set(`${entry[0]},${entry[1]}`, shapeOfEntry(entry));
268
+ }
269
+ for (const [r, c, name] of state.buildings ?? []) {
270
+ const sprite = lookup.get(name);
271
+ const origin = tileOriginAt(layout, r, c);
272
+ const shape = groundByBuilding.get(`${r},${c}`) ?? [[0, 0]];
273
+ const off = shapeBaseOffset(shape, cellW);
274
+ const anchorCx = origin.x + cellW / 2;
275
+ const anchorCy = origin.y + cellH / 2;
276
+ const baseX = anchorCx + off.dx;
277
+ const baseY = anchorCy + off.dy;
278
+ if (sprite !== undefined) {
279
+ const base = typeof sprite.baseFraction === "number"
280
+ ? sprite.baseFraction * sprite.height
281
+ : sprite.height - cellH / 2;
282
+ put(Math.round(baseX - sprite.width / 2), Math.round(baseY - base), sprite.width, sprite.height);
283
+ }
284
+ // 垫底菱形(`fillDiamondSolid` 的口径)—— **逐格**,与 `assembleMap` 同口径。
285
+ // 逐格而不是一个大菱形:非矩形形状(L 形)的大菱形会把凹口算进来
286
+ // (包围盒反而偏大,裁剪时多留一圈白,不至于错格,但要与宿主一致)。
287
+ const cellHalfW = cellW / 4;
288
+ const cellHalfH = cellHalfW / 2;
289
+ for (const [dr, dc] of shape) {
290
+ const cx2 = anchorCx + (dc - dr) * (cellW / 4);
291
+ const cy2 = anchorCy + (dc + dr) * (cellW / 8);
292
+ put(Math.ceil(cx2 - cellHalfW), Math.floor(cy2 - cellHalfH), Math.floor(cx2 + cellHalfW) - Math.ceil(cx2 - cellHalfW) + 1, Math.ceil(cy2 + cellHalfH) - Math.floor(cy2 - cellHalfH) + 1);
293
+ }
294
+ }
295
+ if (!Number.isFinite(left))
296
+ return { left: 0, top: 0, width: 0, height: 0 };
297
+ // 不做额外留白:宿主用**同一个矩形**裁剪(`cropBitmap`),
298
+ // 所以「矩形 → map.png」是恒等映射,多留白只会平白多一圈透明边。
299
+ const l = Math.floor(left);
300
+ const t = Math.floor(top);
301
+ return {
302
+ left: l,
303
+ top: t,
304
+ width: Math.ceil(right) - l,
305
+ height: Math.ceil(bottom) - t
306
+ };
307
+ }
308
+ /**
309
+ * 按**给定的**矩形裁剪(与 `trimTransparent` 的区别:矩形是调用方算好的)。
310
+ *
311
+ * 为什么不让 `trimTransparent` 自己去量:那样「裁剪矩形」就成了**不透明像素的
312
+ * 函数**,界面算不出同一个值来(它不解码贴图)。于是宿主的 `pixel` 与界面按布局
313
+ * 算出的偏移会各说各话 —— 真机上就是「房子上移一格 / 点到的格子和涂到的差一格」。
314
+ *
315
+ * 现在裁剪与上报用**同一个矩形**:界面拿 `measureAssemblyBounds` 各算一遍,
316
+ * 必然一致。矩形超出画布的部分会被夹住,返回的 `left/top` 是**夹过之后**的真值,
317
+ * 所以坐标换算永远成立。
318
+ */
319
+ export function cropBitmap(src, rect) {
320
+ const left = Math.max(0, Math.min(rect.left, Math.max(0, src.width - 1)));
321
+ const top = Math.max(0, Math.min(rect.top, Math.max(0, src.height - 1)));
322
+ const right = Math.max(left + 1, Math.min(rect.left + rect.width, src.width));
323
+ const bottom = Math.max(top + 1, Math.min(rect.top + rect.height, src.height));
324
+ const w = right - left;
325
+ const h = bottom - top;
326
+ const rgba = Buffer.alloc(w * h * 4);
327
+ for (let y = 0; y < h; y++) {
328
+ src.rgba.copy(rgba, y * w * 4, ((y + top) * src.width + left) * 4, ((y + top) * src.width + left + w) * 4);
329
+ }
330
+ return Object.assign({ width: w, height: h, rgba }, { left, top });
331
+ }
332
+ export function assembleMap(lookup, state, options) {
333
+ const { settings } = options;
334
+ if (state.rows < 1 || state.cols < 1)
335
+ throw new Error("地图至少要有 1 行 1 列");
336
+ if (state.rows > 64 || state.cols > 64)
337
+ throw new Error(`地图最大 64×64,收到 ${state.cols}×${state.rows}`);
338
+ const layout = tileLayout(settings, state.rows, state.cols);
339
+ const { stepX, stepY, canvasW, canvasH } = layout;
340
+ const cellW = settings.cellWidth;
341
+ const cellH = settings.cellHeight;
342
+ // 画布尺寸守卫:不守卫的话 64×64 会尝试分配几百 MB 然后 OOM
343
+ if (canvasW * canvasH > 64 * 1024 * 1024) {
344
+ throw new Error(`地图画布过大(${canvasW}×${canvasH})`);
345
+ }
346
+ const bg = options.background ?? [0, 0, 0, 0];
347
+ const out = Buffer.alloc(canvasW * canvasH * 4);
348
+ for (let i = 0; i < canvasW * canvasH; i++) {
349
+ out[i * 4] = bg[0];
350
+ out[i * 4 + 1] = bg[1];
351
+ out[i * 4 + 2] = bg[2];
352
+ out[i * 4 + 3] = bg[3];
353
+ }
354
+ const at = (r, c) => tileOriginAt(layout, r, c);
355
+ // 建筑底面原来是哪种地面 —— 用来给它垫底(见 fillDiamondSolid 的注释)
356
+ const groundByBuilding = new Map();
357
+ for (const entry of state.buildingGround ?? []) {
358
+ groundByBuilding.set(`${entry[0]},${entry[1]}`, { key: entry[4], shape: shapeOfEntry(entry) });
359
+ }
360
+ const decorAt = new Map();
361
+ for (const [key, name] of Object.entries(state.decor))
362
+ decorAt.set(key, [...(decorAt.get(key) ?? []), name]);
363
+ // 按 (r+c) 升序:远的先画,近的盖住远的
364
+ const order = [];
365
+ for (let r = 0; r < state.rows; r++) {
366
+ for (let c = 0; c < state.cols; c++)
367
+ order.push({ r, c, key: r + c });
368
+ }
369
+ order.sort((a, b) => (a.key - b.key) || (a.r - b.r));
370
+ for (const { r, c } of order) {
371
+ const family = state.cells[r]?.[c] ?? "";
372
+ if (family !== "") {
373
+ const candidates = (options.families[family] ?? [family]).filter((k) => lookup.has(k));
374
+ if (candidates.length > 0) {
375
+ // ⚠️ 变体选择必须是**确定性**的(位置 + 种子),不能 `Math.random()`:
376
+ // 界面要在不跑拼图的前提下先预览出来,用随机就永远对不上,
377
+ // 用户会以为「预览的不是成品」。界面用同一个函数各算一次。
378
+ const pick = candidates[pickVariantIndex(state.seed, r, c, candidates.length)];
379
+ const cell = lookup.get(pick);
380
+ const { x, y } = at(r, c);
381
+ blit(out, canvasW, canvasH, cell, x, y);
382
+ }
383
+ }
384
+ // 装饰插在「自己那格之后、下一格之前」:前排地块会自然盖住它的下半部
385
+ for (const name of decorAt.get(`${r},${c}`) ?? []) {
386
+ const sprite = lookup.get(name);
387
+ if (sprite === undefined)
388
+ continue;
389
+ const { x, y } = at(r, c);
390
+ blit(out, canvasW, canvasH, sprite, x, y);
391
+ }
392
+ }
393
+ // 跨格建筑:贴图是「底面格块宽度、往上长高」的立体图。
394
+ //
395
+ // 摆放口径:底面菱形中心要对到锚点格的**几何中心**,也就是世界坐标
396
+ // `(originX + (c−r)·stepX + cellWidth/2, originY + (c+r)·stepY + cellHeight/2)`。
397
+ // 上半部分自然溢出到上面那些格子上,配合 (r+c) 递增的绘制顺序形成正确遮挡。
398
+ //
399
+ // ⚠️ 贴图**不是** 2 格高:它是按底面宽度等比缩放的,高度由模板宽高比决定,
400
+ // 所以底面在贴图里的位置要按 `baseFraction` 取,不能想当然用「贴图中心」。
401
+ for (const [r, c, name] of state.buildings) {
402
+ const sprite = lookup.get(name);
403
+ if (sprite === undefined)
404
+ continue;
405
+ const at2 = at(r, c);
406
+ // 先给底面垫一块实心地面菱形,避免建筑脚下露出透明洞。
407
+ //
408
+ // 垫底按**形状**逐格画(`shapeBaseOffset` 给出包围菱形中心的偏移)。
409
+ // 曾经想当然写成 `cellW × cellH/2`,结果垫底高度是正确值的 3 倍、横向又不够,
410
+ // 洞照样露出来;后来说按 `(fw+fh)/2` 算 —— 那**只对实心矩形**成立,
411
+ // L 形会算成两倍宽,凹口也被涂上。
412
+ const groundInfo = groundByBuilding.get(`${r},${c}`);
413
+ const ground = groundInfo === undefined ? undefined : lookup.get(groundInfo.key);
414
+ const shape = groundInfo?.shape ?? [[0, 0]];
415
+ // 占格菱形的中心在哪儿 —— 建筑贴图的**底面**就落在这里。
416
+ //
417
+ // ⚠️ 不是锚点格的几何中心!2×2 的锚点在左上那格,整个占格菱形的中心
418
+ // 比它右移 `stepX/2`、下移 `stepY/2`。垫底画在锚点格中心的话,
419
+ // 整个垫底会**往左上偏半格**,建筑看着像浮在半空(实测真机就是这么露馅的)。
420
+ //
421
+ // 形状任意时用 `shapeBaseOffset` 现算(推导见它的注释)。
422
+ const off = shapeBaseOffset(shape, cellW);
423
+ const anchorCx = at2.x + cellW / 2;
424
+ const anchorCy = at2.y + cellH / 2;
425
+ const baseX = anchorCx + off.dx;
426
+ const baseY = anchorCy + off.dy;
427
+ if (groundInfo !== undefined && ground !== undefined) {
428
+ // 逐格垫底:非矩形形状(L 形)画一个大菱形会把凹口也涂上,
429
+ // 而凹口本来该透出下面的地面。矩形是特例 —— 各格菱形拼起来
430
+ // 正好等于那个大菱形,所以老行为不变。
431
+ const avg = averageColor(ground);
432
+ const cellHalfW = cellW / 4;
433
+ const cellHalfH = cellHalfW / 2;
434
+ for (const [dr, dc] of shape) {
435
+ fillDiamondSolid(out, canvasW, canvasH, anchorCx + (dc - dr) * (cellW / 4), anchorCy + (dc + dr) * (cellW / 8), cellHalfW, cellHalfH, avg, 255);
436
+ }
437
+ }
438
+ const base = typeof sprite.baseFraction === "number"
439
+ ? sprite.baseFraction * sprite.height
440
+ : sprite.height - cellH / 2;
441
+ const x = Math.round(baseX - sprite.width / 2);
442
+ const y = Math.round(baseY - base);
443
+ blit(out, canvasW, canvasH, sprite, x, y);
444
+ }
445
+ return { width: canvasW, height: canvasH, rgba: out };
446
+ }
447
+ /** 把 `src` 以 source-over 混合到 `dst` 的 (dx, dy)。 */
448
+ function blit(dst, dstW, dstH, src, dx, dy) {
449
+ for (let y = 0; y < src.height; y++) {
450
+ const ty = dy + y;
451
+ if (ty < 0 || ty >= dstH)
452
+ continue;
453
+ for (let x = 0; x < src.width; x++) {
454
+ const tx = dx + x;
455
+ if (tx < 0 || tx >= dstW)
456
+ continue;
457
+ const si = (y * src.width + x) * 4;
458
+ const sa = src.rgba[si + 3];
459
+ if (sa === 0)
460
+ continue;
461
+ const di = (ty * dstW + tx) * 4;
462
+ if (sa === 255) {
463
+ dst[di] = src.rgba[si];
464
+ dst[di + 1] = src.rgba[si + 1];
465
+ dst[di + 2] = src.rgba[si + 2];
466
+ dst[di + 3] = 255;
467
+ continue;
468
+ }
469
+ const a = sa / 255;
470
+ const inv = 1 - a;
471
+ const da = dst[di + 3] / 255;
472
+ const outA = a + da * inv;
473
+ if (outA <= 0)
474
+ continue;
475
+ dst[di] = Math.round((src.rgba[si] * a + dst[di] * da * inv) / outA);
476
+ dst[di + 1] = Math.round((src.rgba[si + 1] * a + dst[di + 1] * da * inv) / outA);
477
+ dst[di + 2] = Math.round((src.rgba[si + 2] * a + dst[di + 2] * da * inv) / outA);
478
+ dst[di + 3] = Math.round(outA * 255);
479
+ }
480
+ }
481
+ }
482
+ /** 裁掉四周全透明的边(地图留白太多时用)。返回裁掉的偏移,调用方要拿它对齐叠层。 */
483
+ export function trimTransparent(src, alphaThreshold = 8) {
484
+ let left = src.width;
485
+ let top = src.height;
486
+ let right = -1;
487
+ let bottom = -1;
488
+ for (let y = 0; y < src.height; y++) {
489
+ for (let x = 0; x < src.width; x++) {
490
+ if (src.rgba[(y * src.width + x) * 4 + 3] < alphaThreshold)
491
+ continue;
492
+ if (x < left)
493
+ left = x;
494
+ if (x > right)
495
+ right = x;
496
+ if (y < top)
497
+ top = y;
498
+ if (y > bottom)
499
+ bottom = y;
500
+ }
501
+ }
502
+ if (right < 0) {
503
+ return Object.assign(src, { left: 0, top: 0 });
504
+ }
505
+ const w = right - left + 1;
506
+ const h = bottom - top + 1;
507
+ const rgba = Buffer.alloc(w * h * 4);
508
+ for (let y = 0; y < h; y++) {
509
+ src.rgba.copy(rgba, y * w * 4, ((y + top) * src.width + left) * 4, ((y + top) * src.width + left + w) * 4);
510
+ }
511
+ // ⚠️ `left/top` 要带出去:成品是裁过的,而界面叠可点格子时用的是**未裁**坐标。
512
+ // 少了这两个值,叠层整体偏移(实测:地图看着对、但点到的格子全错一格)。
513
+ return Object.assign({ width: w, height: h, rgba }, { left, top });
514
+ }
515
+ /**
516
+ * 统计一张地图里「完全透明的洞」的像素数 —— 验收断言 S1 用它。
517
+ *
518
+ * 判据是**内部**透明:先把外部背景连通的透明区域排除,剩下的就是洞。
519
+ * 直接数 `alpha === 0` 会把外部背景也算进去,永远不为 0。
520
+ */
521
+ export function countInteriorHoles(src) {
522
+ const total = src.width * src.height;
523
+ const outside = new Uint8Array(total);
524
+ const queue = new Int32Array(total);
525
+ let head = 0;
526
+ let tail = 0;
527
+ const push = (index) => {
528
+ if (outside[index] === 0 && src.rgba[index * 4 + 3] < 8) {
529
+ outside[index] = 1;
530
+ queue[tail++] = index;
531
+ }
532
+ };
533
+ for (let x = 0; x < src.width; x++) {
534
+ push(x);
535
+ push((src.height - 1) * src.width + x);
536
+ }
537
+ for (let y = 0; y < src.height; y++) {
538
+ push(y * src.width);
539
+ push(y * src.width + src.width - 1);
540
+ }
541
+ while (head < tail) {
542
+ const index = queue[head++];
543
+ const x = index % src.width;
544
+ const y = (index - x) / src.width;
545
+ if (x > 0)
546
+ push(index - 1);
547
+ if (x < src.width - 1)
548
+ push(index + 1);
549
+ if (y > 0)
550
+ push(index - src.width);
551
+ if (y < src.height - 1)
552
+ push(index + src.width);
553
+ }
554
+ let holes = 0;
555
+ for (let i = 0; i < total; i++) {
556
+ if (outside[i] === 0 && src.rgba[i * 4 + 3] < 8)
557
+ holes++;
558
+ }
559
+ return holes;
560
+ }