dsh-game-material-master 0.1.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/chroma.js ADDED
@@ -0,0 +1,466 @@
1
+ /**
2
+ * 绿幕抠像与整图合成。
3
+ *
4
+ * 抠像有两条判据,先空间、后颜色:
5
+ *
6
+ * 1. **边界洪水填充**(主判据)。从画面四边出发,只沿着「与相邻已判定背景
7
+ * 像素颜色接近」的方向生长。它跟随的是**局部连续性**而不是某个固定颜色,
8
+ * 所以绿幕、黄幕、甚至平缓渐变的背景都能整片吃掉,并在角色轮廓的突变处
9
+ * 停下。这一步是必需的:图生视频模型经常会把纯色背景重新打光成渐变,
10
+ * 只认绿色的做法在那些帧上会整片失效。
11
+ *
12
+ * 2. **绿色优势值** `g - max(r, b)`(辅助判据)。只作用在未被判定为背景的
13
+ * 像素上,用来清理角色轮廓残留的绿色边缘,并提供去绿溢出。
14
+ *
15
+ * 合成则是「统一裁剪 + 区域重采样 + 像素量化」:先在所有帧上求 alpha 包围盒
16
+ * 的并集,全部帧共用同一个框——这样各方向的缩放一致、脚底也对齐在同一条
17
+ * 基线上;再按盒式平均重采样到目标尺寸,最后量化成 pixelSize 的方块。
18
+ */
19
+ import { encodePng } from "./png.js";
20
+ export const DEFAULT_KEY_OPTIONS = {
21
+ keyLow: 14,
22
+ keyHigh: 80,
23
+ despill: 0.65,
24
+ edgeShrink: 0,
25
+ bgTolerance: 40
26
+ };
27
+ /** 两个像素的 RGB 欧氏距离。 */
28
+ function colorDistance(rgba, a, b) {
29
+ const dr = rgba[a] - rgba[b];
30
+ const dg = rgba[a + 1] - rgba[b + 1];
31
+ const db = rgba[a + 2] - rgba[b + 2];
32
+ return Math.sqrt(dr * dr + dg * dg + db * db);
33
+ }
34
+ /** 背景调色板的量化格:每通道 16 档。 */
35
+ const PALETTE_GRID = 16;
36
+ const PALETTE_CELL = 256 / PALETTE_GRID;
37
+ /**
38
+ * 用四边像素建一个「背景色查找格」。
39
+ *
40
+ * 为什么需要它:只用「和相邻像素颜色接近」来生长,会顺着抗锯齿的软边缘
41
+ * 一路渗进角色——绿幕到白色围裙的过渡如果跨了 3~4 个像素,每一步的差值都
42
+ * 小于局部容差,填充就穿过去了。加上这条全局约束后,像素还必须「本身就像
43
+ * 背景色」才可能被判为背景,软边缘自然被挡住。
44
+ *
45
+ * 采样点覆盖整圈边界,所以平缓渐变的背景也能被完整覆盖。
46
+ */
47
+ function buildBackgroundPalette(rgba, width, height, globalTolerance) {
48
+ const grid = new Uint8Array(PALETTE_GRID * PALETTE_GRID * PALETTE_GRID);
49
+ const seen = new Uint8Array(PALETTE_GRID * PALETTE_GRID * PALETTE_GRID);
50
+ // 量化误差最多 8*sqrt(3) ≈ 14,补进半径里,避免刚好卡在格边界的颜色被漏掉。
51
+ const limit = globalTolerance + 14;
52
+ const limitSq = limit * limit;
53
+ const radius = Math.max(1, Math.ceil(limit / PALETTE_CELL));
54
+ const mark = (index) => {
55
+ const r = Math.min(PALETTE_GRID - 1, rgba[index] >> 4);
56
+ const g = Math.min(PALETTE_GRID - 1, rgba[index + 1] >> 4);
57
+ const b = Math.min(PALETTE_GRID - 1, rgba[index + 2] >> 4);
58
+ const key = (r * PALETTE_GRID + g) * PALETTE_GRID + b;
59
+ if (seen[key] === 1)
60
+ return;
61
+ seen[key] = 1;
62
+ // 必须按**球体**标记,不能只按格坐标的范围扫一圈:
63
+ // 那会标出一个立方体,角落到中心的距离可达 limit*sqrt(3),
64
+ // 于是离背景很远的角色颜色也会被误判成背景色。
65
+ for (let dr = -radius; dr <= radius; dr++) {
66
+ const nr = r + dr;
67
+ if (nr < 0 || nr >= PALETTE_GRID)
68
+ continue;
69
+ for (let dg = -radius; dg <= radius; dg++) {
70
+ const ng = g + dg;
71
+ if (ng < 0 || ng >= PALETTE_GRID)
72
+ continue;
73
+ for (let db = -radius; db <= radius; db++) {
74
+ const nb = b + db;
75
+ if (nb < 0 || nb >= PALETTE_GRID)
76
+ continue;
77
+ const distSq = (dr * PALETTE_CELL) ** 2 + (dg * PALETTE_CELL) ** 2 + (db * PALETTE_CELL) ** 2;
78
+ if (distSq > limitSq)
79
+ continue;
80
+ grid[(nr * PALETTE_GRID + ng) * PALETTE_GRID + nb] = 1;
81
+ }
82
+ }
83
+ }
84
+ };
85
+ // 步长控制采样量:长边最多取 128 个点,够覆盖渐变又不至于拖慢。
86
+ const stepX = Math.max(1, Math.floor(width / 128));
87
+ const stepY = Math.max(1, Math.floor(height / 128));
88
+ for (let x = 0; x < width; x += stepX) {
89
+ mark(x * 4);
90
+ mark(((height - 1) * width + x) * 4);
91
+ }
92
+ for (let y = 0; y < height; y += stepY) {
93
+ mark(y * width * 4);
94
+ mark((y * width + width - 1) * 4);
95
+ }
96
+ return grid;
97
+ }
98
+ function paletteHas(grid, rgba, index) {
99
+ const r = Math.min(PALETTE_GRID - 1, rgba[index] >> 4);
100
+ const g = Math.min(PALETTE_GRID - 1, rgba[index + 1] >> 4);
101
+ const b = Math.min(PALETTE_GRID - 1, rgba[index + 2] >> 4);
102
+ return grid[(r * PALETTE_GRID + g) * PALETTE_GRID + b] === 1;
103
+ }
104
+ /**
105
+ * 从四边洪水填充出背景掩码:**必须同时满足**「颜色像背景(全局调色板)」
106
+ * 和「与相邻的已判定背景像素颜色接近(局部连续性)」。
107
+ *
108
+ * 全局约束挡住软边缘渗透,局部约束则让填充能跟随调色板覆盖不到的渐变。
109
+ * 返回 1 = 背景,0 = 前景。
110
+ */
111
+ export function segmentBackground(rgba, width, height, globalTolerance, localTolerance) {
112
+ // 局部容差故意收得很紧:它只用来跨过背景自身的细微噪声与编码块边界。
113
+ // 背景的**大范围变化**(渐变、被重新打光)由全局调色板负责——边界采样本来就
114
+ // 覆盖了整圈颜色,局部判据不需要承担这件事。
115
+ //
116
+ // 收得紧是必须的:填充一旦放宽就会顺着抗锯齿的软边缘渗进角色体内,把整个
117
+ // 身体判成背景。实测真实素材(H3 输出)在 64 帧上的表现——12/14 全部正常,
118
+ // 16 开始穿透,18 以上整片失效。
119
+ //
120
+ // 12 不会因为噪声而漏抠:4 邻域填充可以从别的方向绕开孤立的噪声像素,
121
+ // 只有**连续成片**的强边缘(也就是角色轮廓)才能挡住它。
122
+ const local = Math.max(1, Math.round(localTolerance ?? 12));
123
+ const palette = buildBackgroundPalette(rgba, width, height, globalTolerance);
124
+ const total = width * height;
125
+ const background = new Uint8Array(total);
126
+ const stack = new Int32Array(total);
127
+ let top = 0;
128
+ // 种子必须自己就"像背景",否则贴边裁切的角色会被整片误删。
129
+ const push = (index) => {
130
+ if (background[index] === 1)
131
+ return;
132
+ if (!paletteHas(palette, rgba, index * 4))
133
+ return;
134
+ background[index] = 1;
135
+ stack[top++] = index;
136
+ };
137
+ for (let x = 0; x < width; x++) {
138
+ push(x);
139
+ push((height - 1) * width + x);
140
+ }
141
+ for (let y = 0; y < height; y++) {
142
+ push(y * width);
143
+ push(y * width + width - 1);
144
+ }
145
+ while (top > 0) {
146
+ const index = stack[--top];
147
+ const current = index * 4;
148
+ const x = index % width;
149
+ const y = (index - x) / width;
150
+ const visit = (n) => {
151
+ if (background[n] === 1)
152
+ return;
153
+ if (!paletteHas(palette, rgba, n * 4))
154
+ return;
155
+ if (colorDistance(rgba, current, n * 4) > local)
156
+ return;
157
+ background[n] = 1;
158
+ stack[top++] = n;
159
+ };
160
+ if (x > 0)
161
+ visit(index - 1);
162
+ if (x < width - 1)
163
+ visit(index + 1);
164
+ if (y > 0)
165
+ visit(index - width);
166
+ if (y < height - 1)
167
+ visit(index + width);
168
+ }
169
+ return background;
170
+ }
171
+ /** 没启用空间分割时,用颜色判据粗略估一个背景占比,供界面判断可信度。 */
172
+ function countGreenBackground(rgba, high) {
173
+ let count = 0;
174
+ for (let p = 0; p < rgba.length; p += 4) {
175
+ if (rgba[p + 1] - Math.max(rgba[p], rgba[p + 2]) >= high)
176
+ count++;
177
+ }
178
+ return count;
179
+ }
180
+ /**
181
+ * 抠掉背景,返回新的 RGBA 缓冲区与诊断信息。
182
+ * 输入输出都是 `width * height * 4` 字节、非预乘 alpha。
183
+ */
184
+ export function keyGreen(rgba, width, height, options) {
185
+ const low = Math.max(0, Math.min(255, options.keyLow));
186
+ const high = Math.max(low + 1, Math.min(255, options.keyHigh));
187
+ const span = high - low;
188
+ const despill = Math.max(0, Math.min(1, options.despill));
189
+ const tolerance = Math.max(0, options.bgTolerance ?? 0);
190
+ const pixels = width * height;
191
+ // 空间分割只在结果合理时采用:几乎全是背景说明画面里没有主体,
192
+ // 几乎没有背景说明四边就是角色本身(贴边裁切)。两种都不可信。
193
+ let background;
194
+ let backgroundCount = 0;
195
+ if (tolerance > 0) {
196
+ const candidate = segmentBackground(rgba, width, height, tolerance);
197
+ let count = 0;
198
+ for (let i = 0; i < pixels; i++)
199
+ count += candidate[i];
200
+ const fraction = count / pixels;
201
+ if (fraction > 0.12 && fraction < 0.985) {
202
+ background = candidate;
203
+ backgroundCount = count;
204
+ }
205
+ }
206
+ const out = Buffer.alloc(rgba.length);
207
+ for (let i = 0; i < pixels; i++) {
208
+ const p = i * 4;
209
+ const r = rgba[p];
210
+ const g = rgba[p + 1];
211
+ const b = rgba[p + 2];
212
+ const srcAlpha = rgba[p + 3];
213
+ const other = r > b ? r : b;
214
+ const greenness = g - other;
215
+ let alpha = 1;
216
+ if (greenness >= high)
217
+ alpha = 0;
218
+ else if (greenness > low)
219
+ alpha = 1 - (greenness - low) / span;
220
+ alpha *= srcAlpha / 255;
221
+ // 空间上确认为背景的像素直接全透明;颜色判据只负责前景里的绿色残余。
222
+ if (background !== undefined && background[i] === 1)
223
+ alpha = 0;
224
+ let outG = g;
225
+ if (despill > 0 && g > other) {
226
+ const weight = despill * (1 - alpha);
227
+ if (weight > 0)
228
+ outG = Math.round(g - (g - other) * weight);
229
+ }
230
+ out[p] = r;
231
+ out[p + 1] = outG;
232
+ out[p + 2] = b;
233
+ out[p + 3] = Math.round(alpha * 255);
234
+ }
235
+ if (options.edgeShrink > 0)
236
+ shrinkAlpha(out, width, height, Math.min(8, Math.round(options.edgeShrink)));
237
+ return {
238
+ rgba: out,
239
+ backgroundFraction: background !== undefined ? backgroundCount / pixels : countGreenBackground(rgba, high) / pixels,
240
+ usedSegmentation: background !== undefined
241
+ };
242
+ }
243
+ /** 对 alpha 通道做可分离的最小值滤波,等价于把前景边界向内收缩 n 像素。 */
244
+ function shrinkAlpha(rgba, width, height, radius) {
245
+ const alpha = new Uint8Array(width * height);
246
+ for (let i = 0; i < width * height; i++)
247
+ alpha[i] = rgba[i * 4 + 3];
248
+ const horizontal = new Uint8Array(width * height);
249
+ for (let y = 0; y < height; y++) {
250
+ const row = y * width;
251
+ for (let x = 0; x < width; x++) {
252
+ let min = 255;
253
+ const from = Math.max(0, x - radius);
254
+ const to = Math.min(width - 1, x + radius);
255
+ for (let k = from; k <= to; k++) {
256
+ const v = alpha[row + k];
257
+ if (v < min)
258
+ min = v;
259
+ }
260
+ horizontal[row + x] = min;
261
+ }
262
+ }
263
+ for (let y = 0; y < height; y++) {
264
+ const from = Math.max(0, y - radius);
265
+ const to = Math.min(height - 1, y + radius);
266
+ for (let x = 0; x < width; x++) {
267
+ let min = 255;
268
+ for (let k = from; k <= to; k++) {
269
+ const v = horizontal[k * width + x];
270
+ if (v < min)
271
+ min = v;
272
+ }
273
+ rgba[(y * width + x) * 4 + 3] = min;
274
+ }
275
+ }
276
+ }
277
+ /** 所有帧 alpha 包围盒的并集。 */
278
+ export function unionBoundingBox(rows, threshold = 8) {
279
+ let minX = Infinity;
280
+ let minY = Infinity;
281
+ let maxX = -Infinity;
282
+ let maxY = -Infinity;
283
+ for (const row of rows) {
284
+ for (const frame of row.frames) {
285
+ if (frame.length < row.width * row.height * 4)
286
+ continue;
287
+ for (let y = 0; y < row.height; y++) {
288
+ const rowStart = y * row.width * 4;
289
+ for (let x = 0; x < row.width; x++) {
290
+ if (frame[rowStart + x * 4 + 3] <= threshold)
291
+ continue;
292
+ if (x < minX)
293
+ minX = x;
294
+ if (x > maxX)
295
+ maxX = x;
296
+ if (y < minY)
297
+ minY = y;
298
+ if (y > maxY)
299
+ maxY = y;
300
+ }
301
+ }
302
+ }
303
+ }
304
+ if (minX === Infinity)
305
+ return { x: 0, y: 0, width: 0, height: 0, empty: true };
306
+ return { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1, empty: false };
307
+ }
308
+ /**
309
+ * 把一块的源区域做盒式平均(按 alpha 预乘,避免背景色渗进边缘),
310
+ * 再填满输出里对应的整块。
311
+ */
312
+ function blitBlock(out, outWidth, outHeight, destX, destY, destW, destH, frame, frameWidth, frameHeight, srcX, srcY, srcW, srcH) {
313
+ const x0 = Math.max(0, destX);
314
+ const y0 = Math.max(0, destY);
315
+ const x1 = Math.min(outWidth, destX + destW);
316
+ const y1 = Math.min(outHeight, destY + destH);
317
+ if (x1 <= x0 || y1 <= y0)
318
+ return;
319
+ const sx0 = Math.max(0, Math.floor(srcX));
320
+ const sy0 = Math.max(0, Math.floor(srcY));
321
+ const sx1 = Math.min(frameWidth, Math.ceil(srcX + srcW));
322
+ const sy1 = Math.min(frameHeight, Math.ceil(srcY + srcH));
323
+ if (sx1 <= sx0 || sy1 <= sy0)
324
+ return;
325
+ let sumR = 0;
326
+ let sumG = 0;
327
+ let sumB = 0;
328
+ let sumA = 0;
329
+ let count = 0;
330
+ for (let y = sy0; y < sy1; y++) {
331
+ let index = (y * frameWidth + sx0) * 4;
332
+ for (let x = sx0; x < sx1; x++, index += 4) {
333
+ const a = frame[index + 3];
334
+ sumR += frame[index] * a;
335
+ sumG += frame[index + 1] * a;
336
+ sumB += frame[index + 2] * a;
337
+ sumA += a;
338
+ count++;
339
+ }
340
+ }
341
+ if (count === 0 || sumA === 0)
342
+ return;
343
+ const r = Math.round(sumR / sumA);
344
+ const g = Math.round(sumG / sumA);
345
+ const b = Math.round(sumB / sumA);
346
+ const a = Math.round(sumA / count);
347
+ for (let y = y0; y < y1; y++) {
348
+ let index = (y * outWidth + x0) * 4;
349
+ for (let x = x0; x < x1; x++, index += 4) {
350
+ out[index] = r;
351
+ out[index + 1] = g;
352
+ out[index + 2] = b;
353
+ out[index + 3] = a;
354
+ }
355
+ }
356
+ }
357
+ /**
358
+ * 把每个方向的 N 帧拼成一张整图:**行 = 方向,列 = 帧**。
359
+ * 缺帧的格子留空(全透明),方便肉眼看出是哪一步没跑出来。
360
+ */
361
+ export function composeSheet(rows, options) {
362
+ const columns = Math.max(1, options.frameCount);
363
+ const rowCount = Math.max(1, rows.length);
364
+ const cellWidth = options.cellWidth;
365
+ const cellHeight = options.cellHeight;
366
+ const width = cellWidth * columns;
367
+ const height = cellHeight * rowCount;
368
+ const rgba = Buffer.alloc(width * height * 4);
369
+ const pixelSize = Math.max(1, Math.round(options.pixelSize));
370
+ const first = rows.find((row) => row.frames.length > 0);
371
+ const frameWidth = first?.width ?? cellWidth;
372
+ const frameHeight = first?.height ?? cellHeight;
373
+ const bbox = options.autoCrop
374
+ ? unionBoundingBox(rows)
375
+ : { x: 0, y: 0, width: frameWidth, height: frameHeight, empty: false };
376
+ const emptyContent = { x: 0, y: 0, width: 0, height: 0, scaleX: 0, scaleY: 0 };
377
+ if (bbox.empty || bbox.width <= 0 || bbox.height <= 0) {
378
+ return { rgba, width, height, columns, rows: rowCount, bbox, content: emptyContent };
379
+ }
380
+ const bottomMargin = Math.max(0, Math.min(cellHeight - 1, Math.round(options.bottomMargin)));
381
+ let scaleX;
382
+ let scaleY;
383
+ if (options.fitMode === "stretch") {
384
+ scaleX = cellWidth / bbox.width;
385
+ scaleY = (cellHeight - bottomMargin) / bbox.height;
386
+ }
387
+ else {
388
+ const fill = Math.max(0.1, Math.min(1, options.fillRatio));
389
+ const scale = Math.min((cellWidth * fill) / bbox.width, ((cellHeight - bottomMargin) * fill) / bbox.height);
390
+ scaleX = scale;
391
+ scaleY = scale;
392
+ }
393
+ const contentW = Math.min(cellWidth, Math.max(1, Math.round(bbox.width * scaleX)));
394
+ const contentH = Math.min(cellHeight - bottomMargin, Math.max(1, Math.round(bbox.height * scaleY)));
395
+ const offsetX = Math.round((cellWidth - contentW) / 2);
396
+ // 贴底放置:脚底落在同一条基线上,上下起伏才不会看起来在飘。
397
+ const offsetY = Math.max(0, cellHeight - bottomMargin - contentH);
398
+ const blocksX = Math.ceil(cellWidth / pixelSize);
399
+ const blocksY = Math.ceil(cellHeight / pixelSize);
400
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
401
+ const row = rows[rowIndex];
402
+ for (let col = 0; col < columns; col++) {
403
+ const frame = row.frames[col];
404
+ if (frame === undefined || frame.length < frameWidth * frameHeight * 4)
405
+ continue;
406
+ const cellOriginX = col * cellWidth;
407
+ const cellOriginY = rowIndex * cellHeight;
408
+ // by/bx 是「相对内容左上角」的块序号,所以块在格子里的绝对位置是
409
+ // offsetY + by*pixelSize;relY 就是它相对内容原点的偏移。
410
+ for (let by = 0; by < blocksY; by++) {
411
+ const relY = by * pixelSize;
412
+ if (relY >= contentH)
413
+ break;
414
+ const destY = offsetY + relY;
415
+ for (let bx = 0; bx < blocksX; bx++) {
416
+ const relX = bx * pixelSize;
417
+ if (relX >= contentW)
418
+ break;
419
+ const destX = offsetX + relX;
420
+ // 只重采样落在内容区内的那一部分(块可能被内容边界截断)
421
+ const clipLeft = Math.max(0, destX);
422
+ const clipTop = Math.max(0, destY);
423
+ const clipRight = Math.min(cellWidth, destX + pixelSize);
424
+ const clipBottom = Math.min(cellHeight, destY + pixelSize);
425
+ if (clipRight <= clipLeft || clipBottom <= clipTop)
426
+ continue;
427
+ if (clipRight <= offsetX || clipLeft >= offsetX + contentW)
428
+ continue;
429
+ if (clipBottom <= offsetY || clipTop >= offsetY + contentH)
430
+ continue;
431
+ blitBlock(rgba, width, height, cellOriginX + clipLeft, cellOriginY + clipTop, clipRight - clipLeft, clipBottom - clipTop, frame, frameWidth, frameHeight, bbox.x + (clipLeft - offsetX) / scaleX, bbox.y + (clipTop - offsetY) / scaleY, (clipRight - clipLeft) / scaleX, (clipBottom - clipTop) / scaleY);
432
+ }
433
+ }
434
+ }
435
+ }
436
+ return {
437
+ rgba,
438
+ width,
439
+ height,
440
+ columns,
441
+ rows: rowCount,
442
+ bbox,
443
+ content: { x: offsetX, y: offsetY, width: contentW, height: contentH, scaleX, scaleY }
444
+ };
445
+ }
446
+ /** 把一串同尺寸帧横向拼成一条预览带(只给界面看)。 */
447
+ export function makeStrip(frames, cellWidth, cellHeight) {
448
+ const width = cellWidth * frames.length;
449
+ const rgba = Buffer.alloc(width * cellHeight * 4);
450
+ const cellBytes = cellWidth * cellHeight * 4;
451
+ for (let i = 0; i < frames.length; i++) {
452
+ const frame = frames[i];
453
+ if (frame.length < cellBytes)
454
+ continue;
455
+ for (let y = 0; y < cellHeight; y++) {
456
+ const srcStart = y * cellWidth * 4;
457
+ const destStart = (y * width + i * cellWidth) * 4;
458
+ frame.copy(rgba, destStart, srcStart, srcStart + cellWidth * 4);
459
+ }
460
+ }
461
+ return encodePng(rgba, width, cellHeight);
462
+ }
463
+ /** 抠完一帧后直接编码成 PNG。 */
464
+ export function keyedPng(rgba, width, height) {
465
+ return encodePng(rgba, width, height);
466
+ }