@xenra/dsh-draworld 0.0.0-stage → 0.1.39
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/LICENSE +21 -0
- package/README.md +271 -2
- package/client.js +4697 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +7 -0
- package/index.js +2907 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +63 -4
- package/pixelops.js +420 -0
- package/pixels.js +926 -0
package/pixels.js
ADDED
|
@@ -0,0 +1,926 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宿主侧像素引擎(无界面兜底)。
|
|
3
|
+
*
|
|
4
|
+
* 前端(浏览器 <canvas>)不在的时候,copy / trace / palette / pick / compare / fill / view 这些
|
|
5
|
+
* 也要能算:这里用纯 JS 解码 PNG、编码 PNG,再把笔迹用简单胶囊笔触光栅化出来。
|
|
6
|
+
* 第三方依赖为零,只用到 node 自带的 zlib 与 child_process(非 PNG 的输入靠系统转换一次)。
|
|
7
|
+
*
|
|
8
|
+
* 注意:光栅化是「圆头近似」,跟浏览器里 32 支笔刷的真实引擎有差别,
|
|
9
|
+
* 所以 compare 的数字在无界面模式下是近似值;有面板时仍优先用面板算。
|
|
10
|
+
*/
|
|
11
|
+
import zlib from "node:zlib";
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import os from "node:os";
|
|
15
|
+
import { execFile } from "node:child_process";
|
|
16
|
+
|
|
17
|
+
// ---------------------------------------------------------------- PNG 编解码
|
|
18
|
+
|
|
19
|
+
const PNG_SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
20
|
+
|
|
21
|
+
function paeth(a, b, c) {
|
|
22
|
+
const p = a + b - c;
|
|
23
|
+
const pa = Math.abs(p - a);
|
|
24
|
+
const pb = Math.abs(p - b);
|
|
25
|
+
const pc = Math.abs(p - c);
|
|
26
|
+
if (pa <= pb && pa <= pc) return a;
|
|
27
|
+
if (pb <= pc) return b;
|
|
28
|
+
return c;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 解一张 8bit PNG(灰度 / RGB / RGBA / 灰度+alpha),返回 { w, h, data(RGBA) }。 */
|
|
32
|
+
export function decodePng(buf) {
|
|
33
|
+
if (!PNG_SIG.equals(buf.subarray(0, 8))) throw new Error("不是 PNG(签名不对)");
|
|
34
|
+
let off = 8;
|
|
35
|
+
let width = 0;
|
|
36
|
+
let height = 0;
|
|
37
|
+
let bitDepth = 8;
|
|
38
|
+
let colorType = 6;
|
|
39
|
+
let interlace = 0;
|
|
40
|
+
const idat = [];
|
|
41
|
+
while (off + 8 <= buf.length) {
|
|
42
|
+
const len = buf.readUInt32BE(off);
|
|
43
|
+
const type = buf.toString("ascii", off + 4, off + 8);
|
|
44
|
+
const body = buf.subarray(off + 8, off + 8 + len);
|
|
45
|
+
if (type === "IHDR") {
|
|
46
|
+
width = body.readUInt32BE(0);
|
|
47
|
+
height = body.readUInt32BE(4);
|
|
48
|
+
bitDepth = body[8];
|
|
49
|
+
colorType = body[9];
|
|
50
|
+
interlace = body[12];
|
|
51
|
+
} else if (type === "IDAT") {
|
|
52
|
+
idat.push(body);
|
|
53
|
+
} else if (type === "IEND") {
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
off += 12 + len;
|
|
57
|
+
}
|
|
58
|
+
if (!width || !height) throw new Error("PNG 缺 IHDR");
|
|
59
|
+
if (bitDepth !== 8) throw new Error(`PNG 位深 ${bitDepth} 暂不支持(只支持 8bit)`);
|
|
60
|
+
if (interlace !== 0) throw new Error("PNG 是隔行扫描,暂不支持");
|
|
61
|
+
const channels = colorType === 0 ? 1 : colorType === 2 ? 3 : colorType === 4 ? 2 : colorType === 6 ? 4 : 0;
|
|
62
|
+
if (!channels) throw new Error(`PNG 颜色类型 ${colorType} 暂不支持(调色板图请另存成真彩色)`);
|
|
63
|
+
const raw = zlib.inflateSync(Buffer.concat(idat));
|
|
64
|
+
const stride = width * channels;
|
|
65
|
+
const pixels = Buffer.alloc(stride * height);
|
|
66
|
+
const bpp = channels;
|
|
67
|
+
for (let y = 0; y < height; y += 1) {
|
|
68
|
+
const filter = raw[y * (stride + 1)];
|
|
69
|
+
const src = raw.subarray(y * (stride + 1) + 1, y * (stride + 1) + 1 + stride);
|
|
70
|
+
const row = pixels.subarray(y * stride, (y + 1) * stride);
|
|
71
|
+
const prev = y > 0 ? pixels.subarray((y - 1) * stride, y * stride) : null;
|
|
72
|
+
for (let i = 0; i < stride; i += 1) {
|
|
73
|
+
const a = i >= bpp ? row[i - bpp] : 0;
|
|
74
|
+
const b = prev ? prev[i] : 0;
|
|
75
|
+
const c = prev && i >= bpp ? prev[i - bpp] : 0;
|
|
76
|
+
let v = src[i];
|
|
77
|
+
if (filter === 1) v += a;
|
|
78
|
+
else if (filter === 2) v += b;
|
|
79
|
+
else if (filter === 3) v += (a + b) >> 1;
|
|
80
|
+
else if (filter === 4) v += paeth(a, b, c);
|
|
81
|
+
row[i] = v & 0xff;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const data = new Uint8ClampedArray(width * height * 4);
|
|
85
|
+
for (let i = 0; i < width * height; i += 1) {
|
|
86
|
+
if (channels === 4) {
|
|
87
|
+
data[i * 4] = pixels[i * 4];
|
|
88
|
+
data[i * 4 + 1] = pixels[i * 4 + 1];
|
|
89
|
+
data[i * 4 + 2] = pixels[i * 4 + 2];
|
|
90
|
+
data[i * 4 + 3] = pixels[i * 4 + 3];
|
|
91
|
+
} else if (channels === 3) {
|
|
92
|
+
data[i * 4] = pixels[i * 3];
|
|
93
|
+
data[i * 4 + 1] = pixels[i * 3 + 1];
|
|
94
|
+
data[i * 4 + 2] = pixels[i * 3 + 2];
|
|
95
|
+
data[i * 4 + 3] = 255;
|
|
96
|
+
} else if (channels === 2) {
|
|
97
|
+
const g = pixels[i * 2];
|
|
98
|
+
data[i * 4] = g;
|
|
99
|
+
data[i * 4 + 1] = g;
|
|
100
|
+
data[i * 4 + 2] = g;
|
|
101
|
+
data[i * 4 + 3] = pixels[i * 2 + 1];
|
|
102
|
+
} else {
|
|
103
|
+
const g = pixels[i];
|
|
104
|
+
data[i * 4] = g;
|
|
105
|
+
data[i * 4 + 1] = g;
|
|
106
|
+
data[i * 4 + 2] = g;
|
|
107
|
+
data[i * 4 + 3] = 255;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { width, height, data };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function crc32(buf) {
|
|
114
|
+
if (!crc32.table) {
|
|
115
|
+
const t = new Int32Array(256);
|
|
116
|
+
for (let n = 0; n < 256; n += 1) {
|
|
117
|
+
let c = n;
|
|
118
|
+
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
119
|
+
t[n] = c;
|
|
120
|
+
}
|
|
121
|
+
crc32.table = t;
|
|
122
|
+
}
|
|
123
|
+
let c = -1;
|
|
124
|
+
for (let i = 0; i < buf.length; i += 1) c = crc32.table[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
|
125
|
+
return (c ^ -1) >>> 0;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function pngChunk(type, body) {
|
|
129
|
+
const head = Buffer.alloc(8);
|
|
130
|
+
head.writeUInt32BE(body.length, 0);
|
|
131
|
+
head.write(type, 4, "ascii");
|
|
132
|
+
const crc = Buffer.alloc(4);
|
|
133
|
+
crc.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, "ascii"), body])), 0);
|
|
134
|
+
return Buffer.concat([head, body, crc]);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** RGBA → PNG(不压缩策略用固定 filter 0,速度快)。 */
|
|
138
|
+
export function encodePng(rgba, width, height) {
|
|
139
|
+
const stride = width * 4;
|
|
140
|
+
const raw = Buffer.alloc((stride + 1) * height);
|
|
141
|
+
for (let y = 0; y < height; y += 1) {
|
|
142
|
+
raw[y * (stride + 1)] = 0;
|
|
143
|
+
Buffer.from(rgba.buffer, rgba.byteOffset + y * stride, stride).copy(raw, y * (stride + 1) + 1);
|
|
144
|
+
}
|
|
145
|
+
const ihdr = Buffer.alloc(13);
|
|
146
|
+
ihdr.writeUInt32BE(width, 0);
|
|
147
|
+
ihdr.writeUInt32BE(height, 4);
|
|
148
|
+
ihdr[8] = 8;
|
|
149
|
+
ihdr[9] = 6;
|
|
150
|
+
ihdr[10] = 0;
|
|
151
|
+
ihdr[11] = 0;
|
|
152
|
+
ihdr[12] = 0;
|
|
153
|
+
return Buffer.concat([
|
|
154
|
+
PNG_SIG,
|
|
155
|
+
pngChunk("IHDR", ihdr),
|
|
156
|
+
pngChunk("IDAT", zlib.deflateSync(raw, { level: 6 })),
|
|
157
|
+
pngChunk("IEND", Buffer.alloc(0)),
|
|
158
|
+
]);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ---------------------------------------------------------------- 读图(PNG 直接解,其它走系统转换)
|
|
162
|
+
|
|
163
|
+
const IMAGE_CACHE = new Map(); // path -> { mtime, width, height, data }
|
|
164
|
+
|
|
165
|
+
function convertToPng(src, dst) {
|
|
166
|
+
const ps = [
|
|
167
|
+
"-NoProfile",
|
|
168
|
+
"-Command",
|
|
169
|
+
`Add-Type -AssemblyName System.Drawing; $img=[System.Drawing.Image]::FromFile('${src.replace(/'/g, "''")}'); ` +
|
|
170
|
+
`$bmp=New-Object System.Drawing.Bitmap($img.Width,$img.Height); $g=[System.Drawing.Graphics]::FromImage($bmp); ` +
|
|
171
|
+
`$g.DrawImage($img,0,0,$img.Width,$img.Height); $bmp.Save('${dst.replace(/'/g, "''")}',[System.Drawing.Imaging.ImageFormat]::Png); ` +
|
|
172
|
+
`$g.Dispose(); $bmp.Dispose(); $img.Dispose()`,
|
|
173
|
+
];
|
|
174
|
+
return new Promise((resolve, reject) => {
|
|
175
|
+
const which = process.platform === "win32" ? "powershell" : null;
|
|
176
|
+
if (!which) {
|
|
177
|
+
reject(new Error("这台机器不是 Windows,非 PNG 的参考图请先转成 PNG"));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
execFile(which, ps, { timeout: 30000, windowsHide: true }, (err) => {
|
|
181
|
+
if (err) reject(new Error(`系统转换失败:${err.message}`));
|
|
182
|
+
else resolve(dst);
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 读一张图 → { width, height, data };按路径+mtime 缓存。 */
|
|
188
|
+
export async function loadImage(filePath) {
|
|
189
|
+
const abs = path.resolve(filePath);
|
|
190
|
+
const st = fs.statSync(abs);
|
|
191
|
+
const hit = IMAGE_CACHE.get(abs);
|
|
192
|
+
if (hit && hit.mtime === st.mtimeMs) return hit;
|
|
193
|
+
let pngPath = abs;
|
|
194
|
+
if (!/\.png$/i.test(abs)) {
|
|
195
|
+
pngPath = path.join(os.tmpdir(), `draworld-${Buffer.from(abs).toString("hex").slice(-16)}.png`);
|
|
196
|
+
await convertToPng(abs, pngPath);
|
|
197
|
+
}
|
|
198
|
+
const img = decodePng(fs.readFileSync(pngPath));
|
|
199
|
+
const entry = { mtime: st.mtimeMs, ...img };
|
|
200
|
+
IMAGE_CACHE.set(abs, entry);
|
|
201
|
+
return entry;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ---------------------------------------------------------------- 纯算法(和前端同一套思路)
|
|
205
|
+
|
|
206
|
+
export function inkMask(data, w, h, threshold) {
|
|
207
|
+
const t = threshold === undefined ? 0.45 : Math.max(0, Math.min(1, Number(threshold)));
|
|
208
|
+
const mask = new Uint8Array(w * h);
|
|
209
|
+
for (let i = 0, p = 0; p < w * h; p += 1, i += 4) {
|
|
210
|
+
const a = data[i + 3];
|
|
211
|
+
if (a < 24) continue;
|
|
212
|
+
const lum = (0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]) / 255;
|
|
213
|
+
if (lum < t) mask[p] = 1;
|
|
214
|
+
}
|
|
215
|
+
return mask;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function blurMask(mask, w, h) {
|
|
219
|
+
const out = new Uint8Array(w * h);
|
|
220
|
+
for (let y = 0; y < h; y += 1) {
|
|
221
|
+
for (let x = 0; x < w; x += 1) {
|
|
222
|
+
let n = 0;
|
|
223
|
+
for (let dy = -1; dy <= 1; dy += 1) {
|
|
224
|
+
for (let dx = -1; dx <= 1; dx += 1) {
|
|
225
|
+
const nx = x + dx;
|
|
226
|
+
const ny = y + dy;
|
|
227
|
+
if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
|
|
228
|
+
n += mask[ny * w + nx];
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
out[y * w + x] = n >= 5 ? 1 : 0;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** 掩码边界 → 线段(半像素坐标,尺寸 2 倍网格)。边中点用整数 key,拼接不会错位。 */
|
|
238
|
+
export function marchingSquares(mask, w, h) {
|
|
239
|
+
const segs = [];
|
|
240
|
+
const edgePoint = (key, x, y) => {
|
|
241
|
+
if (key === "t") return [x * 2 + 1, y * 2];
|
|
242
|
+
if (key === "r") return [x * 2 + 2, y * 2 + 1];
|
|
243
|
+
if (key === "b") return [x * 2 + 1, y * 2 + 2];
|
|
244
|
+
return [x * 2, y * 2 + 1];
|
|
245
|
+
};
|
|
246
|
+
const push = (a, b) => segs.push([a, b]);
|
|
247
|
+
for (let y = 0; y < h - 1; y += 1) {
|
|
248
|
+
for (let x = 0; x < w - 1; x += 1) {
|
|
249
|
+
const v0 = mask[y * w + x];
|
|
250
|
+
const v1 = mask[y * w + x + 1];
|
|
251
|
+
const v2 = mask[(y + 1) * w + x + 1];
|
|
252
|
+
const v3 = mask[(y + 1) * w + x];
|
|
253
|
+
const code = (v0 << 3) | (v1 << 2) | (v2 << 1) | v3;
|
|
254
|
+
if (code === 0 || code === 15) continue;
|
|
255
|
+
const T = edgePoint("t", x, y);
|
|
256
|
+
const R = edgePoint("r", x, y);
|
|
257
|
+
const B = edgePoint("b", x, y);
|
|
258
|
+
const L = edgePoint("l", x, y);
|
|
259
|
+
switch (code) {
|
|
260
|
+
case 1: case 14: push(L, B); break;
|
|
261
|
+
case 2: case 13: push(B, R); break;
|
|
262
|
+
case 3: case 12: push(L, R); break;
|
|
263
|
+
case 4: case 11: push(T, R); break;
|
|
264
|
+
case 6: case 9: push(T, B); break;
|
|
265
|
+
case 7: case 8: push(L, T); break;
|
|
266
|
+
case 5: push(L, T); push(B, R); break;
|
|
267
|
+
case 10: push(T, R); push(L, B); break;
|
|
268
|
+
default: break;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return segs;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export function stitchSegments(segs) {
|
|
276
|
+
const keyOf = (p) => `${p[0]},${p[1]}`;
|
|
277
|
+
const byKey = new Map();
|
|
278
|
+
segs.forEach((seg, i) => {
|
|
279
|
+
for (const p of seg) {
|
|
280
|
+
const k = keyOf(p);
|
|
281
|
+
const list = byKey.get(k);
|
|
282
|
+
if (list) list.push(i);
|
|
283
|
+
else byKey.set(k, [i]);
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
const used = new Set();
|
|
287
|
+
const lines = [];
|
|
288
|
+
for (let i = 0; i < segs.length; i += 1) {
|
|
289
|
+
if (used.has(i)) continue;
|
|
290
|
+
used.add(i);
|
|
291
|
+
const line = [segs[i][0], segs[i][1]];
|
|
292
|
+
for (;;) {
|
|
293
|
+
const tailKey = keyOf(line[line.length - 1]);
|
|
294
|
+
const next = (byKey.get(tailKey) || []).find((j) => !used.has(j));
|
|
295
|
+
if (next === undefined) break;
|
|
296
|
+
used.add(next);
|
|
297
|
+
const seg = segs[next];
|
|
298
|
+
const p = keyOf(seg[0]) === tailKey ? seg[1] : seg[0];
|
|
299
|
+
line.push(p);
|
|
300
|
+
if (keyOf(p) === keyOf(line[0])) break;
|
|
301
|
+
}
|
|
302
|
+
for (;;) {
|
|
303
|
+
const headKey = keyOf(line[0]);
|
|
304
|
+
const prev = (byKey.get(headKey) || []).find((j) => !used.has(j));
|
|
305
|
+
if (prev === undefined) break;
|
|
306
|
+
used.add(prev);
|
|
307
|
+
const seg = segs[prev];
|
|
308
|
+
const p = keyOf(seg[0]) === headKey ? seg[1] : seg[0];
|
|
309
|
+
line.unshift(p);
|
|
310
|
+
if (keyOf(p) === keyOf(line[line.length - 1])) break;
|
|
311
|
+
}
|
|
312
|
+
if (line.length > 1) lines.push(line);
|
|
313
|
+
}
|
|
314
|
+
return lines;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Zhang-Suen 细化:厚墨迹缩成 1px 骨架。 */
|
|
318
|
+
export function thinning(mask, w, h) {
|
|
319
|
+
const img = Uint8Array.from(mask);
|
|
320
|
+
const at = (x, y) => (x < 0 || y < 0 || x >= w || y >= h ? 0 : img[y * w + x]);
|
|
321
|
+
let changed = true;
|
|
322
|
+
let guard = 0;
|
|
323
|
+
while (changed && guard < 40) {
|
|
324
|
+
guard += 1;
|
|
325
|
+
changed = false;
|
|
326
|
+
for (let step = 0; step < 2; step += 1) {
|
|
327
|
+
const del = [];
|
|
328
|
+
for (let y = 1; y < h - 1; y += 1) {
|
|
329
|
+
for (let x = 1; x < w - 1; x += 1) {
|
|
330
|
+
if (!img[y * w + x]) continue;
|
|
331
|
+
const p2 = at(x, y - 1);
|
|
332
|
+
const p3 = at(x + 1, y - 1);
|
|
333
|
+
const p4 = at(x + 1, y);
|
|
334
|
+
const p5 = at(x + 1, y + 1);
|
|
335
|
+
const p6 = at(x, y + 1);
|
|
336
|
+
const p7 = at(x - 1, y + 1);
|
|
337
|
+
const p8 = at(x - 1, y);
|
|
338
|
+
const p9 = at(x - 1, y - 1);
|
|
339
|
+
const B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
|
|
340
|
+
if (B < 2 || B > 6) continue;
|
|
341
|
+
const seq = [p2, p3, p4, p5, p6, p7, p8, p9, p2];
|
|
342
|
+
let a = 0;
|
|
343
|
+
for (let i = 0; i < 8; i += 1) if (seq[i] === 0 && seq[i + 1] === 1) a += 1;
|
|
344
|
+
if (a !== 1) continue;
|
|
345
|
+
if (step === 0) {
|
|
346
|
+
if (p2 * p4 * p6 !== 0) continue;
|
|
347
|
+
if (p4 * p6 * p8 !== 0) continue;
|
|
348
|
+
} else {
|
|
349
|
+
if (p2 * p4 * p8 !== 0) continue;
|
|
350
|
+
if (p2 * p6 * p8 !== 0) continue;
|
|
351
|
+
}
|
|
352
|
+
del.push(y * w + x);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (del.length > 0) {
|
|
356
|
+
changed = true;
|
|
357
|
+
for (const p of del) img[p] = 0;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return img;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** 骨架 → 折线:先走端点,再走剩下的环。 */
|
|
365
|
+
export function skeletonPaths(skel, w, h) {
|
|
366
|
+
const deg = new Uint8Array(w * h);
|
|
367
|
+
const N8 = [[-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0]];
|
|
368
|
+
for (let y = 0; y < h; y += 1) {
|
|
369
|
+
for (let x = 0; x < w; x += 1) {
|
|
370
|
+
if (!skel[y * w + x]) continue;
|
|
371
|
+
let d = 0;
|
|
372
|
+
for (const [dx, dy] of N8) {
|
|
373
|
+
const nx = x + dx;
|
|
374
|
+
const ny = y + dy;
|
|
375
|
+
if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
|
|
376
|
+
if (skel[ny * w + nx]) d += 1;
|
|
377
|
+
}
|
|
378
|
+
deg[y * w + x] = d;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const visited = new Uint8Array(w * h);
|
|
382
|
+
const paths = [];
|
|
383
|
+
const walk = (sx, sy) => {
|
|
384
|
+
const path = [[sx, sy]];
|
|
385
|
+
visited[sy * w + sx] = 1;
|
|
386
|
+
let x = sx;
|
|
387
|
+
let y = sy;
|
|
388
|
+
for (;;) {
|
|
389
|
+
let next = null;
|
|
390
|
+
for (const [dx, dy] of N8) {
|
|
391
|
+
const nx = x + dx;
|
|
392
|
+
const ny = y + dy;
|
|
393
|
+
if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
|
|
394
|
+
const q = ny * w + nx;
|
|
395
|
+
if (skel[q] && !visited[q]) {
|
|
396
|
+
next = [nx, ny];
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
if (!next) break;
|
|
401
|
+
visited[next[1] * w + next[0]] = 1;
|
|
402
|
+
path.push(next);
|
|
403
|
+
x = next[0];
|
|
404
|
+
y = next[1];
|
|
405
|
+
}
|
|
406
|
+
return path;
|
|
407
|
+
};
|
|
408
|
+
for (let y = 0; y < h; y += 1) {
|
|
409
|
+
for (let x = 0; x < w; x += 1) {
|
|
410
|
+
const p = y * w + x;
|
|
411
|
+
if (skel[p] && deg[p] === 1 && !visited[p]) paths.push(walk(x, y));
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
for (let y = 0; y < h; y += 1) {
|
|
415
|
+
for (let x = 0; x < w; x += 1) {
|
|
416
|
+
const p = y * w + x;
|
|
417
|
+
if (skel[p] && !visited[p]) paths.push(walk(x, y));
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return paths;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
export function rdp(points, tolerance) {
|
|
424
|
+
if (points.length <= 2 || !(tolerance > 0)) return points;
|
|
425
|
+
const keep = new Uint8Array(points.length);
|
|
426
|
+
keep[0] = 1;
|
|
427
|
+
keep[points.length - 1] = 1;
|
|
428
|
+
const stack = [[0, points.length - 1]];
|
|
429
|
+
while (stack.length) {
|
|
430
|
+
const [first, last] = stack.pop();
|
|
431
|
+
const ax = points[first][0];
|
|
432
|
+
const ay = points[first][1];
|
|
433
|
+
const bx = points[last][0];
|
|
434
|
+
const by = points[last][1];
|
|
435
|
+
const dx = bx - ax;
|
|
436
|
+
const dy = by - ay;
|
|
437
|
+
const len = Math.hypot(dx, dy) || 1e-6;
|
|
438
|
+
let index = -1;
|
|
439
|
+
let best = tolerance;
|
|
440
|
+
for (let i = first + 1; i < last; i += 1) {
|
|
441
|
+
const px = points[i][0] - ax;
|
|
442
|
+
const py = points[i][1] - ay;
|
|
443
|
+
const dist = Math.abs(px * dy - py * dx) / len;
|
|
444
|
+
if (dist > best) {
|
|
445
|
+
best = dist;
|
|
446
|
+
index = i;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
if (index >= 0) {
|
|
450
|
+
keep[index] = 1;
|
|
451
|
+
stack.push([first, index], [index, last]);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return points.filter((_, i) => keep[i]);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
export function chaikin(pts, closed) {
|
|
458
|
+
const n = pts.length;
|
|
459
|
+
if (n < 3) return pts;
|
|
460
|
+
const out = [];
|
|
461
|
+
if (!closed) out.push(pts[0]);
|
|
462
|
+
const limit = closed ? n : n - 1;
|
|
463
|
+
for (let i = 0; i < limit; i += 1) {
|
|
464
|
+
const p = pts[i];
|
|
465
|
+
const q = pts[(i + 1) % n];
|
|
466
|
+
out.push([p[0] * 0.75 + q[0] * 0.25, p[1] * 0.75 + q[1] * 0.25]);
|
|
467
|
+
out.push([p[0] * 0.25 + q[0] * 0.75, p[1] * 0.25 + q[1] * 0.75]);
|
|
468
|
+
}
|
|
469
|
+
if (!closed) out.push(pts[n - 1]);
|
|
470
|
+
return out;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export function smoothPath(pts, closed, iterations) {
|
|
474
|
+
const iters = Math.max(0, Math.min(3, Number(iterations) || 0));
|
|
475
|
+
if (iters === 0 || pts.length < 3) return pts;
|
|
476
|
+
let s = pts;
|
|
477
|
+
for (let k = 0; k < iters; k += 1) s = chaikin(s, closed);
|
|
478
|
+
return rdp(s, 0.6);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
export function bezierPoint(seg, t) {
|
|
482
|
+
const mt = 1 - t;
|
|
483
|
+
const b0 = mt * mt * mt;
|
|
484
|
+
const b1 = 3 * t * mt * mt;
|
|
485
|
+
const b2 = 3 * t * t * mt;
|
|
486
|
+
const b3 = t * t * t;
|
|
487
|
+
return [
|
|
488
|
+
seg[0][0] * b0 + seg[1][0] * b1 + seg[2][0] * b2 + seg[3][0] * b3,
|
|
489
|
+
seg[0][1] * b0 + seg[1][1] * b1 + seg[2][1] * b2 + seg[3][1] * b3,
|
|
490
|
+
];
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export function fitBezier(points, tolerance) {
|
|
494
|
+
const tol = Math.max(0.2, Number(tolerance) || 1);
|
|
495
|
+
const pts = points.filter((p) => Array.isArray(p) && Number.isFinite(p[0]));
|
|
496
|
+
const segs = [];
|
|
497
|
+
if (pts.length < 2) return segs;
|
|
498
|
+
const unit = (a, b) => {
|
|
499
|
+
const dx = b[0] - a[0];
|
|
500
|
+
const dy = b[1] - a[1];
|
|
501
|
+
const n = Math.hypot(dx, dy) || 1;
|
|
502
|
+
return [dx / n, dy / n];
|
|
503
|
+
};
|
|
504
|
+
const fitOne = (p, t1, t2) => {
|
|
505
|
+
const last = p.length - 1;
|
|
506
|
+
const u = [0];
|
|
507
|
+
for (let i = 1; i <= last; i += 1) u.push(u[i - 1] + (Math.hypot(p[i][0] - p[i - 1][0], p[i][1] - p[i - 1][1]) || 1e-4));
|
|
508
|
+
const total = u[last] || 1;
|
|
509
|
+
for (let i = 0; i <= last; i += 1) u[i] /= total;
|
|
510
|
+
const C = [[0, 0], [0, 0]];
|
|
511
|
+
const X = [0, 0];
|
|
512
|
+
for (let i = 0; i <= last; i += 1) {
|
|
513
|
+
const t = u[i];
|
|
514
|
+
const mt = 1 - t;
|
|
515
|
+
const b0 = mt * mt * mt;
|
|
516
|
+
const b1 = 3 * t * mt * mt;
|
|
517
|
+
const b2 = 3 * t * t * mt;
|
|
518
|
+
const b3 = t * t * t;
|
|
519
|
+
const a1 = [t1[0] * b1, t1[1] * b1];
|
|
520
|
+
const a2 = [t2[0] * b2, t2[1] * b2];
|
|
521
|
+
C[0][0] += a1[0] * a1[0] + a1[1] * a1[1];
|
|
522
|
+
C[0][1] += a1[0] * a2[0] + a1[1] * a2[1];
|
|
523
|
+
C[1][0] = C[0][1];
|
|
524
|
+
C[1][1] += a2[0] * a2[0] + a2[1] * a2[1];
|
|
525
|
+
const px = p[i][0] - (p[0][0] * (b0 + b1) + p[last][0] * (b2 + b3));
|
|
526
|
+
const py = p[i][1] - (p[0][1] * (b0 + b1) + p[last][1] * (b2 + b3));
|
|
527
|
+
X[0] += a1[0] * px + a1[1] * py;
|
|
528
|
+
X[1] += a2[0] * px + a2[1] * py;
|
|
529
|
+
}
|
|
530
|
+
const det = C[0][0] * C[1][1] - C[0][1] * C[1][0];
|
|
531
|
+
let a1 = 0;
|
|
532
|
+
let a2 = 0;
|
|
533
|
+
if (Math.abs(det) > 1e-9) {
|
|
534
|
+
a1 = (X[0] * C[1][1] - X[1] * C[0][1]) / det;
|
|
535
|
+
a2 = (C[0][0] * X[1] - C[1][0] * X[0]) / det;
|
|
536
|
+
}
|
|
537
|
+
const chord = Math.hypot(p[last][0] - p[0][0], p[last][1] - p[0][1]) || 1;
|
|
538
|
+
if (!(a1 > chord * 0.02)) a1 = chord / 3;
|
|
539
|
+
if (!(a2 > chord * 0.02)) a2 = chord / 3;
|
|
540
|
+
const seg = [
|
|
541
|
+
p[0],
|
|
542
|
+
[p[0][0] + t1[0] * a1, p[0][1] + t1[1] * a1],
|
|
543
|
+
[p[last][0] + t2[0] * a2, p[last][1] + t2[1] * a2],
|
|
544
|
+
p[last],
|
|
545
|
+
];
|
|
546
|
+
let maxErr = 0;
|
|
547
|
+
let maxIdx = Math.floor(last / 2);
|
|
548
|
+
for (let i = 1; i < last; i += 1) {
|
|
549
|
+
const q = bezierPoint(seg, u[i]);
|
|
550
|
+
const d = Math.hypot(q[0] - p[i][0], q[1] - p[i][1]);
|
|
551
|
+
if (d > maxErr) {
|
|
552
|
+
maxErr = d;
|
|
553
|
+
maxIdx = i;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
return { seg, maxErr, maxIdx };
|
|
557
|
+
};
|
|
558
|
+
const fitRange = (s, e, t1, t2, depth) => {
|
|
559
|
+
const p = pts.slice(s, e + 1);
|
|
560
|
+
if (p.length === 2) {
|
|
561
|
+
const c1 = [p[0][0] + (p[1][0] - p[0][0]) / 3, p[0][1] + (p[1][1] - p[0][1]) / 3];
|
|
562
|
+
const c2 = [p[0][0] + (p[1][0] - p[0][0]) * 2 / 3, p[0][1] + (p[1][1] - p[0][1]) * 2 / 3];
|
|
563
|
+
segs.push([p[0], c1, c2, p[1]]);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
const r = fitOne(p, t1, t2);
|
|
567
|
+
if (r.maxErr <= tol || p.length <= 3 || depth >= 12) {
|
|
568
|
+
segs.push(r.seg);
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
const k = s + Math.max(1, Math.min(p.length - 2, r.maxIdx));
|
|
572
|
+
const center = unit(pts[k - 1], pts[k + 1]);
|
|
573
|
+
fitRange(s, k, t1, [-center[0], -center[1]], depth + 1);
|
|
574
|
+
fitRange(k, e, [center[0], center[1]], t2, depth + 1);
|
|
575
|
+
};
|
|
576
|
+
fitRange(0, pts.length - 1, unit(pts[0], pts[1]), unit(pts[pts.length - 1], pts[pts.length - 2]), 0);
|
|
577
|
+
return segs;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
export function bezierSample(segs, step, cap) {
|
|
581
|
+
const out = [];
|
|
582
|
+
if (!Array.isArray(segs) || segs.length === 0) return out;
|
|
583
|
+
const max = Math.max(8, Number(cap) || 400);
|
|
584
|
+
for (const seg of segs) {
|
|
585
|
+
const len = Math.hypot(seg[1][0] - seg[0][0], seg[1][1] - seg[0][1])
|
|
586
|
+
+ Math.hypot(seg[2][0] - seg[1][0], seg[2][1] - seg[1][1])
|
|
587
|
+
+ Math.hypot(seg[3][0] - seg[2][0], seg[3][1] - seg[2][1]);
|
|
588
|
+
const n = Math.max(2, Math.min(64, Math.ceil(len / Math.max(1, Number(step) || 3))));
|
|
589
|
+
for (let i = out.length ? 1 : 0; i <= n; i += 1) {
|
|
590
|
+
const q = bezierPoint(seg, i / n);
|
|
591
|
+
out.push([q[0], q[1]]);
|
|
592
|
+
if (out.length >= max) return out;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return out;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
export function polygonArea(pts) {
|
|
599
|
+
let a = 0;
|
|
600
|
+
for (let i = 0, j = pts.length - 1; i < pts.length; j = i, i += 1) {
|
|
601
|
+
a += pts[j][0] * pts[i][1] - pts[i][0] * pts[j][1];
|
|
602
|
+
}
|
|
603
|
+
return Math.abs(a) / 2;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
export function pointInPolygon(x, y, pts) {
|
|
607
|
+
let inside = false;
|
|
608
|
+
for (let i = 0, j = pts.length - 1; i < pts.length; j = i, i += 1) {
|
|
609
|
+
const xi = pts[i][0];
|
|
610
|
+
const yi = pts[i][1];
|
|
611
|
+
const xj = pts[j][0];
|
|
612
|
+
const yj = pts[j][1];
|
|
613
|
+
if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi || 1e-9) + xi) inside = !inside;
|
|
614
|
+
}
|
|
615
|
+
return inside;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
export function pathWidths(mask, w, h, paths) {
|
|
619
|
+
return paths.map((path) => {
|
|
620
|
+
if (!path || path.length < 2) return 0;
|
|
621
|
+
const samples = Math.min(12, path.length);
|
|
622
|
+
const values = [];
|
|
623
|
+
for (let k = 0; k < samples; k += 1) {
|
|
624
|
+
const idx = Math.floor((k * (path.length - 1)) / Math.max(1, samples - 1));
|
|
625
|
+
const p = path[idx];
|
|
626
|
+
const q = path[Math.min(path.length - 1, idx + 1)];
|
|
627
|
+
const r = path[Math.max(0, idx - 1)];
|
|
628
|
+
const dx = q[0] - r[0];
|
|
629
|
+
const dy = q[1] - r[1];
|
|
630
|
+
const len = Math.hypot(dx, dy) || 1;
|
|
631
|
+
const nx = -dy / len;
|
|
632
|
+
const ny = dx / len;
|
|
633
|
+
let n = 1;
|
|
634
|
+
for (const sign of [1, -1]) {
|
|
635
|
+
for (let step = 1; step <= 8; step += 1) {
|
|
636
|
+
const px = Math.round(p[0] + nx * step * sign);
|
|
637
|
+
const py = Math.round(p[1] + ny * step * sign);
|
|
638
|
+
if (px < 0 || py < 0 || px >= w || py >= h) break;
|
|
639
|
+
if (!mask[py * w + px]) break;
|
|
640
|
+
n += 1;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
values.push(n);
|
|
644
|
+
}
|
|
645
|
+
values.sort((a, b) => a - b);
|
|
646
|
+
return values[Math.floor(values.length / 2)];
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
export function kmeansColors(data, k, stepPx = 2) {
|
|
651
|
+
const samples = [];
|
|
652
|
+
for (let i = 0; i < data.length; i += 4 * stepPx) {
|
|
653
|
+
if (data[i + 3] < 16) continue;
|
|
654
|
+
samples.push([data[i], data[i + 1], data[i + 2]]);
|
|
655
|
+
}
|
|
656
|
+
if (samples.length === 0) throw new Error("这块区域里没有不透明的像素");
|
|
657
|
+
const kk = Math.max(2, Math.min(8, Math.round(k)));
|
|
658
|
+
const buckets = new Map();
|
|
659
|
+
for (const s of samples) {
|
|
660
|
+
const key = ((s[0] >> 3) << 10) | ((s[1] >> 3) << 5) | (s[2] >> 3);
|
|
661
|
+
const cur = buckets.get(key) || { r: 0, g: 0, b: 0, n: 0 };
|
|
662
|
+
cur.r += s[0];
|
|
663
|
+
cur.g += s[1];
|
|
664
|
+
cur.b += s[2];
|
|
665
|
+
cur.n += 1;
|
|
666
|
+
buckets.set(key, cur);
|
|
667
|
+
}
|
|
668
|
+
const init = [...buckets.values()].sort((a, b) => b.n - a.n).slice(0, kk).map((b) => [b.r / b.n, b.g / b.n, b.b / b.n]);
|
|
669
|
+
while (init.length < kk && samples.length > init.length) init.push(samples[init.length * 7 % samples.length].slice());
|
|
670
|
+
let centers = init;
|
|
671
|
+
for (let iter = 0; iter < 10; iter += 1) {
|
|
672
|
+
const acc = centers.map(() => ({ r: 0, g: 0, b: 0, n: 0 }));
|
|
673
|
+
for (const s of samples) {
|
|
674
|
+
let best = 0;
|
|
675
|
+
let bestD = Infinity;
|
|
676
|
+
for (let c = 0; c < centers.length; c += 1) {
|
|
677
|
+
const d = (s[0] - centers[c][0]) ** 2 + (s[1] - centers[c][1]) ** 2 + (s[2] - centers[c][2]) ** 2;
|
|
678
|
+
if (d < bestD) {
|
|
679
|
+
bestD = d;
|
|
680
|
+
best = c;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
const a = acc[best];
|
|
684
|
+
a.r += s[0];
|
|
685
|
+
a.g += s[1];
|
|
686
|
+
a.b += s[2];
|
|
687
|
+
a.n += 1;
|
|
688
|
+
}
|
|
689
|
+
centers = acc.map((a, i) => (a.n ? [a.r / a.n, a.g / a.n, a.b / a.n] : centers[i]));
|
|
690
|
+
}
|
|
691
|
+
return centers.map((c) => ({
|
|
692
|
+
hex: toHex(Math.round(c[0]), Math.round(c[1]), Math.round(c[2])),
|
|
693
|
+
rgb: c.map((v) => Math.round(v)),
|
|
694
|
+
ratio: samples.length ? 100 : 0,
|
|
695
|
+
}));
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
export function toHex(r, g, b) {
|
|
699
|
+
const h = (v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0");
|
|
700
|
+
return `#${h(r)}${h(g)}${h(b)}`;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/** 参考图 → 折线(和前端 traceInk 同一套参数)。 */
|
|
704
|
+
export function traceInk(imageData, w, h, opts = {}) {
|
|
705
|
+
const center = opts.mode === "center";
|
|
706
|
+
const tolerance = Math.max(0.5, Number(opts.tolerance) || (center ? 1.2 : 2.5));
|
|
707
|
+
const minLength = Math.max(2, Number(opts.minLength) || 12);
|
|
708
|
+
const maxLines = Math.max(1, Number(opts.maxLines) || 80);
|
|
709
|
+
const maxPointsPerLine = Math.max(6, Number(opts.maxPointsPerLine) || 160);
|
|
710
|
+
const smoothIters = Math.max(0, Math.min(3, opts.smooth === undefined ? 1 : Number(opts.smooth) || 0));
|
|
711
|
+
const wantFit = opts.fit === true;
|
|
712
|
+
const fitStep = Math.max(1.5, Number(opts.fitStep) || 3);
|
|
713
|
+
const mask = inkMask(imageData, w, h, opts.threshold);
|
|
714
|
+
let lines;
|
|
715
|
+
if (center) {
|
|
716
|
+
const skel = thinning(mask, w, h);
|
|
717
|
+
lines = skeletonPaths(skel, w, h).map((pts) => pts.map((p) => [p[0] * 2, p[1] * 2]));
|
|
718
|
+
} else {
|
|
719
|
+
lines = stitchSegments(marchingSquares(blurMask(mask, w, h), w, h));
|
|
720
|
+
}
|
|
721
|
+
const out = [];
|
|
722
|
+
const closedFlags = [];
|
|
723
|
+
let dropped = 0;
|
|
724
|
+
for (const raw of lines) {
|
|
725
|
+
const pts = raw.map((p) => [p[0] / 2, p[1] / 2]);
|
|
726
|
+
const a = pts[0];
|
|
727
|
+
const b = pts[pts.length - 1];
|
|
728
|
+
const closed = pts.length > 3 && Math.hypot(a[0] - b[0], a[1] - b[1]) < 1.5;
|
|
729
|
+
if (closed) pts.pop();
|
|
730
|
+
let len = 0;
|
|
731
|
+
for (let i = 1; i < pts.length; i += 1) len += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
|
|
732
|
+
if (len < minLength) {
|
|
733
|
+
dropped += 1;
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
let simplified = rdp(pts, tolerance);
|
|
737
|
+
if (wantFit && simplified.length >= 3) {
|
|
738
|
+
const sampled = bezierSample(fitBezier(simplified, Math.max(0.3, tolerance * 0.9)), fitStep, maxPointsPerLine * 2);
|
|
739
|
+
if (sampled.length >= 2) {
|
|
740
|
+
// 闭合环拟合容易外冲,夹回画布内,否则色块 bbox 会虚大
|
|
741
|
+
simplified = sampled.map((p) => [
|
|
742
|
+
Math.max(0, Math.min(w - 1, p[0])),
|
|
743
|
+
Math.max(0, Math.min(h - 1, p[1])),
|
|
744
|
+
]);
|
|
745
|
+
}
|
|
746
|
+
} else if (smoothIters > 0) {
|
|
747
|
+
simplified = smoothPath(simplified, closed, smoothIters);
|
|
748
|
+
}
|
|
749
|
+
if (simplified.length > maxPointsPerLine) {
|
|
750
|
+
const stepN = Math.ceil(simplified.length / maxPointsPerLine);
|
|
751
|
+
simplified = simplified.filter((_, i) => i % stepN === 0 || i === simplified.length - 1);
|
|
752
|
+
}
|
|
753
|
+
out.push(simplified.map((p) => [Number(p[0].toFixed(1)), Number(p[1].toFixed(1))]));
|
|
754
|
+
closedFlags.push(closed);
|
|
755
|
+
if (out.length >= maxLines) break;
|
|
756
|
+
}
|
|
757
|
+
const points = out.reduce((n, l) => n + l.length, 0);
|
|
758
|
+
return { paths: out, closed: closedFlags, mode: center ? "center" : "edge", mask, lines: out.length, points, dropped, tolerance, smooth: smoothIters, fit: wantFit };
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// ---------------------------------------------------------------- 光栅化
|
|
762
|
+
|
|
763
|
+
function parseColor(hex) {
|
|
764
|
+
const s = String(hex || "#111111").replace("#", "");
|
|
765
|
+
const n = s.length === 3 ? s.split("").map((c) => c + c).join("") : s;
|
|
766
|
+
return [parseInt(n.slice(0, 2), 16) || 0, parseInt(n.slice(2, 4), 16) || 0, parseInt(n.slice(4, 6), 16) || 0];
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function makeSurface(w, h) {
|
|
770
|
+
return { w, h, data: new Uint8ClampedArray(w * h * 4) };
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function blendPixel(surf, x, y, rgb, alpha) {
|
|
774
|
+
if (x < 0 || y < 0 || x >= surf.w || y >= surf.h) return;
|
|
775
|
+
const i = (y * surf.w + x) * 4;
|
|
776
|
+
const d = surf.data;
|
|
777
|
+
const a = alpha <= 0 ? 0 : alpha >= 1 ? 1 : alpha;
|
|
778
|
+
d[i] = d[i] * (1 - a) + rgb[0] * a;
|
|
779
|
+
d[i + 1] = d[i + 1] * (1 - a) + rgb[1] * a;
|
|
780
|
+
d[i + 2] = d[i + 2] * (1 - a) + rgb[2] * a;
|
|
781
|
+
d[i + 3] = Math.max(d[i + 3], Math.round(255 * a));
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** 圆头胶囊笔触(近似浏览器里的实心笔刷)。 */
|
|
785
|
+
function strokeCapsule(surf, pts, radius, rgb, alpha) {
|
|
786
|
+
const r = Math.max(0.6, radius);
|
|
787
|
+
for (let i = 0; i < pts.length - 1; i += 1) {
|
|
788
|
+
const a = pts[i];
|
|
789
|
+
const b = pts[i + 1];
|
|
790
|
+
const d = Math.hypot(b[0] - a[0], b[1] - a[1]);
|
|
791
|
+
const steps = Math.max(1, Math.ceil(d / Math.max(0.8, r * 0.6)));
|
|
792
|
+
for (let s = 0; s <= steps; s += 1) {
|
|
793
|
+
const t = s / steps;
|
|
794
|
+
const cx = a[0] + (b[0] - a[0]) * t;
|
|
795
|
+
const cy = a[1] + (b[1] - a[1]) * t;
|
|
796
|
+
const x0 = Math.floor(cx - r);
|
|
797
|
+
const x1 = Math.ceil(cx + r);
|
|
798
|
+
const y0 = Math.floor(cy - r);
|
|
799
|
+
const y1 = Math.ceil(cy + r);
|
|
800
|
+
for (let y = y0; y <= y1; y += 1) {
|
|
801
|
+
for (let x = x0; x <= x1; x += 1) {
|
|
802
|
+
if (Math.hypot(x - cx, y - cy) <= r) blendPixel(surf, x, y, rgb, alpha);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/** 多边形填充(even-odd,支持洞)。 */
|
|
810
|
+
function fillPolygon(surf, outer, holes, rgb, alpha) {
|
|
811
|
+
const rings = [outer, ...(Array.isArray(holes) ? holes.filter((h) => h && h.length >= 3) : [])];
|
|
812
|
+
let minY = Infinity;
|
|
813
|
+
let maxY = -Infinity;
|
|
814
|
+
for (const r of rings) {
|
|
815
|
+
for (const p of r) {
|
|
816
|
+
if (p[1] < minY) minY = p[1];
|
|
817
|
+
if (p[1] > maxY) maxY = p[1];
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
const y0 = Math.max(0, Math.floor(minY));
|
|
821
|
+
const y1 = Math.min(surf.h - 1, Math.ceil(maxY));
|
|
822
|
+
for (let y = y0; y <= y1; y += 1) {
|
|
823
|
+
const cy = y + 0.5;
|
|
824
|
+
const xs = [];
|
|
825
|
+
for (const r of rings) {
|
|
826
|
+
for (let i = 0, j = r.length - 1; i < r.length; j = i, i += 1) {
|
|
827
|
+
const a = r[j];
|
|
828
|
+
const b = r[i];
|
|
829
|
+
if ((a[1] > cy) === (b[1] > cy)) continue;
|
|
830
|
+
xs.push(a[0] + ((cy - a[1]) * (b[0] - a[0])) / ((b[1] - a[1]) || 1e-9));
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
xs.sort((p, q) => p - q);
|
|
834
|
+
for (let k = 0; k + 1 < xs.length; k += 2) {
|
|
835
|
+
const sx = Math.max(0, Math.round(xs[k]));
|
|
836
|
+
const ex = Math.min(surf.w - 1, Math.round(xs[k + 1]));
|
|
837
|
+
for (let x = sx; x <= ex; x += 1) blendPixel(surf, x, y, rgb, alpha);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/** 把一张图按 x,y,w,h 画进 surface(最近邻缩放)。 */
|
|
843
|
+
export function blitImage(surf, img, x, y, w, h) {
|
|
844
|
+
const dw = Math.max(1, Math.round(w));
|
|
845
|
+
const dh = Math.max(1, Math.round(h));
|
|
846
|
+
for (let j = 0; j < dh; j += 1) {
|
|
847
|
+
for (let i = 0; i < dw; i += 1) {
|
|
848
|
+
const sx = Math.min(img.width - 1, Math.floor((i * img.width) / dw));
|
|
849
|
+
const sy = Math.min(img.height - 1, Math.floor((j * img.height) / dh));
|
|
850
|
+
const si = (sy * img.width + sx) * 4;
|
|
851
|
+
const a = img.data[si + 3] / 255;
|
|
852
|
+
blendPixel(surf, Math.round(x) + i, Math.round(y) + j, [img.data[si], img.data[si + 1], img.data[si + 2]], a);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/**
|
|
858
|
+
* 文档 → 位图。opts.withImages=false 时不画图片层,opts.onlyImage 只画某张图片层。
|
|
859
|
+
*/
|
|
860
|
+
export async function rasterDoc(doc, opts = {}) {
|
|
861
|
+
const w = doc.width || 1024;
|
|
862
|
+
const h = doc.height || 1024;
|
|
863
|
+
const surf = makeSurface(w, h);
|
|
864
|
+
const withImages = opts.withImages !== false;
|
|
865
|
+
for (const layer of doc.layers || []) {
|
|
866
|
+
if (layer.visible === false) continue;
|
|
867
|
+
const lo = layer.opacity === undefined ? 1 : Math.max(0, Math.min(1, Number(layer.opacity)));
|
|
868
|
+
if (layer.image) {
|
|
869
|
+
if (!withImages) continue;
|
|
870
|
+
const img = await loadImage(opts.resolve(layer.image.file));
|
|
871
|
+
blitImage(surf, img, layer.image.x || 0, layer.image.y || 0, layer.image.w || img.width, layer.image.h || img.height);
|
|
872
|
+
continue;
|
|
873
|
+
}
|
|
874
|
+
for (const s of layer.strokes || []) {
|
|
875
|
+
const rgb = parseColor(s.color);
|
|
876
|
+
const so = s.opacity === undefined ? 1 : Math.max(0, Math.min(1, Number(s.opacity)));
|
|
877
|
+
const alpha = lo * so;
|
|
878
|
+
if (s.mode === "fill") {
|
|
879
|
+
fillPolygon(surf, s.points || [], s.holes || [], rgb, alpha);
|
|
880
|
+
} else {
|
|
881
|
+
const size = Number(s.size) || 8;
|
|
882
|
+
strokeCapsule(surf, s.points || [], size / 2, rgb, alpha);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
return surf;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
export function cropSurface(surf, rect) {
|
|
890
|
+
const x = Math.max(0, Math.round(rect.x));
|
|
891
|
+
const y = Math.max(0, Math.round(rect.y));
|
|
892
|
+
const w = Math.min(surf.w - x, Math.round(rect.w));
|
|
893
|
+
const h = Math.min(surf.h - y, Math.round(rect.h));
|
|
894
|
+
const out = makeSurface(w, h);
|
|
895
|
+
for (let j = 0; j < h; j += 1) {
|
|
896
|
+
for (let i = 0; i < w; i += 1) {
|
|
897
|
+
const si = ((y + j) * surf.w + (x + i)) * 4;
|
|
898
|
+
const di = (j * w + i) * 4;
|
|
899
|
+
out.data[di] = surf.data[si];
|
|
900
|
+
out.data[di + 1] = surf.data[si + 1];
|
|
901
|
+
out.data[di + 2] = surf.data[si + 2];
|
|
902
|
+
out.data[di + 3] = surf.data[si + 3];
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
return out;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/** 最近邻放大。 */
|
|
909
|
+
export function zoomSurface(surf, zoom) {
|
|
910
|
+
const z = Math.max(1, Math.round(zoom));
|
|
911
|
+
if (z === 1) return surf;
|
|
912
|
+
const out = makeSurface(surf.w * z, surf.h * z);
|
|
913
|
+
for (let y = 0; y < out.h; y += 1) {
|
|
914
|
+
for (let x = 0; x < out.w; x += 1) {
|
|
915
|
+
const si = ((y / z | 0) * surf.w + (x / z | 0)) * 4;
|
|
916
|
+
const di = (y * out.w + x) * 4;
|
|
917
|
+
out.data[di] = surf.data[si];
|
|
918
|
+
out.data[di + 1] = surf.data[si + 1];
|
|
919
|
+
out.data[di + 2] = surf.data[si + 2];
|
|
920
|
+
out.data[di + 3] = surf.data[si + 3];
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
return out;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
export { makeSurface };
|