dsh-game-material-master 0.4.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +101 -12
- package/README.md +86 -11
- package/lib/ark.js +1 -1
- package/lib/{tilemedia.js → bitmap.js} +21 -3
- package/lib/client.js +3295 -158
- package/lib/config.js +70 -2
- package/lib/customimage.js +518 -0
- package/lib/imagegen.js +15 -15
- package/lib/imageprovider.js +151 -0
- package/lib/index.js +305 -9
- package/lib/jsonio.js +24 -3
- package/lib/links.js +11 -2
- package/lib/mapauto.js +126 -0
- package/lib/mapdoc.js +617 -0
- package/lib/mapexport.js +188 -0
- package/lib/mapgen.js +1591 -0
- package/lib/mapgeom.js +320 -0
- package/lib/maprender.js +484 -0
- package/lib/mapsample.js +36 -0
- package/lib/mapsamplegen.js +760 -0
- package/lib/maptiles.js +253 -0
- package/lib/media.js +34 -0
- package/lib/pipeline.js +197 -15
- package/lib/rigexport.js +29 -98
- package/lib/riggen.js +34 -30
- package/lib/rigpath.js +47 -10
- package/lib/rigpreview.js +91 -84
- package/lib/rigsemantics.js +4 -4
- package/lib/rigvalidate.js +72 -14
- package/lib/spine.js +147 -80
- package/lib/store.js +12 -3
- package/lib/tilegen.js +7 -11
- package/lib/tilegeom.js +1 -1
- package/lib/tools.js +253 -29
- package/lib/wire.js +198 -3
- package/lib/zip.js +127 -0
- package/package.json +10 -4
package/lib/maptiles.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 地图编辑器(模块六)的**图集(tileset)模型与切分**。
|
|
3
|
+
*
|
|
4
|
+
* 一个项目可以导入多张图集;每张图集按**自动识别出来的形态**切成图块:
|
|
5
|
+
*
|
|
6
|
+
* · `plain` 正方形网格:按 `cell` 行优先逐格切;`animRows` 时**同一列的每一行
|
|
7
|
+
* 是同一块的一帧**(地形动画,AsLib 的「逐行动画」)
|
|
8
|
+
* · `corner16` 整格自动连接:切法与 plain 完全相同,只是每块会挂一个 4 位掩码
|
|
9
|
+
* · `a2quad` A2 拼块:一格的四个象限从素材里各取一个小格(详见 `buildTiles`)
|
|
10
|
+
*
|
|
11
|
+
* ## 两条铁律
|
|
12
|
+
*
|
|
13
|
+
* 1. **图块 id 由矩形派生**(`t{x}_{y}`),不是数组下标。重新切分(改格尺寸、改形态)
|
|
14
|
+
* 之后,同一个矩形的元数据仍然挂在同一个 id 上;用下标的话会静默漂移。
|
|
15
|
+
* 2. **单元格里存的是「全局图块序号」(1-based,0 = 空)**,不是图块 id ——
|
|
16
|
+
* 绘制计划、脏 chunk、`map.json` 都靠它。序号由 `flatTiles()` 唯一决定,
|
|
17
|
+
* 顺序 = 图集顺序 → `tiles` 数组顺序,别的地方不许按下标自己算。
|
|
18
|
+
*
|
|
19
|
+
* ## A2 的真实几何(照 AsLib,`AsMap.hpp` 的 `drawMapBranch` / `map20n_Number`)
|
|
20
|
+
*
|
|
21
|
+
* 一张 A2 图:小格边长 `S = imageHeight / 10`(10 行小格),横向 `imageWidth % S === 0`。
|
|
22
|
+
* 一个「逻辑块」(= 屏幕上一格)= 2×2 个小格。于是:
|
|
23
|
+
* · **块行号 0..4 = 形状号**(5 种),**块列号 = 变体号**(素材里横着排了几种)
|
|
24
|
+
* · 逻辑块尺寸 = 2S(32px 的块 = 16px 的小格),逻辑块列数 = `imageWidth / (2S)`
|
|
25
|
+
* · `detectLayout(64, 160)` → S=16、块 32×32、2 变体 × 5 形状
|
|
26
|
+
* (AsLib 要求「小格列数(= NumX)是偶数」,否则变体凑不成对)
|
|
27
|
+
* 小格的行列号与小格内的象限是一一对应的:
|
|
28
|
+
* `smallRow = 2 * shape + (0 上 / 1 下)`,`smallCol = 2 * variant + (0 左 / 1 右)`
|
|
29
|
+
* 这跟 AsLib 的 chip 下标 `NumX * 2 * shape + tm_id(+1)(+NumX)` 逐项相等 ——
|
|
30
|
+
* 我们把 `tiles` 按小格行优先展开,于是 **1-based 序号 − 1 = AsLib 的 chip 下标**。
|
|
31
|
+
* 渲染端(`maprender.ts`)按这个对应关系挑象限块,别自己另立一套顺序。
|
|
32
|
+
*/
|
|
33
|
+
import { pngSize } from "./bitmap.js";
|
|
34
|
+
import { A2_SHAPES } from "./mapauto.js";
|
|
35
|
+
export const COMMON_TILE_SIZES = [8, 16, 24, 32, 48, 64];
|
|
36
|
+
export function tileIdFor(rect) {
|
|
37
|
+
return `t${rect.x}_${rect.y}`;
|
|
38
|
+
}
|
|
39
|
+
export function rectKey(rect) {
|
|
40
|
+
return `${rect.x},${rect.y},${rect.width},${rect.height}`;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* plain 兜底的试算顺序:**先 ≤32 的降序**(32 → 24 → 16 → 8),再 >32 的升序(48 → 64)。
|
|
44
|
+
*
|
|
45
|
+
* 为什么不直接取「能整除的最大尺寸」:像素画工作流的默认口径就是 32px,而「最大」
|
|
46
|
+
* 会把 2×2 个 32px 道具并成一个 64px 格 —— 那是**静默改掉用户素材的语义**(一块里
|
|
47
|
+
* 装四个道具),比报错难查得多。48 / 64 只在前面的都试不出来时才轮到。
|
|
48
|
+
*
|
|
49
|
+
* 举例(都是 32px 网格):`256×192` = 8 列 × 6 行 —— 若取最大会得到 64px / 4×3;
|
|
50
|
+
* `96×96` = 3×3 —— 若取最大会得到 48px。注意 `256×160`(8×5)**轮不到这一分支**:
|
|
51
|
+
* 它会先命中上面的 A2 判据(高 = 5 × 32、宽能被 32 整除),那正是内置道具图走
|
|
52
|
+
* `importSampleTileset` 的 `known` 通道显式声明形态、不经自动识别的原因。
|
|
53
|
+
*/
|
|
54
|
+
const PLAIN_PREFERRED_SIZES = [
|
|
55
|
+
...COMMON_TILE_SIZES.filter((size) => size <= 32).reverse(),
|
|
56
|
+
...COMMON_TILE_SIZES.filter((size) => size > 32)
|
|
57
|
+
];
|
|
58
|
+
/**
|
|
59
|
+
* 自动识别切分方式。
|
|
60
|
+
*
|
|
61
|
+
* **先试 A2**(`imageHeight === 5 × 块边长` 且 `imageWidth` 能被块边长整除,从小到大),
|
|
62
|
+
* 免得 64×160 的草地被当成普通网格;再按 `PLAIN_PREFERRED_SIZES` 找能整除两者的
|
|
63
|
+
* 正方形网格;两个都不成立时退回 32×32,并在 reason 里说清为什么要裁像素。
|
|
64
|
+
*
|
|
65
|
+
* ⚠️ **尺寸判据天生有二义性,这里不是 bug**:`256×160` 既可能是「8 变体 × 5 形状的
|
|
66
|
+
* 拼块图」,也可能是「8×5 的 32px 普通网格」(AsLib 靠清单文件里的 `type` 列区分,
|
|
67
|
+
* 光看尺寸分不开)。这里的取舍是**优先给拼块结论**;内置素材那条路不吃这个判据
|
|
68
|
+
* (`mapgen.importSampleTileset` 带显式的 `shape` / `cell` / `animRows`),
|
|
69
|
+
* 用户自己导入的图靠界面上「这块素材怎么用」的下拉改(`saveMapTileset`)。
|
|
70
|
+
*/
|
|
71
|
+
export function detectLayout(imageWidth, imageHeight) {
|
|
72
|
+
for (const size of COMMON_TILE_SIZES) {
|
|
73
|
+
if (imageHeight !== size * A2_SHAPES || imageWidth % size !== 0)
|
|
74
|
+
continue;
|
|
75
|
+
return {
|
|
76
|
+
...layoutFor("a2quad", { width: size, height: size }, imageWidth, imageHeight),
|
|
77
|
+
reason: `识别到:拼块自动连接(${imageWidth / size} 种变体 × ${A2_SHAPES} 种形状)`
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
for (const size of PLAIN_PREFERRED_SIZES) {
|
|
81
|
+
if (imageWidth < size || imageHeight < size)
|
|
82
|
+
continue;
|
|
83
|
+
if (imageWidth % size !== 0 || imageHeight % size !== 0)
|
|
84
|
+
continue;
|
|
85
|
+
return {
|
|
86
|
+
...layoutFor("plain", { width: size, height: size }, imageWidth, imageHeight),
|
|
87
|
+
reason: `识别到:正方形网格 ${size}×${size}(${imageWidth / size} 列 × ${imageHeight / size} 行)`
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
...layoutFor("plain", { width: 32, height: 32 }, imageWidth, imageHeight),
|
|
92
|
+
reason: `没找到能整除 ${imageWidth}×${imageHeight} 的常见尺寸,先按 32×32 切:右侧 / 底部不足一格的部分会被裁掉。`
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* 按指定的形态与格尺寸算切分结果(用户在图集设置里改形态 / 格尺寸时走这条)。
|
|
97
|
+
*
|
|
98
|
+
* 只取**完整的块**:横向 / 纵向不足一个块的像素被裁掉(`Math.floor`),
|
|
99
|
+
* 因为半个块既挑不出象限也对不上邻接。A2 还要求格尺寸是偶数(小格 = 块 / 2)。
|
|
100
|
+
*/
|
|
101
|
+
export function layoutFor(shape, cell, imageWidth, imageHeight) {
|
|
102
|
+
if (!Number.isInteger(cell.width) || !Number.isInteger(cell.height) || cell.width < 1 || cell.height < 1) {
|
|
103
|
+
throw new Error(`图块尺寸必须是正整数,收到 ${cell.width}×${cell.height}`);
|
|
104
|
+
}
|
|
105
|
+
if (shape === "a2quad") {
|
|
106
|
+
if (cell.width % 2 !== 0 || cell.height % 2 !== 0) {
|
|
107
|
+
throw new Error(`A2 拼块要求逻辑块尺寸是偶数(小格 = 逻辑块 / 2),收到 ${cell.width}×${cell.height}`);
|
|
108
|
+
}
|
|
109
|
+
const cols = Math.floor(imageWidth / cell.width);
|
|
110
|
+
// 形状只有 0..4:第 6 行以后永远选不到,切出来只会让序号表里多出用不上的块。
|
|
111
|
+
const rows = Math.min(A2_SHAPES, Math.floor(imageHeight / cell.height));
|
|
112
|
+
if (cols < 1 || rows < 1) {
|
|
113
|
+
return {
|
|
114
|
+
cell: { width: cell.width, height: cell.height },
|
|
115
|
+
shape,
|
|
116
|
+
cols: 0,
|
|
117
|
+
rows: 0,
|
|
118
|
+
count: 0,
|
|
119
|
+
reason: `素材 ${imageWidth}×${imageHeight} 比一个逻辑块 ${cell.width}×${cell.height} 还小,切不出图块。`
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
cell: { width: cell.width, height: cell.height },
|
|
124
|
+
shape,
|
|
125
|
+
cols,
|
|
126
|
+
rows,
|
|
127
|
+
count: cols * 2 * rows * 2,
|
|
128
|
+
reason: `已设为:拼块自动连接(${cols} 种变体 × ${rows} 种形状)`
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
const cols = Math.floor(imageWidth / cell.width);
|
|
132
|
+
const rows = Math.floor(imageHeight / cell.height);
|
|
133
|
+
if (cols < 1 || rows < 1) {
|
|
134
|
+
return {
|
|
135
|
+
cell: { width: cell.width, height: cell.height },
|
|
136
|
+
shape,
|
|
137
|
+
cols: 0,
|
|
138
|
+
rows: 0,
|
|
139
|
+
count: 0,
|
|
140
|
+
reason: `素材 ${imageWidth}×${imageHeight} 比一个图块 ${cell.width}×${cell.height} 还小,切不出图块。`
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const count = cols * rows;
|
|
144
|
+
const reason = shape === "corner16"
|
|
145
|
+
? `已设为:整格自动连接(${cell.width}×${cell.height} 切 ${cols} 列 × ${rows} 行,16 种邻接)`
|
|
146
|
+
: `已设为:正方形网格 ${cell.width}×${cell.height}(${cols} 列 × ${rows} 行)`;
|
|
147
|
+
return { cell: { width: cell.width, height: cell.height }, shape, cols, rows, count, reason };
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* 按切分结果生成图块表,并**保留已有元数据**。
|
|
151
|
+
*
|
|
152
|
+
* 保留的判据是矩形派生的 id(`tileIdFor`):改格尺寸后仍然存在的矩形**把旧 tile 上的
|
|
153
|
+
* 字段原样带过来** —— 界面上按位序配好的 16 张连接块、改过的名字不会因为一次
|
|
154
|
+
* 「改格尺寸」全被抹掉。消失的 id 丢弃,新出现的给默认值。
|
|
155
|
+
*
|
|
156
|
+
* ⚠️ 这里**不做白名单拷贝**,只覆盖由几何算出来的那几项(`id` / `rect` / `shape` /
|
|
157
|
+
* `variant` / `frame`)。白名单是旧实现踩过的坑:`MapTile` 以后加一个字段
|
|
158
|
+
* (锚点、通行、标签……),白名单没跟上就会在每次重切时静默清空 —— 而且只有
|
|
159
|
+
* 「改过那个字段、又改了格尺寸」的用户才会遇到。反过来,几何派生项**必须**覆盖:
|
|
160
|
+
* 沿用旧值会让块号与 rect 对不上,静默错位。
|
|
161
|
+
*
|
|
162
|
+
* 顺序(= `flatTiles` 的 1-based 序号顺序,改了就等同于换了一套语义值):
|
|
163
|
+
* · plain / corner16:行优先逐格;`animRows` 时 `frame` = 行号(同列共用一个逻辑块)
|
|
164
|
+
* · a2quad:小格行优先;`shape` = 块行号、`variant` = 块列号、`frame` = 0
|
|
165
|
+
*/
|
|
166
|
+
export function buildTiles(input, previous = []) {
|
|
167
|
+
const { shape, cell, imageWidth, imageHeight } = input;
|
|
168
|
+
const previousById = new Map(previous.map((tile) => [tile.id, tile]));
|
|
169
|
+
const tileOf = (rect, shapeAt, variant, frame) => {
|
|
170
|
+
const id = tileIdFor(rect);
|
|
171
|
+
const old = previousById.get(id);
|
|
172
|
+
// 先整份继承旧 tile(含以后新增的字段),再覆盖几何派生项。
|
|
173
|
+
const tile = old === undefined ? { id, rect, name: id } : { ...old };
|
|
174
|
+
tile.id = id;
|
|
175
|
+
tile.rect = rect;
|
|
176
|
+
if (typeof tile.name !== "string" || tile.name === "")
|
|
177
|
+
tile.name = id;
|
|
178
|
+
if (shapeAt === undefined)
|
|
179
|
+
delete tile.shape;
|
|
180
|
+
else
|
|
181
|
+
tile.shape = shapeAt;
|
|
182
|
+
if (variant === undefined)
|
|
183
|
+
delete tile.variant;
|
|
184
|
+
else
|
|
185
|
+
tile.variant = variant;
|
|
186
|
+
tile.frame = frame;
|
|
187
|
+
return tile;
|
|
188
|
+
};
|
|
189
|
+
if (shape === "a2quad") {
|
|
190
|
+
if (cell.width % 2 !== 0 || cell.height % 2 !== 0) {
|
|
191
|
+
throw new Error(`A2 拼块要求逻辑块尺寸是偶数(小格 = 逻辑块 / 2),收到 ${cell.width}×${cell.height}`);
|
|
192
|
+
}
|
|
193
|
+
const smallWidth = cell.width / 2;
|
|
194
|
+
const smallHeight = cell.height / 2;
|
|
195
|
+
// 只切完整的逻辑块:横向留半块的话,那一列凑不齐左右象限(AsLib 要求小格列数是偶数)。
|
|
196
|
+
const smallCols = Math.floor(imageWidth / cell.width) * 2;
|
|
197
|
+
const smallRows = Math.min(A2_SHAPES, Math.floor(imageHeight / cell.height)) * 2;
|
|
198
|
+
const tiles = [];
|
|
199
|
+
for (let smallRow = 0; smallRow < smallRows; smallRow++) {
|
|
200
|
+
for (let smallCol = 0; smallCol < smallCols; smallCol++) {
|
|
201
|
+
tiles.push(tileOf({ x: smallCol * smallWidth, y: smallRow * smallHeight, width: smallWidth, height: smallHeight }, Math.floor(smallRow / 2), Math.floor(smallCol / 2), 0));
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return tiles;
|
|
205
|
+
}
|
|
206
|
+
const cols = Math.floor(imageWidth / cell.width);
|
|
207
|
+
const rows = Math.floor(imageHeight / cell.height);
|
|
208
|
+
const animRows = input.animRows === true;
|
|
209
|
+
const tiles = [];
|
|
210
|
+
for (let row = 0; row < rows; row++) {
|
|
211
|
+
for (let col = 0; col < cols; col++) {
|
|
212
|
+
tiles.push(tileOf({ x: col * cell.width, y: row * cell.height, width: cell.width, height: cell.height }, undefined, undefined, animRows ? row : 0));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return tiles;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* 展平成一个全项目通用的索引。
|
|
219
|
+
*
|
|
220
|
+
* 顺序 = 图集顺序 → `tileset.tiles` 数组顺序,**因此只要不动图集顺序与切分参数,
|
|
221
|
+
* 序号就稳定**;这也是 `applyOps` 里存的序号能跨会话读回来的前提。
|
|
222
|
+
* 序号的唯一真源是这里,别的任何地方都不许自己按数组下标算。
|
|
223
|
+
*/
|
|
224
|
+
export function flatTiles(tilesets) {
|
|
225
|
+
const out = [];
|
|
226
|
+
let index = 1;
|
|
227
|
+
for (const tileset of tilesets) {
|
|
228
|
+
for (const tile of tileset.tiles) {
|
|
229
|
+
out.push({ index, tilesetId: tileset.id, tile, value: index });
|
|
230
|
+
index++;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
export function flatIndexByValue(tilesets) {
|
|
236
|
+
return new Map(flatTiles(tilesets).map((flat) => [flat.value, flat]));
|
|
237
|
+
}
|
|
238
|
+
// ── 图像尺寸探测 / 裁剪 ──────────────────────────────────────────────────
|
|
239
|
+
/** 从文件头拿尺寸;PNG 之外的类型回落到 ffmpeg(见 `bitmap.probeImageSize`)。 */
|
|
240
|
+
export function sizeFromBytes(bytes) {
|
|
241
|
+
return pngSize(bytes);
|
|
242
|
+
}
|
|
243
|
+
/** 给验收 / 界面用的图块位图(裁剪出一块)。 */
|
|
244
|
+
export function cropTile(source, rect) {
|
|
245
|
+
const width = Math.max(1, Math.min(rect.width, source.width - rect.x));
|
|
246
|
+
const height = Math.max(1, Math.min(rect.height, source.height - rect.y));
|
|
247
|
+
const rgba = Buffer.alloc(width * height * 4);
|
|
248
|
+
for (let y = 0; y < height; y++) {
|
|
249
|
+
const from = ((rect.y + y) * source.width + rect.x) * 4;
|
|
250
|
+
source.rgba.copy(rgba, y * width * 4, from, from + width * 4);
|
|
251
|
+
}
|
|
252
|
+
return { width, height, rgba };
|
|
253
|
+
}
|
package/lib/media.js
CHANGED
|
@@ -196,6 +196,40 @@ export async function makeThumbnail(source, dest, maxEdge = 768) {
|
|
|
196
196
|
dest
|
|
197
197
|
], 120000);
|
|
198
198
|
}
|
|
199
|
+
/**
|
|
200
|
+
* 按**文件头**认一段本地视频的容器(用户自选的本地视频走这条路)。
|
|
201
|
+
*
|
|
202
|
+
* 为什么不看扩展名:从手机 / 剪辑软件 / 聊天工具里拿到的文件经常被改名或根本
|
|
203
|
+
* 没有正确的后缀(`.mp4` 其实是 MOV、`.bin` 其实是 MP4)。这里只在本机交给
|
|
204
|
+
* ffmpeg 解码,容器认错了不会当场报错,而是**抽帧时**才失败——那时用户已经
|
|
205
|
+
* 以为「导入成功了」。
|
|
206
|
+
*
|
|
207
|
+
* 认三种,覆盖游戏素材的常见来源:
|
|
208
|
+
* - ISO BMFF(MP4 / MOV / M4V):第 4~8 字节是 `ftyp`,再按 brand 区分 MOV 与 MP4;
|
|
209
|
+
* - Matroska / WebM:EBML 头 `1A 45 DF A3`(两者同族,统一按 webm 存);
|
|
210
|
+
* - AVI:`RIFF` + 第 8~12 字节 `AVI `。
|
|
211
|
+
*
|
|
212
|
+
* 返回的 `ext` 直接当落盘后缀,所以它必须是 ffmpeg 认得的容器名。
|
|
213
|
+
*/
|
|
214
|
+
export function sniffVideo(base64) {
|
|
215
|
+
// 48 字节足够覆盖三种文件头里的判别字段。
|
|
216
|
+
const head = Buffer.from(base64.slice(0, 64), "base64");
|
|
217
|
+
if (head.length >= 12 && head.toString("ascii", 4, 8) === "ftyp") {
|
|
218
|
+
const brand = head.toString("ascii", 8, 12).trim().toLowerCase();
|
|
219
|
+
if (brand === "qt")
|
|
220
|
+
return { ext: "mov", mime: "video/quicktime", label: "MOV" };
|
|
221
|
+
if (brand === "m4v" || brand === "m4vh")
|
|
222
|
+
return { ext: "m4v", mime: "video/x-m4v", label: "M4V" };
|
|
223
|
+
return { ext: "mp4", mime: "video/mp4", label: "MP4" };
|
|
224
|
+
}
|
|
225
|
+
if (head.length >= 4 && head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) {
|
|
226
|
+
return { ext: "webm", mime: "video/webm", label: "WebM / MKV" };
|
|
227
|
+
}
|
|
228
|
+
if (head.length >= 12 && head.toString("ascii", 0, 4) === "RIFF" && head.toString("ascii", 8, 12) === "AVI ") {
|
|
229
|
+
return { ext: "avi", mime: "video/x-msvideo", label: "AVI" };
|
|
230
|
+
}
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
199
233
|
/** 读取文件并组装成 data URI(Ark 参考图用)。 */
|
|
200
234
|
export async function toDataUri(file, mime) {
|
|
201
235
|
const bytes = await readFile(file);
|
package/lib/pipeline.js
CHANGED
|
@@ -21,11 +21,12 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
|
21
21
|
import { dirname } from "node:path";
|
|
22
22
|
import { loadConfig } from "./config.js";
|
|
23
23
|
import { DEFAULT_TURN_PROMPT, DIRECTIONS, DIRECTION_KEYS, TURN_DIRECTION_DEFAULT, TURN_FRAME_COUNT_MAX, TURN_FRAME_COUNT_MIN, directionOf, turnOrder } from "./directions.js";
|
|
24
|
-
import {
|
|
24
|
+
import { assertImageProviderReady, generateImageWithProvider, imageModelOf, imageSizeOf, imageWatermarkOf } from "./imageprovider.js";
|
|
25
25
|
import { downloadVideo, queryVideo, retrieveFile, submitVideo } from "./minimax.js";
|
|
26
|
-
import { extractFrames, mimeOf, toDataUri, toJpegDataUri } from "./media.js";
|
|
26
|
+
import { extractFrames, mimeOf, sniffVideo, toDataUri, toJpegDataUri } from "./media.js";
|
|
27
27
|
import { composeSheet, keyGreen } from "./chroma.js";
|
|
28
28
|
import { encodePng } from "./png.js";
|
|
29
|
+
import { zipEntries } from "./zip.js";
|
|
29
30
|
import { assetPath, freshPicks, log, patchProject, readProject, referenceFiles } from "./store.js";
|
|
30
31
|
/** 生图的依赖分层:同一层内可并发,层与层之间必须按序。 */
|
|
31
32
|
const IMAGE_STAGES = [
|
|
@@ -51,14 +52,6 @@ export function listJobs(projectId) {
|
|
|
51
52
|
function messageOf(error) {
|
|
52
53
|
return error instanceof Error ? error.message : String(error);
|
|
53
54
|
}
|
|
54
|
-
function arkRequest(config) {
|
|
55
|
-
return {
|
|
56
|
-
baseUrl: config.arkBaseUrl,
|
|
57
|
-
apiKey: config.arkApiKey,
|
|
58
|
-
model: config.arkModel,
|
|
59
|
-
timeoutMs: config.arkTimeoutMs
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
55
|
function miniMaxRequest(config) {
|
|
63
56
|
return {
|
|
64
57
|
baseUrl: config.minimaxBaseUrl,
|
|
@@ -140,6 +133,8 @@ async function generateOne(projectId, key, promptOverride) {
|
|
|
140
133
|
if (project === undefined)
|
|
141
134
|
throw new Error(`项目不存在:${projectId}`);
|
|
142
135
|
const config = await loadConfig();
|
|
136
|
+
// 后端没配好就不要往下走:这一步会真实计费,早失败比「跑到一半报错」好。
|
|
137
|
+
assertImageProviderReady(config);
|
|
143
138
|
const basePrompt = (promptOverride ?? project.prompts.images[key] ?? "").trim();
|
|
144
139
|
if (basePrompt === "")
|
|
145
140
|
throw new Error("提示词为空,请先填写生图提示词");
|
|
@@ -161,12 +156,11 @@ async function generateOne(projectId, key, promptOverride) {
|
|
|
161
156
|
const startedAt = Date.now();
|
|
162
157
|
try {
|
|
163
158
|
const images = await Promise.all(refs.map((file) => toDataUri(file, mimeOf(file))));
|
|
164
|
-
const result = await
|
|
165
|
-
...arkRequest(config),
|
|
159
|
+
const result = await generateImageWithProvider({
|
|
166
160
|
prompt,
|
|
167
161
|
images,
|
|
168
|
-
size: config
|
|
169
|
-
watermark: config
|
|
162
|
+
size: imageSizeOf(config),
|
|
163
|
+
watermark: imageWatermarkOf(config)
|
|
170
164
|
});
|
|
171
165
|
const relative = `images/${key}.${result.ext}`;
|
|
172
166
|
await mkdir(dirname(assetPath(projectId, relative)), { recursive: true });
|
|
@@ -179,7 +173,7 @@ async function generateOne(projectId, key, promptOverride) {
|
|
|
179
173
|
file: relative,
|
|
180
174
|
approved: false,
|
|
181
175
|
stale: false,
|
|
182
|
-
model: config
|
|
176
|
+
model: imageModelOf(config),
|
|
183
177
|
elapsedMs: elapsed,
|
|
184
178
|
updatedAt: Date.now()
|
|
185
179
|
};
|
|
@@ -642,6 +636,194 @@ export async function setImageMode(projectId, mode) {
|
|
|
642
636
|
log(project, "info", mode === "turn" ? "阶段①改用「转圈截帧」" : "阶段①改用「逐方向生图」");
|
|
643
637
|
});
|
|
644
638
|
}
|
|
639
|
+
// ── 本地自选视频:阶段①(转圈)与阶段②(八段行走)的第三条输入 ────────────
|
|
640
|
+
//
|
|
641
|
+
// 两处「需要生成视频」的地方都可以直接**自己选一段本地视频**,跳过远程生成:
|
|
642
|
+
// · `turn` → 一段原地转圈的绿幕视频(导入后自动抽候选帧、切八张方向图);
|
|
643
|
+
// · 八个方向 key → 某一段行走视频(导入后照旧在第 3 步抽帧)。
|
|
644
|
+
//
|
|
645
|
+
// 产物与远端生成的**完全同形**(同一个 `videos/` 目录、同一个 VideoNode 形状,
|
|
646
|
+
// 只有 `origin: "local"` 这一个字段不同),所以阶段 3、4 一行都不用改。
|
|
647
|
+
// 这条链路只在本机跑 ffmpeg,没有任何网络调用,因此上限比「发给模型」宽得多。
|
|
648
|
+
/** 本地自选视频的大小上限(只受本机内存与传输体量限制,见 `importLocalVideo`)。 */
|
|
649
|
+
export const LOCAL_VIDEO_MAX_BYTES = 100 * 1024 * 1024;
|
|
650
|
+
/** 落盘用的文件名安全化:用户给的名字会直接拼进项目目录。 */
|
|
651
|
+
function safeFileStem(input, fallback) {
|
|
652
|
+
const cleaned = (input ?? "")
|
|
653
|
+
.replace(/[^\p{L}\p{N}_-]+/gu, "_")
|
|
654
|
+
.replace(/^_+|_+$/g, "")
|
|
655
|
+
.slice(0, 40);
|
|
656
|
+
return cleaned === "" ? fallback : cleaned;
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* 把一段本地视频放进 `turn` 或某个方向的槽位。
|
|
660
|
+
*
|
|
661
|
+
* 除了写文件,还要做三件“不写就会静默坏掉”的事:
|
|
662
|
+
* 1. **作废旧产物**:这个槽位原来的视频、它抽出来的帧、以及由那些帧合成的
|
|
663
|
+
* 整图都属于上一段视频。尤其是抽帧缓存 `raw.bin`,留着就会拿旧帧去合成
|
|
664
|
+
* (界面看着一切正常,只是人物朝向对不上)。
|
|
665
|
+
* 2. **摘掉远端任务号**:如果这一刻正好有一个远端任务在跑,它的结果稍后会
|
|
666
|
+
* 把我们的本地视频**直接覆盖掉**。写 `status: ready` 并清掉 `taskId`,
|
|
667
|
+
* 轮询器下一轮就不会再认领它(单次已经在下载途中的那一轮仍可能落盘,
|
|
668
|
+
* 所以日志里明确写一条)。
|
|
669
|
+
* 3. **转圈模式顺手抽帧**:远端路径也是「视频到手就抽候选帧」,这里保持一致,
|
|
670
|
+
* 否则用户导入完还得自己找「抽取候选帧」按钮,而且不知道时间轴为什么是空的。
|
|
671
|
+
*/
|
|
672
|
+
export async function importLocalVideo(projectId, key, name, base64) {
|
|
673
|
+
const project = await readProject(projectId);
|
|
674
|
+
if (project === undefined)
|
|
675
|
+
throw new Error(`项目不存在:${projectId}`);
|
|
676
|
+
const isTurn = key === "turn";
|
|
677
|
+
if (!isTurn && directionOf(key) === undefined) {
|
|
678
|
+
throw new Error(`未知方位:${key}(可用 turn 或 ${DIRECTION_KEYS.join(" / ")})`);
|
|
679
|
+
}
|
|
680
|
+
const clean = base64.replace(/^data:[^;]+;base64,/, "");
|
|
681
|
+
if (clean.trim() === "")
|
|
682
|
+
throw new Error("没有收到视频数据");
|
|
683
|
+
const bytes = Buffer.from(clean, "base64");
|
|
684
|
+
if (bytes.length === 0)
|
|
685
|
+
throw new Error("视频数据为空");
|
|
686
|
+
if (bytes.length > LOCAL_VIDEO_MAX_BYTES) {
|
|
687
|
+
throw new Error(`视频 ${(bytes.length / 1024 / 1024).toFixed(1)}MB 超过上限 ${Math.round(LOCAL_VIDEO_MAX_BYTES / 1024 / 1024)}MB,请先压缩或裁剪`);
|
|
688
|
+
}
|
|
689
|
+
const sniffed = sniffVideo(clean);
|
|
690
|
+
if (sniffed === undefined) {
|
|
691
|
+
throw new Error("无法识别的视频格式(支持 MP4 / MOV / M4V / WebM / MKV / AVI)");
|
|
692
|
+
}
|
|
693
|
+
const originalName = safeFileStem(name.replace(/\.[^.]+$/, ""), `local-${key}`) + "." + sniffed.ext;
|
|
694
|
+
const relative = `videos/${isTurn ? "turn" : key}.${sniffed.ext}`;
|
|
695
|
+
const mb = (bytes.length / 1024 / 1024).toFixed(1);
|
|
696
|
+
await mkdir(dirname(assetPath(projectId, relative)), { recursive: true });
|
|
697
|
+
await writeFile(assetPath(projectId, relative), bytes);
|
|
698
|
+
if (isTurn) {
|
|
699
|
+
await patchProject(projectId, (current) => {
|
|
700
|
+
const droppedTask = current.turn.video?.taskId;
|
|
701
|
+
current.turn.video = {
|
|
702
|
+
status: "ready",
|
|
703
|
+
file: relative,
|
|
704
|
+
approved: false,
|
|
705
|
+
// 远端状态这一栏在界面上同时是「这段视频的来路」,本地导入就照实写。
|
|
706
|
+
remoteStatus: "本地视频",
|
|
707
|
+
origin: "local",
|
|
708
|
+
originalName,
|
|
709
|
+
// 首帧只对「图生视频」有意义,本地视频没有输入图,清掉免得界面指向一张无关的图。
|
|
710
|
+
firstFrame: undefined,
|
|
711
|
+
updatedAt: Date.now()
|
|
712
|
+
};
|
|
713
|
+
if (current.turn.frames.frames.length > 0)
|
|
714
|
+
current.turn.frames.stale = true;
|
|
715
|
+
log(current, "info", `已选用本地视频作为转圈视频:${originalName}(${mb} MB)`);
|
|
716
|
+
if (droppedTask !== undefined) {
|
|
717
|
+
log(current, "warn", `原先的转圈视频远端任务(${droppedTask})已作废,它的结果不会再被采用`);
|
|
718
|
+
}
|
|
719
|
+
});
|
|
720
|
+
const started = startTurnFrames(projectId);
|
|
721
|
+
return {
|
|
722
|
+
key,
|
|
723
|
+
file: relative,
|
|
724
|
+
name: originalName,
|
|
725
|
+
bytes: bytes.length,
|
|
726
|
+
extractStarted: started.started === true,
|
|
727
|
+
extractReason: started.reason
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
const label = directionOf(key)?.label ?? key;
|
|
731
|
+
await patchProject(projectId, (current) => {
|
|
732
|
+
const droppedTask = current.videos[key]?.taskId;
|
|
733
|
+
current.videos[key] = {
|
|
734
|
+
status: "ready",
|
|
735
|
+
file: relative,
|
|
736
|
+
approved: false,
|
|
737
|
+
remoteStatus: "本地视频",
|
|
738
|
+
origin: "local",
|
|
739
|
+
originalName,
|
|
740
|
+
updatedAt: Date.now()
|
|
741
|
+
};
|
|
742
|
+
// 旧帧与整图都属于上一段视频:不清掉就会拿另一段视频的帧继续往下走。
|
|
743
|
+
current.frames[key] = { status: "empty", frames: [], keyed: [], approved: false };
|
|
744
|
+
current.sheet = { status: "empty", approved: false };
|
|
745
|
+
log(current, "info", `已选用本地视频作为「${label}」的行走视频:${originalName}(${mb} MB),需要到第 3 步重新抽帧`);
|
|
746
|
+
if (droppedTask !== undefined) {
|
|
747
|
+
log(current, "warn", `「${label}」原先的远端任务(${droppedTask})已作废,它的结果不会再被采用`);
|
|
748
|
+
}
|
|
749
|
+
});
|
|
750
|
+
return { key, file: relative, name: originalName, bytes: bytes.length };
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* 这个项目里所有**中间图片**的相对路径。
|
|
754
|
+
*
|
|
755
|
+
* 「中间」= 一路生成下来留下的每一张图:八方向绿幕图、转圈候选帧与整圈条带、
|
|
756
|
+
* 每段视频抽出来的绿幕帧与它的手动选帧候选、抠完绿幕的帧、以及最后合成的整图。
|
|
757
|
+
* 源图(用户自己的输入)不算,它不是这条路产出的东西。
|
|
758
|
+
*
|
|
759
|
+
* 顺序刻意按阶段走(① → ② → ③ → ④),解压出来的人眼一翻就能对上流程。
|
|
760
|
+
*/
|
|
761
|
+
export function intermediateImagePaths(project) {
|
|
762
|
+
const out = [];
|
|
763
|
+
const push = (value) => {
|
|
764
|
+
if (typeof value === "string" && value !== "")
|
|
765
|
+
out.push(value);
|
|
766
|
+
};
|
|
767
|
+
for (const key of DIRECTION_KEYS) {
|
|
768
|
+
push(project.images[key]?.file);
|
|
769
|
+
const node = project.frames[key];
|
|
770
|
+
for (const file of node?.frames ?? [])
|
|
771
|
+
push(file);
|
|
772
|
+
for (const file of node?.keyed ?? [])
|
|
773
|
+
push(file);
|
|
774
|
+
for (const file of node?.candidates?.frames ?? [])
|
|
775
|
+
push(file);
|
|
776
|
+
push(node?.strip);
|
|
777
|
+
push(node?.candidates?.strip);
|
|
778
|
+
}
|
|
779
|
+
push(project.turn?.frames?.strip);
|
|
780
|
+
for (const file of project.turn?.frames?.frames ?? [])
|
|
781
|
+
push(file);
|
|
782
|
+
push(project.sheet?.file);
|
|
783
|
+
push(project.sheet?.thumb);
|
|
784
|
+
return [...new Set(out)];
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* 把所有中间图片打成一个 zip,落在 `out/` 下(静态资源路由可直接下载)。
|
|
788
|
+
*
|
|
789
|
+
* 为什么是 zip 而不是几十个下载链接:转圈模式的候选帧一抽就是 32~64 张,
|
|
790
|
+
* 一张一个按钮既点不完也看不清。包里保留**项目内的相对路径**
|
|
791
|
+
* (`images/front.png`、`turn/frames/f00.png`、`frames/front/f00.png`…),
|
|
792
|
+
* 这样解压出来还能和项目目录对上号。
|
|
793
|
+
*/
|
|
794
|
+
export async function exportImages(projectId) {
|
|
795
|
+
const project = await readProject(projectId);
|
|
796
|
+
if (project === undefined)
|
|
797
|
+
throw new Error(`项目不存在:${projectId}`);
|
|
798
|
+
const wanted = intermediateImagePaths(project);
|
|
799
|
+
if (wanted.length === 0) {
|
|
800
|
+
throw new Error("还没有任何图片可保存:先在阶段①出绿幕图,或在阶段③抽取序列帧");
|
|
801
|
+
}
|
|
802
|
+
const entries = [];
|
|
803
|
+
let bytes = 0;
|
|
804
|
+
let skipped = 0;
|
|
805
|
+
for (const relative of wanted) {
|
|
806
|
+
try {
|
|
807
|
+
const data = await readFile(assetPath(projectId, relative));
|
|
808
|
+
entries.push({ path: relative, data });
|
|
809
|
+
bytes += data.length;
|
|
810
|
+
}
|
|
811
|
+
catch {
|
|
812
|
+
// 单张读不到不该让整包失败(可能是手删过的旧记录):跳过并如实报数。
|
|
813
|
+
skipped++;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
if (entries.length === 0)
|
|
817
|
+
throw new Error("这些图片文件都不在了,请重新生成或重新抽帧");
|
|
818
|
+
const zip = zipEntries(entries);
|
|
819
|
+
const relative = `out/${safeFileStem(project.name, project.id)}-images.zip`;
|
|
820
|
+
await mkdir(dirname(assetPath(projectId, relative)), { recursive: true });
|
|
821
|
+
await writeFile(assetPath(projectId, relative), zip);
|
|
822
|
+
await patchProject(projectId, (current) => {
|
|
823
|
+
log(current, "info", `已打包 ${entries.length} 张图片(${(zip.length / 1024 / 1024).toFixed(1)} MB)${skipped > 0 ? `,${skipped} 张读不到已跳过` : ""}`);
|
|
824
|
+
});
|
|
825
|
+
return { file: relative, count: entries.length, skipped, bytes };
|
|
826
|
+
}
|
|
645
827
|
// ── 阶段 2:八段视频 ──────────────────────────────────────────────────────
|
|
646
828
|
export function startVideos(projectId, keys) {
|
|
647
829
|
const started = kick(projectId, "videos:submit", "提交视频任务", async () => {
|