dsh-game-material-master 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/maptiles.js CHANGED
@@ -32,7 +32,135 @@
32
32
  */
33
33
  import { pngSize } from "./bitmap.js";
34
34
  import { A2_SHAPES } from "./mapauto.js";
35
+ /** 整图每边的格数范围(2 格起步才有「多格」的意义,8 格已经是一整栋大建筑)。 */
36
+ export const STAMP_MIN_CELLS = 2;
37
+ /**
38
+ * 整图占格的**硬上限**:只是一道「别把 9999 传进来」的保险;真正的业务上限是
39
+ * **地图本身的大小**(一张整图最多和整张地图一样大)—— 那条在导入 / 整理时按项目尺寸校验
40
+ * (`assertStampFitsProject`)。
41
+ */
42
+ export const STAMP_MAX_CELLS = 512;
43
+ /** 整图最多几帧(每帧是一整张图,竖着排)。 */
44
+ export const STAMP_FRAMES_MAX = 16;
45
+ export const STAMP_PASS_LABELS = {
46
+ 0: "不可通过",
47
+ 1: "可通过(被人物遮挡)",
48
+ 2: "可通过(遮挡人物)"
49
+ };
50
+ /**
51
+ * 归一「整图」规格:不认识的值**抛错**(不静默夹)。
52
+ *
53
+ * 返回 `undefined` 表示「这不是整图」(没给规格),与 `parseAssetFps` 的约定一致。
54
+ */
55
+ export function parseStampSpec(raw) {
56
+ if (raw === undefined || raw === null)
57
+ return undefined;
58
+ const source = raw;
59
+ const int = (value) => {
60
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
61
+ return Number.isFinite(n) ? Math.round(n) : undefined;
62
+ };
63
+ const cols = int(source.cols);
64
+ const rows = int(source.rows);
65
+ if (cols === undefined && rows === undefined)
66
+ return undefined;
67
+ for (const [label, value] of [["宽", cols], ["高", rows]]) {
68
+ if (value === undefined || value < STAMP_MIN_CELLS || value > STAMP_MAX_CELLS) {
69
+ throw new Error(`整图的${label}要在 ${STAMP_MIN_CELLS}~${STAMP_MAX_CELLS} 格之间,收到:${String(value)}`);
70
+ }
71
+ }
72
+ const frames = int(source.frames) ?? 1;
73
+ if (frames < 1 || frames > STAMP_FRAMES_MAX) {
74
+ throw new Error(`整图的帧数要在 1~${STAMP_FRAMES_MAX} 之间,收到:${String(source.frames)}`);
75
+ }
76
+ const rawPass = Array.isArray(source.pass) ? source.pass : [];
77
+ const pass = [];
78
+ for (let i = 0; i < cols * rows; i++) {
79
+ const value = rawPass[i] === undefined ? 0 : Math.round(Number(rawPass[i]));
80
+ if (value !== 0 && value !== 1 && value !== 2) {
81
+ throw new Error(`整图的区域只有三种:0 不可通过 / 1 可通过(被人物遮挡)/ 2 可通过(遮挡人物)—— 第 ${i + 1} 格收到:${String(rawPass[i])}`);
82
+ }
83
+ pass.push(value);
84
+ }
85
+ return { cols: cols, rows: rows, frames, pass };
86
+ }
87
+ /**
88
+ * 整图在某个旋转下占几格(90° / 270° 时长宽互换)—— 旋转是顺时针。
89
+ */
90
+ /**
91
+ * 整图不能比地图大(一张整图最多占满整张地图)。
92
+ *
93
+ * 为什么不用固定的「最多 8 格」:用户要做「一张图铺满整张地图」的城门 / 大地图插画,8 格根本不够。
94
+ * 真正的上限是地图自己 —— 比地图还大的整图永远画不全,只会让人以为是 bug。
95
+ */
96
+ export function assertStampFitsProject(spec, mapCols, mapRows) {
97
+ if (spec.cols > mapCols || spec.rows > mapRows) {
98
+ throw new Error(`整图比地图还大:这张是 ${spec.cols}×${spec.rows} 格,而地图只有 ${mapCols}×${mapRows} 格。一张整图最多和整张地图一样大。`);
99
+ }
100
+ }
101
+ export function stampSpan(spec, rot) {
102
+ const turn = ((Math.round(rot) % 4) + 4) % 4;
103
+ return turn % 2 === 1 ? { cols: spec.rows, rows: spec.cols } : { cols: spec.cols, rows: spec.rows };
104
+ }
105
+ /**
106
+ * 烘焙排版:**每帧 4 个旋转,逐块竖排**。
107
+ *
108
+ * 顺序是 `frame 0 (rot 0,1,2,3) → frame 1 (rot 0,1,2,3) …`;宽度取 `max(cols, rows)` 格
109
+ * (竖着的块比横着的块窄一点,右边留透明),这样非方形整图(4×3)也能放进同一张图。
110
+ */
111
+ export function stampBlocks(spec) {
112
+ const out = [];
113
+ let y = 0;
114
+ for (let frame = 0; frame < spec.frames; frame++) {
115
+ for (let rot = 0; rot < 4; rot++) {
116
+ const span = stampSpan(spec, rot);
117
+ out.push({ frame, rot, y, cols: span.cols, rows: span.rows });
118
+ y += span.rows;
119
+ }
120
+ }
121
+ return out;
122
+ }
123
+ /**
124
+ * **源图**有多少格宽 / 高(还**没有**烘旋转)。
125
+ *
126
+ * ⚠️ 这一条是给「AI 整理」用的:`composeMapAsset` 只负责把每帧拼成 `cols × rows*frames` 的
127
+ * 源图,**旋转由导入端烘**。两边都烘过一次的话,导入会把「4 个旋转叠起来的图」当成一帧再压成
128
+ * 一格高 —— 真机就是这么翻的车(`ai/…png` 是 1024×2560,导入压成 256×64,地图上全是横条纹)。
129
+ */
130
+ export function stampSourceCells(spec) {
131
+ return { cols: spec.cols, rows: spec.rows * spec.frames };
132
+ }
133
+ /** 烘焙后的素材图有多少格宽 / 高。 */
134
+ export function stampSheetCells(spec) {
135
+ const blocks = stampBlocks(spec);
136
+ const last = blocks[blocks.length - 1];
137
+ return {
138
+ cols: Math.max(spec.cols, spec.rows),
139
+ rows: last === undefined ? spec.rows : last.y + last.rows
140
+ };
141
+ }
35
142
  export const COMMON_TILE_SIZES = [8, 16, 24, 32, 48, 64];
143
+ /** 素材自己的播放速度的合法范围(帧/秒)。下限 0.5 是「两秒走一帧」,上限 30 已经比手速快。 */
144
+ export const ASSET_FPS_MIN = 0.5;
145
+ export const ASSET_FPS_MAX = 30;
146
+ /**
147
+ * 归一素材自己的播放速度:`undefined` / `null` / `""` = **跟全局**,返回 `undefined`。
148
+ *
149
+ * 不合法的值**抛错**(不静默夹到边界)—— 这个仓库的规矩:静默改值比直接报错难查得多。
150
+ * 界面上是一个下拉框,会走到这里的只有对话面与老数据。
151
+ */
152
+ export function parseAssetFps(value) {
153
+ if (value === undefined || value === null || value === "")
154
+ return undefined;
155
+ const parsed = typeof value === "number" ? value : Number(value);
156
+ if (!Number.isFinite(parsed))
157
+ throw new Error(`播放速度得是数字(帧/秒),收到:${String(value)}`);
158
+ if (parsed < ASSET_FPS_MIN || parsed > ASSET_FPS_MAX) {
159
+ throw new Error(`播放速度要在 ${ASSET_FPS_MIN}~${ASSET_FPS_MAX} 帧/秒之间,收到:${parsed}`);
160
+ }
161
+ // 两位小数够了(0.5 帧/秒 = 两秒一帧)。
162
+ return Math.round(parsed * 100) / 100;
163
+ }
36
164
  export function tileIdFor(rect) {
37
165
  return `t${rect.x}_${rect.y}`;
38
166
  }
@@ -98,10 +226,27 @@ export function detectLayout(imageWidth, imageHeight) {
98
226
  * 只取**完整的块**:横向 / 纵向不足一个块的像素被裁掉(`Math.floor`),
99
227
  * 因为半个块既挑不出象限也对不上邻接。A2 还要求格尺寸是偶数(小格 = 块 / 2)。
100
228
  */
101
- export function layoutFor(shape, cell, imageWidth, imageHeight) {
229
+ export function layoutFor(shape, cell, imageWidth, imageHeight,
230
+ /** 仅 stamp:占几格 / 几帧(决定切多少块)。 */
231
+ stamp) {
102
232
  if (!Number.isInteger(cell.width) || !Number.isInteger(cell.height) || cell.width < 1 || cell.height < 1) {
103
233
  throw new Error(`图块尺寸必须是正整数,收到 ${cell.width}×${cell.height}`);
104
234
  }
235
+ if (shape === "stamp") {
236
+ // 整图:切分数由规格决定(帧 × 4 旋转 × 占格),具体块阵见 `buildTiles`。
237
+ const spec = stamp;
238
+ if (spec === undefined)
239
+ throw new Error("整图素材缺规格(占几格 / 几帧)——请重新导入这张图。");
240
+ const size = stampSheetCells(spec);
241
+ return {
242
+ cell: { width: cell.width, height: cell.height },
243
+ shape,
244
+ cols: size.cols,
245
+ rows: size.rows,
246
+ count: size.cols * size.rows,
247
+ reason: `整图 ${spec.cols}×${spec.rows} 格、${spec.frames} 帧(含 4 个旋转)`
248
+ };
249
+ }
105
250
  if (shape === "a2quad") {
106
251
  if (cell.width % 2 !== 0 || cell.height % 2 !== 0) {
107
252
  throw new Error(`A2 拼块要求逻辑块尺寸是偶数(小格 = 逻辑块 / 2),收到 ${cell.width}×${cell.height}`);
@@ -186,6 +331,27 @@ export function buildTiles(input, previous = []) {
186
331
  tile.frame = frame;
187
332
  return tile;
188
333
  };
334
+ if (shape === "stamp") {
335
+ /**
336
+ * 整图:块 = 帧 × 4 个旋转 × 占格。每块都带 `stamp` 元数据,
337
+ * 渲染时按「第几帧、转几档、第几行第几列」把一张图摆到 N×M 个格子上。
338
+ * 几何全部来自 `stampBlocks`(与烘焙 `bakeStampSheet` 同一份排版)。
339
+ */
340
+ const spec = input.stamp;
341
+ if (spec === undefined)
342
+ throw new Error("整图素材缺规格(占几格 / 几帧)——请重新导入这张图。");
343
+ const tiles = [];
344
+ for (const block of stampBlocks(spec)) {
345
+ for (let r = 0; r < block.rows; r++) {
346
+ for (let c = 0; c < block.cols; c++) {
347
+ const tile = tileOf({ x: c * cell.width, y: (block.y + r) * cell.height, width: cell.width, height: cell.height }, undefined, undefined, block.frame);
348
+ tile.stamp = { frame: block.frame, rot: block.rot, r, c };
349
+ tiles.push(tile);
350
+ }
351
+ }
352
+ }
353
+ return tiles;
354
+ }
189
355
  if (shape === "a2quad") {
190
356
  if (cell.width % 2 !== 0 || cell.height % 2 !== 0) {
191
357
  throw new Error(`A2 拼块要求逻辑块尺寸是偶数(小格 = 逻辑块 / 2),收到 ${cell.width}×${cell.height}`);
@@ -251,3 +417,850 @@ export function cropTile(source, rect) {
251
417
  }
252
418
  return { width, height, rgba };
253
419
  }
420
+ export const ASSET_LOOPS = ["forward", "reverse", "pingpong"];
421
+ /** 归一循环方式:不认识的值**抛错**(不静默回落)。留空 = `forward`。 */
422
+ export function parseAssetLoop(value) {
423
+ if (value === undefined || value === null || value === "")
424
+ return "forward";
425
+ const text = String(value);
426
+ if (!ASSET_LOOPS.includes(text)) {
427
+ throw new Error(`未知的循环方式:${text}(可选 ${ASSET_LOOPS.join(" / ")})`);
428
+ }
429
+ return text;
430
+ }
431
+ /**
432
+ * 把「一遍」的帧序展开成**实际循环**的帧序。
433
+ *
434
+ * 来回播放用的是 `[0,1,2,3,2,1]`(首尾各留一次,中间来回),2 帧时就是原样 ——
435
+ * 那是对的:两帧来回和正放看起来一样,循环点也不会跳。
436
+ */
437
+ export function applyLoop(frames, loop = "forward") {
438
+ if (frames.length <= 1)
439
+ return [...frames];
440
+ if (loop === "reverse")
441
+ return [...frames].reverse();
442
+ if (loop === "pingpong")
443
+ return [...frames, ...frames.slice(1, -1).reverse()];
444
+ return [...frames];
445
+ }
446
+ // ── 自动裁边:模型爱在四周留一圈白边 ───────────────────────────────────────
447
+ /** 算「白/浅灰画布边」用的亮度下界(0~255)。 */
448
+ const LIGHT_BAND = 170;
449
+ /**
450
+ * 裁掉四周**近乎纯色**的边框(模型经常无视「四边不留白」)。
451
+ *
452
+ * 判据是「这一行 / 这一列的像素彼此几乎一样(偏差 < `tolerance`)」,从四条边往里推进,
453
+ * 遇到第一行有内容(颜色起伏)就停。
454
+ *
455
+ * ⚠️ **宁可少裁,也不能把画面裁坏** —— 这个模块的素材是「一格内容」,四周本来就该有画面,
456
+ * 裁错了就是内容被裁掉。所以四道保险缺一不可:
457
+ * ① 只裁**浅色**带(平均亮度 ≥ `LIGHT_BAND`):模型留的是白 / 浅灰画布边;深色平底
458
+ * 往往是道具自己的背景,属于内容;
459
+ * ② 每边最多裁 `maxRatio`(默认 6%)—— 真边框就是一圈薄边,超过 6% 更可能是背景;
460
+ * ③ 裁完至少留 `minKeep`(默认 60%)的宽高;
461
+ * ④ 四条边**都得**有浅色带,而且**里面必须真的有内容**(有 ≥2% 的像素与边框色明显不同)。
462
+ * 整张图是一个纯色(测试夹具 / 单色砖)时因此一个像素都不动。
463
+ */
464
+ export function trimUniformBorder(frame, options = {}) {
465
+ const tolerance = Math.max(1, options.tolerance ?? 12);
466
+ const maxRatio = Math.min(0.2, Math.max(0.01, options.maxRatio ?? 0.06));
467
+ const minKeep = Math.min(0.95, Math.max(0.5, options.minKeep ?? 0.6));
468
+ const unchanged = { bitmap: frame, left: 0, top: 0, right: 0, bottom: 0 };
469
+ if (frame.width < 4 || frame.height < 4)
470
+ return unchanged;
471
+ const at = (x, y) => {
472
+ const offset = (y * frame.width + x) * 4;
473
+ return frame.rgba.subarray(offset, offset + 4);
474
+ };
475
+ /** 这一整行(或列)是不是「一个颜色」。 */
476
+ const rowUniform = (y, from, to) => {
477
+ const first = at(from, y);
478
+ for (let x = from; x < to; x++) {
479
+ const pixel = at(x, y);
480
+ if (Math.abs(pixel[0] - first[0]) > tolerance || Math.abs(pixel[1] - first[1]) > tolerance || Math.abs(pixel[2] - first[2]) > tolerance)
481
+ return false;
482
+ }
483
+ return true;
484
+ };
485
+ const colUniform = (x, from, to) => {
486
+ const first = at(x, from);
487
+ for (let y = from; y < to; y++) {
488
+ const pixel = at(x, y);
489
+ if (Math.abs(pixel[0] - first[0]) > tolerance || Math.abs(pixel[1] - first[1]) > tolerance || Math.abs(pixel[2] - first[2]) > tolerance)
490
+ return false;
491
+ }
492
+ return true;
493
+ };
494
+ // 先量出纯色带「到底有多宽」(上限 45%,防病态图),再决定它算不算画布边。
495
+ const scanLimitX = Math.floor(frame.width * 0.45);
496
+ const scanLimitY = Math.floor(frame.height * 0.45);
497
+ let left = 0;
498
+ while (left < scanLimitX && colUniform(left, 0, frame.height))
499
+ left++;
500
+ let right = 0;
501
+ while (right < scanLimitX && colUniform(frame.width - 1 - right, 0, frame.height))
502
+ right++;
503
+ let top = 0;
504
+ while (top < scanLimitY && rowUniform(top, 0, frame.width))
505
+ top++;
506
+ let bottom = 0;
507
+ while (bottom < scanLimitY && rowUniform(frame.height - 1 - bottom, 0, frame.width))
508
+ bottom++;
509
+ // ④a 四条边都得有浅色带;有一条没裁说明这条边是满的(图本来就是铺满的)。
510
+ if (left === 0 || right === 0 || top === 0 || bottom === 0)
511
+ return unchanged;
512
+ /**
513
+ * ② 带子太宽就不当画布边:真边框是一圈薄边(几个百分点)。宽过 `maxRatio` 的
514
+ * 纯色带更可能是**背景**(道具画在平底上的那种),裁掉就把内容裁了 —— 宁可不动。
515
+ */
516
+ if (left > frame.width * maxRatio || right > frame.width * maxRatio || top > frame.height * maxRatio || bottom > frame.height * maxRatio)
517
+ return unchanged;
518
+ /**
519
+ * 再多裁 `inset`(1%):模型描的边框常有一两像素的柔化过渡,纯色判定会在过渡处停下,
520
+ * 残留一圈**浅色细边** —— 缩到格子上就是每块素材边上一条白线。只在「确实有边框」时才多
521
+ * 吃这一点(不会伤到正常素材),并且仍然受下面的最小保留量约束。
522
+ */
523
+ {
524
+ const inset = Math.max(1, Math.round(Math.min(frame.width, frame.height) * 0.01));
525
+ const capX = Math.floor(frame.width * maxRatio);
526
+ const capY = Math.floor(frame.height * maxRatio);
527
+ left = Math.min(left + inset, capX);
528
+ right = Math.min(right + inset, capX);
529
+ top = Math.min(top + inset, capY);
530
+ bottom = Math.min(bottom + inset, capY);
531
+ }
532
+ // ③ 至少留 60%。
533
+ const width = frame.width - left - right;
534
+ const height = frame.height - top - bottom;
535
+ if (width < frame.width * minKeep || height < frame.height * minKeep)
536
+ return unchanged;
537
+ if (width < 2 || height < 2)
538
+ return unchanged;
539
+ // ① 边框得是浅色(白 / 浅灰画布边),深色平底算内容。
540
+ const band = at(Math.floor(left / 2), Math.floor(top / 2));
541
+ const luminance = (band[0] + band[1] + band[2]) / 3;
542
+ if (luminance < 170)
543
+ return unchanged;
544
+ // ④b 里面必须真的有内容:至少 2% 的像素与边框色明显不同。
545
+ let different = 0;
546
+ const total = width * height;
547
+ for (let y = 0; y < height; y += 2) {
548
+ for (let x = 0; x < width; x += 2) {
549
+ const pixel = at(left + x, top + y);
550
+ if (Math.abs(pixel[0] - band[0]) > tolerance * 2 || Math.abs(pixel[1] - band[1]) > tolerance * 2 || Math.abs(pixel[2] - band[2]) > tolerance * 2)
551
+ different++;
552
+ }
553
+ }
554
+ if (different < Math.max(4, total * 0.02 * 0.25))
555
+ return unchanged;
556
+ const rgba = Buffer.alloc(width * height * 4);
557
+ for (let y = 0; y < height; y++) {
558
+ const from = ((top + y) * frame.width + left) * 4;
559
+ frame.rgba.copy(rgba, y * width * 4, from, from + width * 4);
560
+ }
561
+ return { bitmap: { width, height, rgba }, left, top, right, bottom };
562
+ }
563
+ export const ASSET_CLARITIES = ["smooth", "sharp", "crisp"];
564
+ /** 归一清晰度:不认识的值**抛错**(不静默回落到某个默认值)。留空 = `smooth`。 */
565
+ export function parseClarity(value) {
566
+ if (value === undefined || value === null || value === "")
567
+ return "smooth";
568
+ const text = String(value);
569
+ if (!ASSET_CLARITIES.includes(text)) {
570
+ throw new Error(`未知的清晰度:${text}(可选 ${ASSET_CLARITIES.join(" / ")})`);
571
+ }
572
+ return text;
573
+ }
574
+ /**
575
+ * 素材图最多保留多少倍分辨率(相对地图格子)。`composeMapAsset` 把大图先留到
576
+ * `cell × 这个倍数`,等用户在「新增素材」里选好清晰度再缩到格子上 —— 留太多没意义
577
+ * (32px 一格看不出 256px 与 128px 的区别),留 1 倍就等于没得选。
578
+ */
579
+ export const MAX_ASSET_SCALE = 4;
580
+ /** 归一「素材图相对格子的倍数」:1~8 的整数,留空 = 1。越界抛错。 */
581
+ export function parseAssetScale(value) {
582
+ if (value === undefined || value === null || value === "")
583
+ return 1;
584
+ const parsed = typeof value === "number" ? value : Number(value);
585
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 1 || parsed > 8) {
586
+ throw new Error(`素材图的倍数得是 1~8 的整数,收到:${String(value)}`);
587
+ }
588
+ return parsed;
589
+ }
590
+ /** 一次重采样的原料:源图 + 目标尺寸 + 方式。 */
591
+ function nearestResample(frame, width, height) {
592
+ const rgba = Buffer.alloc(width * height * 4);
593
+ for (let y = 0; y < height; y++) {
594
+ const sy = Math.min(frame.height - 1, Math.floor((y * frame.height) / height));
595
+ for (let x = 0; x < width; x++) {
596
+ const sx = Math.min(frame.width - 1, Math.floor((x * frame.width) / width));
597
+ const from = (sy * frame.width + sx) * 4;
598
+ const to = (y * width + x) * 4;
599
+ rgba[to] = frame.rgba[from];
600
+ rgba[to + 1] = frame.rgba[from + 1];
601
+ rgba[to + 2] = frame.rgba[from + 2];
602
+ rgba[to + 3] = frame.rgba[from + 3];
603
+ }
604
+ }
605
+ return { width, height, rgba };
606
+ }
607
+ /** 面积平均(盒式)重采样:每个目标像素 = 它覆盖到的源像素的加权平均。 */
608
+ function boxResample(frame, width, height) {
609
+ const rgba = Buffer.alloc(width * height * 4);
610
+ for (let y = 0; y < height; y++) {
611
+ const sy0 = (y * frame.height) / height;
612
+ const sy1 = ((y + 1) * frame.height) / height;
613
+ const yStart = Math.max(0, Math.floor(sy0));
614
+ const yEnd = Math.min(frame.height, Math.max(yStart + 1, Math.ceil(sy1)));
615
+ for (let x = 0; x < width; x++) {
616
+ const sx0 = (x * frame.width) / width;
617
+ const sx1 = ((x + 1) * frame.width) / width;
618
+ const xStart = Math.max(0, Math.floor(sx0));
619
+ const xEnd = Math.min(frame.width, Math.max(xStart + 1, Math.ceil(sx1)));
620
+ /**
621
+ * alpha 要**预乘**再平均:不预乘的话透明边缘(抠过像的素材)会把黑色带进来,
622
+ * 缩小之后一圈发黑 —— 这也是「看起来不干净」的一个来源。
623
+ */
624
+ let sumA = 0;
625
+ let sumR = 0;
626
+ let sumG = 0;
627
+ let sumB = 0;
628
+ let count = 0;
629
+ for (let sy = yStart; sy < yEnd; sy++) {
630
+ for (let sx = xStart; sx < xEnd; sx++) {
631
+ const offset = (sy * frame.width + sx) * 4;
632
+ const alpha = frame.rgba[offset + 3] / 255;
633
+ sumR += frame.rgba[offset] * alpha;
634
+ sumG += frame.rgba[offset + 1] * alpha;
635
+ sumB += frame.rgba[offset + 2] * alpha;
636
+ sumA += frame.rgba[offset + 3];
637
+ count++;
638
+ }
639
+ }
640
+ const to = (y * width + x) * 4;
641
+ if (count === 0)
642
+ continue;
643
+ const averageAlpha = sumA / count;
644
+ const weight = (averageAlpha / 255) * count;
645
+ rgba[to] = weight <= 0 ? 0 : Math.min(255, Math.round(sumR / weight));
646
+ rgba[to + 1] = weight <= 0 ? 0 : Math.min(255, Math.round(sumG / weight));
647
+ rgba[to + 2] = weight <= 0 ? 0 : Math.min(255, Math.round(sumB / weight));
648
+ rgba[to + 3] = Math.min(255, Math.round(averageAlpha));
649
+ }
650
+ }
651
+ return { width, height, rgba };
652
+ }
653
+ /** 3×3 盒式模糊(只给锐化当底稿用)。 */
654
+ function blur3x3(frame) {
655
+ const rgba = Buffer.alloc(frame.width * frame.height * 4);
656
+ for (let y = 0; y < frame.height; y++) {
657
+ for (let x = 0; x < frame.width; x++) {
658
+ let r = 0;
659
+ let g = 0;
660
+ let b = 0;
661
+ let a = 0;
662
+ let count = 0;
663
+ for (let dy = -1; dy <= 1; dy++) {
664
+ for (let dx = -1; dx <= 1; dx++) {
665
+ const sx = Math.min(frame.width - 1, Math.max(0, x + dx));
666
+ const sy = Math.min(frame.height - 1, Math.max(0, y + dy));
667
+ const offset = (sy * frame.width + sx) * 4;
668
+ r += frame.rgba[offset];
669
+ g += frame.rgba[offset + 1];
670
+ b += frame.rgba[offset + 2];
671
+ a += frame.rgba[offset + 3];
672
+ count++;
673
+ }
674
+ }
675
+ const to = (y * frame.width + x) * 4;
676
+ rgba[to] = Math.round(r / count);
677
+ rgba[to + 1] = Math.round(g / count);
678
+ rgba[to + 2] = Math.round(b / count);
679
+ rgba[to + 3] = Math.round(a / count);
680
+ }
681
+ }
682
+ return { width: frame.width, height: frame.height, rgba };
683
+ }
684
+ /** 锐化强度(`crisp` 用):0.75 是「看得出来更利落、又不会出白边」的档。 */
685
+ const SHARPEN_AMOUNT = 0.75;
686
+ /**
687
+ * 缩放到目标尺寸,按清晰度选算法。
688
+ *
689
+ * `sharp` 与原来源行为**逐像素一致**(最近邻);`smooth` / `crisp` 只在**缩小**时有意义
690
+ * (放大时退回最近邻 —— 插值放大只会更糊)。
691
+ */
692
+ export function resampleToSize(frame, width, height, clarity = "smooth") {
693
+ const targetWidth = Math.max(1, Math.floor(width));
694
+ const targetHeight = Math.max(1, Math.floor(height));
695
+ if (targetWidth === frame.width && targetHeight === frame.height)
696
+ return { width: targetWidth, height: targetHeight, rgba: Buffer.from(frame.rgba) };
697
+ const shrinking = targetWidth < frame.width || targetHeight < frame.height;
698
+ if (clarity === "sharp" || !shrinking)
699
+ return nearestResample(frame, targetWidth, targetHeight);
700
+ const smoothed = boxResample(frame, targetWidth, targetHeight);
701
+ if (clarity === "smooth")
702
+ return smoothed;
703
+ // crisp:平滑之后再按「原值 - 模糊」补一点边缘。
704
+ const blurred = blur3x3(smoothed);
705
+ const rgba = Buffer.from(smoothed.rgba);
706
+ for (let offset = 0; offset < rgba.length; offset += 4) {
707
+ for (let channel = 0; channel < 3; channel++) {
708
+ const value = smoothed.rgba[offset + channel];
709
+ const soft = blurred.rgba[offset + channel];
710
+ rgba[offset + channel] = Math.min(255, Math.max(0, Math.round(value + SHARPEN_AMOUNT * (value - soft))));
711
+ }
712
+ }
713
+ return { width: targetWidth, height: targetHeight, rgba };
714
+ }
715
+ // ── AI 生成素材:把模型吐出来的一批帧整理成一张能直接导入的素材图 ──────────
716
+ /**
717
+ * 等比裁到目标宽高比、再**最近邻**缩放到 `width × height`。
718
+ *
719
+ * 为什么先裁再缩:地图上的图块是**按原尺寸**画在格子左上角的(宿主 `maprender`
720
+ * 出的计划、界面按 `rect.width/height` `drawImage`),所以一格素材的像素尺寸必须
721
+ * **正好等于地图网格**,否则会压到邻居格上。模型给的是 1024×1024 这类大图、也
722
+ * 可能不是正方形,直接拉成网格尺寸会把内容压扁 —— 所以取中心等比裁切,再缩到
723
+ * 目标尺寸。
724
+ *
725
+ * 为什么用最近邻而不是双线性:这是像素画工作流,硬边是内容的一部分;插值会把
726
+ * 色块边缘糊成渐变(`rigpose` 那边的双线性采样是给骨骼变形用的,两件事)。
727
+ */
728
+ export function fitFrameToCell(frame, cell, clarity = "sharp") {
729
+ const width = Math.max(1, Math.floor(cell.width));
730
+ const height = Math.max(1, Math.floor(cell.height));
731
+ const targetRatio = width / height;
732
+ const sourceRatio = frame.width / frame.height;
733
+ // 按目标比例取中心那块(源图更宽 → 裁宽;更高 → 裁高)。
734
+ let cropWidth;
735
+ let cropHeight;
736
+ if (sourceRatio > targetRatio) {
737
+ cropHeight = frame.height;
738
+ cropWidth = Math.max(1, Math.min(frame.width, Math.round(frame.height * targetRatio)));
739
+ }
740
+ else {
741
+ cropWidth = frame.width;
742
+ cropHeight = Math.max(1, Math.min(frame.height, Math.round(frame.width / targetRatio)));
743
+ }
744
+ const offsetX = Math.floor((frame.width - cropWidth) / 2);
745
+ const offsetY = Math.floor((frame.height - cropHeight) / 2);
746
+ // 先裁出中心那块,再按清晰度缩到目标尺寸(`sharp` = 最近邻,与原来逐像素一致)。
747
+ const cropped = cropTile(frame, { x: offsetX, y: offsetY, width: cropWidth, height: cropHeight });
748
+ return resampleToSize(cropped, width, height, clarity);
749
+ }
750
+ /**
751
+ * 每帧先 `fitFrameToCell`,再**自上而下堆成一列**。
752
+ *
753
+ * 为什么是「一列 N 行」而不是「一行 N 列」:地图编辑器的翻页图(`animRows`)约定
754
+ * **同一列的每一行是同一块的一帧** —— 调色板只取第 0 帧那一条、帧由宿主按全局
755
+ * 帧号现推。横排会被当成 N 个互不相干的图块,画下去只是一块静止的图,而且不报错。
756
+ */
757
+ export function stackFrames(frames, cell, clarity = "sharp") {
758
+ if (frames.length === 0)
759
+ throw new Error("没有可整理的帧");
760
+ const width = Math.max(1, Math.floor(cell.width));
761
+ const height = Math.max(1, Math.floor(cell.height));
762
+ const fitted = frames.map((frame) => fitFrameToCell(frame, { width, height }, clarity));
763
+ const rgba = Buffer.alloc(width * height * frames.length * 4);
764
+ for (let index = 0; index < fitted.length; index++) {
765
+ fitted[index].rgba.copy(rgba, index * height * width * 4);
766
+ }
767
+ return { width, height: height * frames.length, rgba };
768
+ }
769
+ // ── 按素材形态规整:普通 / 整格 / 拼块 ─────────────────────────────────────
770
+ /**
771
+ * **非等比**最近邻缩放到指定宽高。
772
+ *
773
+ * 与 `fitFrameToCell` 的区别:那个是「中心等比裁切再缩」(一格内容 → 一格),
774
+ * 这个是「整张图映射到目标矩形」(一张排布图 → 一张排布图)。
775
+ *
776
+ * 为什么整格 / 拼块必须**拉伸**而不是裁:模型画的是「4 列 × 4 行」「N 列 × 5 行」
777
+ * 的排布,裁掉多余部分等于把某些块切掉,块与块的对应关系就没了;拉伸至少保证
778
+ * **每块落在它该落的位置上**(内容会随源图比例轻微变形,但结构是对的)。提示词里
779
+ * 会要求模型按目标比例出图,比例对上了拉伸就是恒等变换。
780
+ */
781
+ export function stretchToSize(frame, width, height) {
782
+ const targetWidth = Math.max(1, Math.floor(width));
783
+ const targetHeight = Math.max(1, Math.floor(height));
784
+ const rgba = Buffer.alloc(targetWidth * targetHeight * 4);
785
+ for (let y = 0; y < targetHeight; y++) {
786
+ const sy = Math.min(frame.height - 1, Math.floor((y * frame.height) / targetHeight));
787
+ for (let x = 0; x < targetWidth; x++) {
788
+ const sx = Math.min(frame.width - 1, Math.floor((x * frame.width) / targetWidth));
789
+ const from = (sy * frame.width + sx) * 4;
790
+ const to = (y * targetWidth + x) * 4;
791
+ rgba[to] = frame.rgba[from];
792
+ rgba[to + 1] = frame.rgba[from + 1];
793
+ rgba[to + 2] = frame.rgba[from + 2];
794
+ rgba[to + 3] = frame.rgba[from + 3];
795
+ }
796
+ }
797
+ return { width: targetWidth, height: targetHeight, rgba };
798
+ }
799
+ /** 整格自动连接的块数(4×4 = 16 种接法,位序 N=1/E=2/S=4/W=8,掩码 = 行优先下标)。 */
800
+ export const CORNER16_BLOCKS = 4;
801
+ /** 拼块的形状行数(照 AsLib:上到下 5 种接法,最后一行是满格)。 */
802
+ export const A2_ROWS = A2_SHAPES;
803
+ /**
804
+ * 「收口」的厚度:按被收口的那块图的大小算(32px 的一格 → 4px;拼块的 16px 小格 → 2px)。
805
+ * 太薄看不出来,太厚会把内容吃掉。
806
+ */
807
+ export function capThicknessFor(size) {
808
+ return Math.min(6, Math.max(2, Math.round(size / 8)));
809
+ }
810
+ /** 把某个像素按系数压暗(alpha 不动:收口不该改变图像的形状)。 */
811
+ function darkenPixel(rgba, offset, factor) {
812
+ for (let channel = 0; channel < 3; channel++) {
813
+ const value = Math.round(rgba[offset + channel] * factor);
814
+ rgba[offset + channel] = value < 0 ? 0 : value > 255 ? 255 : value;
815
+ }
816
+ }
817
+ /**
818
+ * 在**一块图的某条边**上压一道「收口」:最外 1px 最深,往内线性回到原色。
819
+ *
820
+ * 为什么需要它:「断」的那一边是墙头 / 拐角 / 材质的边界,得能看出来;而**不能用
821
+ * 模型画**(见 `corner16SheetFromTile` 的注释)—— 收口是几何,交给代码做才一致。
822
+ */
823
+ export function shadeSide(bitmap, side, thickness = capThicknessFor(Math.min(bitmap.width, bitmap.height))) {
824
+ const t = Math.max(1, Math.min(thickness, Math.min(bitmap.width, bitmap.height)));
825
+ const horizontal = side === "N" || side === "S";
826
+ const length = horizontal ? bitmap.width : bitmap.height;
827
+ for (let depth = 0; depth < t; depth++) {
828
+ // 最外一圈 0.35,往内线性回到 1.0(看起来像一条压边 + 内侧投影)。
829
+ const factor = depth === 0 ? 0.35 : 0.35 + ((1 - 0.35) * depth) / t;
830
+ for (let i = 0; i < length; i++) {
831
+ const x = horizontal ? i : side === "W" ? depth : bitmap.width - 1 - depth;
832
+ const y = horizontal ? (side === "N" ? depth : bitmap.height - 1 - depth) : i;
833
+ darkenPixel(bitmap.rgba, (y * bitmap.width + x) * 4, factor);
834
+ }
835
+ }
836
+ }
837
+ /**
838
+ * 在**一角**压一块 `size × size` 的收口(越靠外角越深)。
839
+ *
840
+ * 只有拼块的形状 3 用得上:它「上面和左边都接、左上方对角不接」—— 那个凹角要在
841
+ * 象限的外角上露出一点缺口,否则形状 3 和满格(形状 4)就完全一样了。
842
+ */
843
+ export function shadeCorner(bitmap, corner, size) {
844
+ const t = Math.max(1, Math.min(size, Math.min(bitmap.width, bitmap.height)));
845
+ for (let dy = 0; dy < t; dy++) {
846
+ for (let dx = 0; dx < t; dx++) {
847
+ const depth = Math.max(dx, dy);
848
+ const factor = depth === 0 ? 0.35 : 0.35 + ((1 - 0.35) * depth) / t;
849
+ const x = corner === "NW" || corner === "SW" ? dx : bitmap.width - 1 - dx;
850
+ const y = corner === "NW" || corner === "NE" ? dy : bitmap.height - 1 - dy;
851
+ darkenPixel(bitmap.rgba, (y * bitmap.width + x) * 4, factor);
852
+ }
853
+ }
854
+ }
855
+ /** 把一张小图画到另一张图上(左上角对齐)。 */
856
+ function blitInto(source, target, atX, atY) {
857
+ for (let y = 0; y < source.height; y++) {
858
+ const from = y * source.width * 4;
859
+ const to = ((atY + y) * target.width + atX) * 4;
860
+ source.rgba.copy(target.rgba, to, from, from + source.width * 4);
861
+ }
862
+ }
863
+ /**
864
+ * 整格(`corner16`):由**一块无缝墙砖**拼出 4×4 = 16 格,每格只在「断」的那几边加收口。
865
+ *
866
+ * ⚠️ 这里**不再让模型画 4×4**,原因是实测出来的:一排墙在地图上会用到**三块不同的图块**
867
+ * (只连右 / 左右都连 / 只连左 → 掩码 2 / 10 / 8 → 素材里的三个不同格子),而模型画出来的
868
+ * 16 个格子是**各自独立**的(霓虹灯带、板缝各自偏几十像素),拼到一起边缘差 201、块内相邻
869
+ * 列才差 58 —— 那就是用户看到的「接缝」。
870
+ *
871
+ * 正确做法是**几何交给代码**:模型只负责画**一块**无缝的墙面(内容),16 种接法由这里
872
+ * 从同一块砖的像素拼出来 —— 凡是「连」的边都是同一张砖的边缘,接缝等于砖自身的环绕缝
873
+ * (最好的可能值);「断」的边由 `shadeSide` 加收口,所以墙头 / 拐角仍然看得见。
874
+ */
875
+ /**
876
+ * 顺时针转 90°:**竖着走的那一段墙要用它**。
877
+ *
878
+ * 一张砖墙贴图的砖缝是横向的;墙往南北走时,砖缝也得跟着竖过来 —— 否则竖着的那一段看着
879
+ * 就是「同一张图硬贴上去」,花纹接不上(用户原话:「围墙竖过来的部分花纹就没拼了」)。
880
+ */
881
+ export function rotate90(frame, clockwise = true) {
882
+ const width = frame.height;
883
+ const height = frame.width;
884
+ const rgba = Buffer.alloc(width * height * 4);
885
+ for (let y = 0; y < height; y++) {
886
+ for (let x = 0; x < width; x++) {
887
+ // 顺时针:新 (x,y) 取原 (y, H-1-x)... 用行列替换写清楚更不容易错。
888
+ const sx = clockwise ? y : frame.width - 1 - y;
889
+ const sy = clockwise ? frame.height - 1 - x : x;
890
+ const from = (sy * frame.width + sx) * 4;
891
+ const to = (y * width + x) * 4;
892
+ frame.rgba.copy(rgba, to, from, from + 4);
893
+ }
894
+ }
895
+ return { width, height, rgba };
896
+ }
897
+ /**
898
+ * **烘焙整图**:把「每帧一整张」的源图排成 `4 旋转 × 帧` 的素材图。
899
+ *
900
+ * 为什么把 4 个旋转烘进去、而不是让渲染器转:地图的绘制契约是「一格一次
901
+ * `drawImage(rect → 目标格)`」,宿主的光栅化器(导出 PNG)也走同一条。旋转若发生在
902
+ * 绘制时,客户端与宿主两边都要各写一套旋转几何,还要改黄金对照——烘进图里则只多占
903
+ * 3 倍的图高,其余一行不动(调色板、legend、导出、客户端全都不用知道旋转这回事)。
904
+ *
905
+ * 源图要求:`cols × (rows × frames)` 格,帧自上而下排(与翻页图同一个约定);
906
+ * 尺寸不足 / 多出来的部分由 `resampleToSize` 的调用方负责(本函数按目标块切)。
907
+ */
908
+ export function bakeStampSheet(source, spec, cell, clarity = "sharp") {
909
+ const cellW = Math.max(1, Math.floor(cell.width));
910
+ const cellH = Math.max(1, Math.floor(cell.height));
911
+ const frameW = spec.cols * cellW;
912
+ const frameH = spec.rows * cellH;
913
+ const size = stampSheetCells(spec);
914
+ const sheet = { width: size.cols * cellW, height: size.rows * cellH, rgba: Buffer.alloc(size.cols * cellW * size.rows * cellH * 4) };
915
+ for (let frame = 0; frame < spec.frames; frame++) {
916
+ // 逐帧取源图(源图可能刚被缩到目标尺寸,这里按格切,避免整图重采样两次)。
917
+ const frameBitmap = { width: frameW, height: frameH, rgba: Buffer.alloc(frameW * frameH * 4) };
918
+ for (let y = 0; y < frameH; y++) {
919
+ const fromY = frame * frameH + y;
920
+ if (fromY >= source.height)
921
+ break;
922
+ source.rgba.copy(frameBitmap.rgba, y * frameW * 4, (fromY * source.width) * 4, (fromY * source.width + Math.min(frameW, source.width)) * 4);
923
+ }
924
+ for (let rot = 0; rot < 4; rot++) {
925
+ let turned = frameBitmap;
926
+ for (let step = 0; step < rot; step++)
927
+ turned = rotate90(turned, true);
928
+ const block = stampBlocks(spec).find((item) => item.frame === frame && item.rot === rot);
929
+ if (block === undefined)
930
+ continue;
931
+ blitInto(turned, sheet, 0, block.y * cellH);
932
+ }
933
+ }
934
+ void clarity;
935
+ return sheet;
936
+ }
937
+ /**
938
+ * 「每帧一整张」的几张图 → 一张**源图**(`cols × rows*frames` 格,**不烘旋转**)。
939
+ *
940
+ * 分工:这里只负责「把每帧缩成一整块、竖着排好」;**4 个旋转由导入端烘**(`stampTilesetImage`)。
941
+ * 两边都烘的话,导入会把「4 个旋转叠起来的那张图」当成一帧压扁 —— 真机踩过。
942
+ */
943
+ export function composeStampSource(frames, spec, cell, clarity = "smooth") {
944
+ if (frames.length === 0)
945
+ throw new Error("没有可整理的帧");
946
+ return stackFrames(frames, { width: spec.cols * Math.max(1, Math.floor(cell.width)), height: spec.rows * Math.max(1, Math.floor(cell.height)) }, clarity);
947
+ }
948
+ /**
949
+ * 抠掉绿幕背景(**只给整图用**):把「纯绿背景」变成透明。
950
+ *
951
+ * 为什么整图要抠、别的形态不用:普通 / 整格 / 拼块都是**铺满一格**的材质(背景就是内容),
952
+ * 而整图是「立在格子上的物件」—— 绿幕是模型为了让人看清而加的假背景,留着就会在地图上
953
+ * 出现一块绿色方框;而且它会让整图**占满** N×M 格,连本来该空着的角落也涂绿。
954
+ *
955
+ * 判定用 `chroma.keyGreen` 的 `backgroundFraction`:
956
+ * - `< 0.02`:几乎没抠到东西(模型没画绿幕),**原样返回**并说明;
957
+ * - `> 0.98`:整张都被判成背景(画面里没有主体),同样原样返回 —— 不能把图抠成空白。
958
+ */
959
+ /**
960
+ * 整图抠像的参数:**比角色抠像严格得多**,而且**关掉空间分割**。
961
+ *
962
+ * 真机教训(用户那张城门):模型的「背景」其实是一片草地 + 泥土路,绿的优势值只有 26~59;
963
+ * 角色的默认参数(`keyLow 14`)会把它当绿幕吃掉 82%,而空间分割(`bgTolerance 40`)会从四边
964
+ * 灌进去把墙内部的阴影也吃掉 —— 城墙被啃成一堆碎片。
965
+ * 所以整图只认「**饱和纯绿**」(优势值 ≥ 80 才开始透明、≥ 150 全透明),不分割;
966
+ * 不够绿就原样保留并说明(宁可不抠,也不能把画面啃坏)。
967
+ */
968
+ export const STAMP_KEY_OPTIONS = {
969
+ keyLow: 80,
970
+ keyHigh: 150,
971
+ despill: 0.65,
972
+ edgeShrink: 0,
973
+ bgTolerance: 0
974
+ };
975
+ export function keyStampBackground(frame, keyGreenFn) {
976
+ if (keyGreenFn === undefined)
977
+ return { bitmap: frame, keyed: 0 };
978
+ const result = keyGreenFn(frame.rgba, frame.width, frame.height);
979
+ const fraction = result.backgroundFraction;
980
+ if (!Number.isFinite(fraction) || fraction < 0.02 || fraction > 0.98)
981
+ return { bitmap: frame, keyed: 0 };
982
+ return { bitmap: { width: frame.width, height: frame.height, rgba: result.rgba }, keyed: fraction };
983
+ }
984
+ /**
985
+ * **源图 → 成品素材图**:先缩到「一格 = 一格地图格子」,再烘 4 个旋转。
986
+ *
987
+ * 导入(`registerTileset`)与原地重烘(`recomposeMapTileset`)共用这一条口径 ——
988
+ * 少一处不烘,那一处的整图就永远只有一个朝向。
989
+ */
990
+ export function stampTilesetImage(source, spec, cell, clarity = "smooth") {
991
+ const cellW = Math.max(1, Math.floor(cell.width));
992
+ const cellH = Math.max(1, Math.floor(cell.height));
993
+ const base = resampleToSize(source, spec.cols * cellW, spec.rows * spec.frames * cellH, clarity);
994
+ return bakeStampSheet(base, spec, { width: cellW, height: cellH }, clarity);
995
+ }
996
+ /** 整格的位序:北 1 / 东 2 / 南 4 / 西 8。 */
997
+ const CORNER_SIDES = { N: 1, E: 2, S: 4, W: 8 };
998
+ /**
999
+ * 转角块:把「横着走的砖」和「竖着走的砖」沿一条**斜接线**拼起来,线的两侧各用各的。
1000
+ *
1001
+ * 这是真砌墙的做法(两块砖在转角处斜着对口),也是用户说的「拐角要有拐角的效果」:
1002
+ * 只画一条亮线没用,得让**砖缝真的换向**,否则看起来还是两段直墙交叉。
1003
+ *
1004
+ * 斜接线 = 两条相连边中点之间的那条线;线靠近「角」的那一小块用竖直方向的砖,
1005
+ * 其余用水平方向的砖(四种转角都是一个竖臂 + 一个横臂,所以这个分配是通用的)。
1006
+ */
1007
+ export function joinCorner(horizontal, vertical, sideA, sideB, thickness = 2) {
1008
+ const { width, height } = horizontal;
1009
+ const rgba = Buffer.alloc(width * height * 4);
1010
+ const midA = sideMidpoint(sideA, width, height);
1011
+ const midB = sideMidpoint(sideB, width, height);
1012
+ // 角那一侧 = 两条边的公共角(N + W → 左上;N + E → 右上;S + E → 右下;S + W → 左下)。
1013
+ const cornerX = sideA === "N" || sideA === "S" ? (sideB === "W" ? 0 : width - 1) : sideA === "W" ? 0 : width - 1;
1014
+ const cornerY = sideA === "E" || sideA === "W" ? (sideB === "N" ? 0 : height - 1) : sideA === "N" ? 0 : height - 1;
1015
+ const line = Math.max(1, Math.round(thickness));
1016
+ const span = Math.max(1, Math.hypot(midB.x - midA.x, midB.y - midA.y));
1017
+ const towardsCorner = (midB.x - midA.x) * (cornerY - midA.y) - (midB.y - midA.y) * (cornerX - midA.x);
1018
+ for (let y = 0; y < height; y++) {
1019
+ for (let x = 0; x < width; x++) {
1020
+ // 叉积的符号就是「在哪一侧」,不用开方也算得出距离。
1021
+ const cross = (midB.x - midA.x) * (y - midA.y) - (midB.y - midA.y) * (x - midA.x);
1022
+ const cornerSide = Math.sign(cross) === Math.sign(towardsCorner);
1023
+ const source = cornerSide ? vertical : horizontal;
1024
+ const offset = (y * width + x) * 4;
1025
+ rgba[offset] = source.rgba[offset];
1026
+ rgba[offset + 1] = source.rgba[offset + 1];
1027
+ rgba[offset + 2] = source.rgba[offset + 2];
1028
+ rgba[offset + 3] = source.rgba[offset + 3];
1029
+ const distance = Math.abs(cross) / span;
1030
+ if (distance <= line * 0.5) {
1031
+ // 斜接缝本身:提亮一线,读起来是两块砖在这里对口。
1032
+ for (let channel = 0; channel < 3; channel++)
1033
+ rgba[offset + channel] = clamp255(Math.round(rgba[offset + channel] * 1.28));
1034
+ }
1035
+ else if (distance <= line * 2.5) {
1036
+ // 缝两侧一点点压暗(渐淡),给拐角一点体积感,不至于像贴纸。
1037
+ const factor = 1 - 0.18 * (1 - (distance - line * 0.5) / (line * 2));
1038
+ for (let channel = 0; channel < 3; channel++)
1039
+ rgba[offset + channel] = clamp255(Math.round(rgba[offset + channel] * factor));
1040
+ }
1041
+ }
1042
+ }
1043
+ return { width, height, rgba };
1044
+ }
1045
+ /** 把 `joinCorner` 的结果写回已有的块(省一次分配)。 */
1046
+ function joinCornerInto(target, horizontal, vertical, sideA, sideB, thickness) {
1047
+ const joined = joinCorner(horizontal, vertical, sideA, sideB, thickness);
1048
+ joined.rgba.copy(target.rgba);
1049
+ }
1050
+ /** 0~255 夹紧。 */
1051
+ function clamp255(value) {
1052
+ return Math.max(0, Math.min(255, Math.round(value)));
1053
+ }
1054
+ /** 一条边的中点(画斜接用)。 */
1055
+ function sideMidpoint(side, width, height) {
1056
+ if (side === "N")
1057
+ return { x: (width - 1) / 2, y: 0 };
1058
+ if (side === "S")
1059
+ return { x: (width - 1) / 2, y: height - 1 };
1060
+ if (side === "W")
1061
+ return { x: 0, y: (height - 1) / 2 };
1062
+ return { x: width - 1, y: (height - 1) / 2 };
1063
+ }
1064
+ export function corner16SheetFromTile(tile, cell, clarity = "sharp") {
1065
+ const blockW = Math.max(1, Math.floor(cell.width));
1066
+ const blockH = Math.max(1, Math.floor(cell.height));
1067
+ const sheet = { width: blockW * CORNER16_BLOCKS, height: blockH * CORNER16_BLOCKS, rgba: Buffer.alloc(blockW * CORNER16_BLOCKS * blockH * CORNER16_BLOCKS * 4) };
1068
+ const thickness = capThicknessFor(Math.min(blockW, blockH));
1069
+ // 斜接按块大小走:32px 一格约 2px 线,128px(4 倍留图)时约 7px。
1070
+ const miterSize = Math.max(1, Math.round(Math.min(blockW, blockH) / 18));
1071
+ const base = resampleToSize(tile, blockW, blockH, clarity);
1072
+ /**
1073
+ * **方向感知**:整格是「墙体」用法(拼块才是「材质」用法),所以砖缝要跟着墙的走向。
1074
+ *
1075
+ * - 南北直线(N+S,掩码 5):把砖顺时针转 90° —— 墙竖起来,砖缝也得竖起来;
1076
+ * - 转角(N+E / E+S / S+W / W+N):在两条相连边的中点之间画斜接,拐角才有「转角」的样子;
1077
+ * - 其它(直线东西、端头、T 字、十字、孤立):直接用砖本身。
1078
+ *
1079
+ * 这一步做在 compose 阶段(16 块烘进素材图),渲染器一行不用改 —— 它照旧按掩码挑块。
1080
+ */
1081
+ const vertical = rotate90(base, true);
1082
+ for (let mask = 0; mask < CORNER16_BLOCKS * CORNER16_BLOCKS; mask++) {
1083
+ const block = { width: blockW, height: blockH, rgba: Buffer.from((mask === (CORNER_SIDES.N | CORNER_SIDES.S) ? vertical : base).rgba) };
1084
+ // 转角:横竖两版沿斜接线拼起来(真砌墙的转角做法);收口照旧落在断开的那几边。
1085
+ if (mask === (CORNER_SIDES.N | CORNER_SIDES.W))
1086
+ joinCornerInto(block, base, vertical, "N", "W", miterSize);
1087
+ else if (mask === (CORNER_SIDES.N | CORNER_SIDES.E))
1088
+ joinCornerInto(block, base, vertical, "N", "E", miterSize);
1089
+ else if (mask === (CORNER_SIDES.E | CORNER_SIDES.S))
1090
+ joinCornerInto(block, base, vertical, "E", "S", miterSize);
1091
+ else if (mask === (CORNER_SIDES.S | CORNER_SIDES.W))
1092
+ joinCornerInto(block, base, vertical, "S", "W", miterSize);
1093
+ // 位序 N=1 / E=2 / S=4 / W=8:**没置位**的那几边就是「断」,要收口。
1094
+ if ((mask & 1) === 0)
1095
+ shadeSide(block, "N", thickness);
1096
+ if ((mask & 2) === 0)
1097
+ shadeSide(block, "E", thickness);
1098
+ if ((mask & 4) === 0)
1099
+ shadeSide(block, "S", thickness);
1100
+ if ((mask & 8) === 0)
1101
+ shadeSide(block, "W", thickness);
1102
+ blitInto(block, sheet, (mask % CORNER16_BLOCKS) * blockW, Math.floor(mask / CORNER16_BLOCKS) * blockH);
1103
+ }
1104
+ return sheet;
1105
+ }
1106
+ /**
1107
+ * 拼块(`a2quad`):由**每个变体一块无缝砖**拼出 N 列 × 5 行;每一格的四个小格分别按
1108
+ * 「它自己那一侧的接法」加收口。
1109
+ *
1110
+ * 小格与地图象限的对应(见 `maprender.a2Ops`):一格的第 (qx, qy) 个小格(qx 左/右、qy 上/下)
1111
+ * 就是地图上那一格的对应象限;形状号 s 决定该象限「横向邻居」(left/right)与「纵向邻居」
1112
+ * (up/down)接不接:
1113
+ *
1114
+ * | s | 横向邻居 | 纵向邻居 | 对角 |
1115
+ * |---|---|---|---|
1116
+ * | 0 | 断 | 断 | — |
1117
+ * | 1 | 断 | 连 | — |
1118
+ * | 2 | 连 | 断 | — |
1119
+ * | 3 | 连 | 连 | 断(凹角) |
1120
+ * | 4 | 连 | 连 | 连(满格,什么都不加) |
1121
+ *
1122
+ * 与整格同理:所有小格都来自**同一块砖**,所以任何两块在「连」的那边拼起来都是砖自己的
1123
+ * 边缘 —— 一排草地 / 一片水不会出现「每格各画各的」那种接缝。
1124
+ */
1125
+ export function a2SheetFromTiles(tiles, cell, clarity = "sharp") {
1126
+ if (tiles.length === 0)
1127
+ throw new Error("没有可整理的帧");
1128
+ const blockW = Math.max(1, Math.floor(cell.width));
1129
+ const blockH = Math.max(1, Math.floor(cell.height));
1130
+ const subW = Math.max(1, Math.round(blockW / 2));
1131
+ const subH = Math.max(1, Math.round(blockH / 2));
1132
+ const variants = tiles.length;
1133
+ const sheet = { width: blockW * variants, height: blockH * A2_ROWS, rgba: Buffer.alloc(blockW * variants * blockH * A2_ROWS * 4) };
1134
+ const thickness = capThicknessFor(Math.min(subW, subH));
1135
+ for (let variant = 0; variant < variants; variant++) {
1136
+ const block = resampleToSize(tiles[variant], blockW, blockH, clarity);
1137
+ for (let shape = 0; shape < A2_ROWS; shape++) {
1138
+ // 该形状下,「横向邻居」「纵向邻居」接不接(见上面那张表)。
1139
+ const sideConnected = shape >= 2;
1140
+ const verticalConnected = shape === 1 || shape >= 3;
1141
+ for (let qy = 0; qy < 2; qy++) {
1142
+ for (let qx = 0; qx < 2; qx++) {
1143
+ const sub = cropTile(block, { x: qx * subW, y: qy * subH, width: subW, height: subH });
1144
+ if (!sideConnected)
1145
+ shadeSide(sub, qx === 0 ? "W" : "E", thickness);
1146
+ if (!verticalConnected)
1147
+ shadeSide(sub, qy === 0 ? "N" : "S", thickness);
1148
+ if (shape === 3)
1149
+ shadeCorner(sub, `${qy === 0 ? "N" : "S"}${qx === 0 ? "W" : "E"}`, thickness);
1150
+ blitInto(sub, sheet, variant * blockW + qx * subW, shape * blockH + qy * subH);
1151
+ }
1152
+ }
1153
+ }
1154
+ }
1155
+ return sheet;
1156
+ }
1157
+ /**
1158
+ * 砖自身的**环绕缝**:左右、上下两条对边的平均差,除以块内相邻列 / 行的平均差。
1159
+ *
1160
+ * 1 左右 = 和自己内部一样平(无缝);明显大于 1 说明这块砖左右 / 上下接不上自己 ——
1161
+ * 平铺出去就会出现可见的缝。宿主把它写进 `notes`,用户 / agent 可以据此重画。
1162
+ */
1163
+ export function tileSeamRatios(tile) {
1164
+ const px = (x, y) => {
1165
+ const offset = (y * tile.width + x) * 4;
1166
+ return [tile.rgba[offset], tile.rgba[offset + 1], tile.rgba[offset + 2], tile.rgba[offset + 3]];
1167
+ };
1168
+ const distance = (a, b) => Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]) + Math.abs(a[2] - b[2]) + Math.abs(a[3] - b[3]);
1169
+ let horizontalWrap = 0;
1170
+ let verticalWrap = 0;
1171
+ for (let y = 0; y < tile.height; y++)
1172
+ horizontalWrap += distance(px(0, y), px(tile.width - 1, y));
1173
+ for (let x = 0; x < tile.width; x++)
1174
+ verticalWrap += distance(px(x, 0), px(x, tile.height - 1));
1175
+ horizontalWrap /= tile.height;
1176
+ verticalWrap /= tile.width;
1177
+ let horizontalInner = 0;
1178
+ let verticalInner = 0;
1179
+ let innerCount = 0;
1180
+ for (let y = 0; y < tile.height; y++) {
1181
+ for (let x = 1; x < tile.width; x++) {
1182
+ horizontalInner += distance(px(x - 1, y), px(x, y));
1183
+ innerCount++;
1184
+ }
1185
+ }
1186
+ horizontalInner = innerCount === 0 ? 0 : horizontalInner / innerCount;
1187
+ innerCount = 0;
1188
+ for (let x = 0; x < tile.width; x++) {
1189
+ for (let y = 1; y < tile.height; y++) {
1190
+ verticalInner += distance(px(x, y - 1), px(x, y));
1191
+ innerCount++;
1192
+ }
1193
+ }
1194
+ verticalInner = innerCount === 0 ? 0 : verticalInner / innerCount;
1195
+ const ratio = (wrap, inner) => (inner <= 0.5 ? 1 : wrap / inner);
1196
+ return { horizontal: ratio(horizontalWrap, horizontalInner), vertical: ratio(verticalWrap, verticalInner) };
1197
+ }
1198
+ /**
1199
+ * 按形态算目标几何。`frames` 对普通是帧数、对拼块是变体数;整格固定 4×4;
1200
+ * 整图由 `stamp` 规格决定(帧 × 4 旋转 × 占格)。
1201
+ */
1202
+ export function sheetPlanOf(shape, cell, frames, stamp) {
1203
+ if (shape === "stamp") {
1204
+ if (stamp === undefined)
1205
+ throw new Error("整图缺规格(占几格 / 几帧)");
1206
+ // 源图 = `cols × rows*frames`(**不含**旋转烘焙:那是导入端的事)。
1207
+ const size = stampSourceCells(stamp);
1208
+ return { shape, cell: { width: Math.max(1, Math.floor(cell.width)), height: Math.max(1, Math.floor(cell.height)) }, cols: size.cols, rows: size.rows };
1209
+ }
1210
+ const width = Math.max(1, Math.floor(cell.width));
1211
+ const height = Math.max(1, Math.floor(cell.height));
1212
+ const count = Math.max(1, Math.floor(frames) || 1);
1213
+ if (shape === "corner16")
1214
+ return { shape, cell: { width, height }, cols: CORNER16_BLOCKS, rows: CORNER16_BLOCKS };
1215
+ if (shape === "a2quad")
1216
+ return { shape, cell: { width, height }, cols: count, rows: A2_ROWS };
1217
+ return { shape: "plain", cell: { width, height }, cols: 1, rows: count };
1218
+ }
1219
+ /**
1220
+ * 按**形态计划**把模型吐出来的那几张图规整成地图编辑器要的几何。
1221
+ *
1222
+ * 三种形态的输入约定(提示词里逐条讲给模型听,这里是对应的代码):
1223
+ * · `plain` 每张 = **一帧**(一格内容)→ 每张裁成 `cell`、自上而下堆成一列
1224
+ * (N 帧 = 一列 N 行的翻页图)
1225
+ * · `corner16` 恰好 **1 张** = **一块**无缝墙砖 → `corner16SheetFromTile` 拼出 4×4 = 16 格
1226
+ * · `a2quad` 每张 = **一个变体的一块**无缝材质 → `a2SheetFromTiles` 拼出 N 列 × 5 行
1227
+ * (拼块的动画就是「换变体」,所以帧数 = 变体数)
1228
+ *
1229
+ * ⚠️ **整格 / 拼块都不能让模型直接画「多格排布」**:模型画出的多格是各自独立的
1230
+ * (灯带 / 板纹各自偏几十像素),而地图上相邻的两格往往取自**不同的格子**,于是每一处
1231
+ * 交界都是硬缝(实测一条墙的边缘差 201、块内才 58)。所以这两条路都是「模型给一块砖、
1232
+ * 代码拼出全部格子」。
1233
+ */
1234
+ export function composeAssetSheet(frames, plan, clarity = "sharp") {
1235
+ if (frames.length === 0)
1236
+ throw new Error("没有可整理的帧");
1237
+ if (plan.shape === "plain")
1238
+ return stackFrames(frames, plan.cell, clarity);
1239
+ if (plan.shape === "corner16") {
1240
+ if (frames.length !== 1) {
1241
+ throw new Error(`整格自动连接的素材需要**一块**无缝墙砖(收到 ${frames.length} 张:16 种接法由宿主从这一块拼出来)`);
1242
+ }
1243
+ return corner16SheetFromTile(frames[0], plan.cell, clarity);
1244
+ }
1245
+ return a2SheetFromTiles(frames, plan.cell, clarity);
1246
+ }
1247
+ /**
1248
+ * 素材名字 → 能当文件名的干名。
1249
+ *
1250
+ * 名字是用户填的(可能带 `/`、换行、超长),要拿去当 `ai/<干名>.png`。这里只做
1251
+ * **保守归一**:去掉路径分隔与控制字符、把空白压成一个空格、截 40 字、去掉结尾的
1252
+ * 点(Windows 上 `x.` 是非法文件名);实在空就退回 `ai-asset`。不做拼音 / 转写 ——
1253
+ * 中文文件名在 mac / Windows 与资源路由上都正常工作。
1254
+ */
1255
+ export function safeAssetStem(name) {
1256
+ const cleaned = String(name ?? "")
1257
+ .normalize("NFC")
1258
+ // eslint-disable-next-line no-control-regex
1259
+ .replace(/[\\/:*?"<>|\u0000-\u001f]/gu, " ")
1260
+ .replace(/\s+/gu, " ")
1261
+ .trim()
1262
+ .slice(0, 40)
1263
+ .replace(/\.+$/u, "")
1264
+ .trim();
1265
+ return cleaned === "" ? "ai-asset" : cleaned;
1266
+ }